MarketCustomerResourcesController.cs 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927
  1. using Aspose.Cells;
  2. using EyeSoft.Extensions;
  3. using OASystem.API.OAMethodLib;
  4. using OASystem.Domain.AesEncryption;
  5. using OASystem.Domain.Attributes;
  6. using OASystem.Domain.Dtos.CRM;
  7. using OASystem.Domain.Entities.Customer;
  8. using OASystem.Domain.ViewModels.CRM;
  9. using OASystem.Infrastructure.Repositories.CRM;
  10. using OASystem.RedisRepository;
  11. using System.Collections;
  12. using System.Data;
  13. using System.Diagnostics;
  14. using System.Net;
  15. using UAParser;
  16. namespace OASystem.API.Controllers
  17. {
  18. /// <summary>
  19. /// 市场客户资料
  20. /// </summary>
  21. [Route("api/[controller]/[action]")]
  22. public class MarketCustomerResourcesController : ControllerBase
  23. {
  24. private readonly NewClientDataRepository _clientDataRepository;
  25. private readonly SqlSugarClient _sqlSugar;
  26. private string keyName = "newClient_SearchKey";
  27. /// <summary>
  28. /// 初始化
  29. /// </summary>
  30. public MarketCustomerResourcesController(NewClientDataRepository clientDataRepository, SqlSugarClient sqlSugar)
  31. {
  32. this._clientDataRepository = clientDataRepository;
  33. _sqlSugar = sqlSugar;
  34. }
  35. /// <summary>
  36. /// 客户资料数据
  37. /// 基础数据
  38. /// </summary>
  39. /// <returns></returns>
  40. [HttpPost]
  41. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  42. public async Task<IActionResult> MarketCustomerInit(MarketCustomerInitDto dto)
  43. {
  44. JsonView jw = new JsonView();
  45. try
  46. {
  47. Result resultData = await _clientDataRepository._Init(dto);
  48. if (resultData.Code == 0)
  49. {
  50. jw = JsonView(true, "查询成功!", resultData.Data);
  51. }
  52. else
  53. {
  54. jw = JsonView(false, resultData.Msg);
  55. }
  56. }
  57. catch (Exception)
  58. {
  59. jw = JsonView(false, "程序错误!");
  60. }
  61. return Ok(jw);
  62. }
  63. /// <summary>
  64. /// 查询客户资料数据
  65. /// </summary>
  66. /// <returns></returns>
  67. [HttpPost]
  68. //[ApiLog("Crm_NewClientData", OperationEnum.List)]
  69. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  70. public async Task<IActionResult> QueryNewClientData(NewClientDataQueryDto dto)
  71. {
  72. #region 参数验证
  73. if (dto.OperationUserId < 0)
  74. return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
  75. if (dto.PortType < 0)
  76. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  77. #endregion
  78. JsonView jw = new JsonView();
  79. var startTime = DateTime.UtcNow;
  80. try
  81. {
  82. Result resultData = await _clientDataRepository.QueryNewClientData(dto);
  83. if (resultData.Code == 0)
  84. {
  85. #region 客户资料表操作记录
  86. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.NoOperation, dto.OperationUserId, 0, "");
  87. #endregion
  88. jw = JsonView(true, resultData.Msg, resultData.Data);
  89. }
  90. else
  91. {
  92. jw = JsonView(false, resultData.Msg);
  93. }
  94. }
  95. catch (Exception)
  96. {
  97. jw = JsonView(false, "程序错误!");
  98. }
  99. finally
  100. {
  101. using var ssg = _sqlSugar.CopyNew();
  102. var status = HttpContext.Response.StatusCode.ToString();
  103. _ = Task.Run(async () =>
  104. {
  105. try
  106. {
  107. string remoteIp = string.Empty,
  108. location = string.Empty;
  109. // 检查请求头中的X-Forwarded-For,以获取真实的客户端IP地址
  110. if (HttpContext.Request.Headers.ContainsKey("X-Forwarded-For"))
  111. {
  112. remoteIp = HttpContext.Request.Headers["X-Forwarded-For"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)[0];
  113. }
  114. else
  115. {
  116. remoteIp = HttpContext.Connection.RemoteIpAddress?.ToString();
  117. }
  118. var task = GetIpInfo(remoteIp);
  119. string deviceType = string.Empty, browser = string.Empty, os = string.Empty;
  120. var userAgent = HttpContext.Request.Headers["User-Agent"].FirstOrDefault();
  121. if (!string.IsNullOrEmpty(userAgent))
  122. {
  123. // 解析User-Agent头
  124. var parser = Parser.GetDefault();
  125. var client = parser.Parse(userAgent);
  126. // 提取浏览器信息
  127. browser = client.UA.Family; // 浏览器名称
  128. var browserVersion = client.UA.Major + "." + client.UA.Minor + "." + client.UA.Patch; // 浏览器版本
  129. browser += $"({browserVersion})";
  130. // 提取操作系统信息
  131. os = client.OS.Family; // 操作系统名称
  132. var osVersion = string.Empty; // 操作系统版本
  133. if (!string.IsNullOrEmpty(client.OS.Major)) osVersion += client.OS.Major;
  134. if (!string.IsNullOrEmpty(client.OS.Minor)) osVersion += "." + client.OS.Minor;
  135. if (!string.IsNullOrEmpty(client.OS.Patch)) osVersion += "." + client.OS.Patch;
  136. if (!string.IsNullOrEmpty(osVersion)) os += $"({osVersion})";
  137. // 提取设备信息
  138. deviceType = client.Device.Family; // 设备类型,如 'mobile', 'tablet', 'desktop' 等
  139. }
  140. // 记录请求结束时间
  141. var endTime = DateTime.UtcNow;
  142. // 计算耗时
  143. var duration = (long)(endTime - startTime).TotalMilliseconds;
  144. //等待任务进行
  145. (remoteIp, location) = await task;
  146. //单独记录操作
  147. var logInfo = new Crm_TableOperationRecord()
  148. {
  149. TableName = "Crm_NewClientData",
  150. PortType = dto.PortType,
  151. OperationItem = OperationEnum.List,
  152. DataId = 0,
  153. RequestUrl = "/api/MarketCustomerResources/QueryNewClientData",
  154. RemoteIp = remoteIp,
  155. Location = location,
  156. RequestParam = JsonConvert.SerializeObject(dto),
  157. ReturnResult = JsonConvert.SerializeObject(jw),
  158. Elapsed = duration,
  159. Status = status,
  160. CreateUserId = dto.OperationUserId,
  161. UpdatePreData = "",
  162. UpdateBefData = "",
  163. Browser = browser,
  164. Os = os,
  165. DeviceType = deviceType,
  166. };
  167. // 存储到数据库
  168. await ssg.Insertable(logInfo).ExecuteCommandAsync();
  169. }
  170. catch (Exception ex)
  171. {
  172. }
  173. });
  174. }
  175. return Ok(jw);
  176. }
  177. /// <summary>
  178. /// 客户资料数据
  179. /// Details
  180. /// </summary>
  181. /// <returns></returns>
  182. [HttpPost]
  183. [ApiLog("Crm_NewClientData", OperationEnum.Details)]
  184. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  185. public async Task<IActionResult> PostNewClientDataDetails(NewClientDataDetailsDto dto)
  186. {
  187. #region 参数验证
  188. if (dto.Id < 0)
  189. return Ok(JsonView(false, "请传入有效的Id参数!"));
  190. if (dto.UserId < 0)
  191. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  192. if (dto.PortType < 0)
  193. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  194. #endregion
  195. JsonView jw = new JsonView();
  196. try
  197. {
  198. Result resultData = await _clientDataRepository._Details(dto.PortType, dto.Id);
  199. if (resultData.Code == 0)
  200. {
  201. #region 客户资料表操作记录
  202. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Details, dto.UserId, dto.Id, "");
  203. #endregion
  204. jw = JsonView(true, "查询成功!", resultData.Data);
  205. }
  206. else
  207. {
  208. jw = JsonView(false, resultData.Msg);
  209. }
  210. }
  211. catch (Exception)
  212. {
  213. jw = JsonView(false, "程序错误!");
  214. }
  215. return Ok(jw);
  216. }
  217. /// <summary>
  218. /// 客户资料操作(Status:1.新增,2.修改)
  219. /// </summary>
  220. /// <param name="dto"></param>
  221. /// <returns></returns>
  222. [HttpPost]
  223. [ApiLog("Crm_NewClientData", OperationEnum.NoOperation)]
  224. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  225. public async Task<IActionResult> NewClientOp(NewClientOpDto dto)
  226. {
  227. #region 参数验证
  228. if (dto.CreateUserId < 0)
  229. {
  230. return Ok(JsonView(false, "请传入有效的CreateUserId参数!"));
  231. }
  232. if (dto.PortType < 0)
  233. {
  234. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  235. }
  236. #endregion
  237. try
  238. {
  239. Domain.Result result = await _clientDataRepository.NewClientOp(dto);
  240. if (result.Code != 0)
  241. {
  242. return Ok(JsonView(false, result.Msg));
  243. }
  244. #region 客户资料操作记录
  245. //OperationEnum operationEnum = OperationEnum.NoOperation;
  246. //if (dto.Status == 1)
  247. //{
  248. // operationEnum = OperationEnum.Add;
  249. // dto.Id = Convert.ToInt32(result.Data);
  250. //}
  251. //else if (dto.Status == 2) operationEnum = OperationEnum.Edit;
  252. //await GeneralMethod.NewClientOperationRecord(dto.PortType, operationEnum, dto.CreateUserId, dto.Id, "");
  253. #endregion
  254. //this.keyName += "_" + dto.CreateUserId;
  255. //var exists = await RedisFactory.CreateRedisRepository().KeyExistsAsync(keyName);
  256. //if (exists) await RedisFactory.CreateRedisRepository().KeyDeleteAsync(keyName);
  257. return Ok(JsonView(true, result.Msg + "Id:" + dto.Id));
  258. }
  259. catch (Exception ex)
  260. {
  261. return Ok(JsonView(false, "程序错误!Msg:" + ex.Message));
  262. }
  263. }
  264. /// <summary>
  265. /// 新客户资料操作(删除)
  266. /// </summary>
  267. /// <param name="dto"></param>
  268. /// <returns></returns>
  269. [HttpPost]
  270. [ApiLog("Crm_NewClientData", OperationEnum.Del)]
  271. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  272. public async Task<IActionResult> NewClientDel(DelBaseDto dto)
  273. {
  274. #region 参数验证
  275. if (dto.Id < 0)
  276. {
  277. return Ok(JsonView(false, "请传入有效的Id参数!"));
  278. }
  279. if (dto.DeleteUserId < 0)
  280. {
  281. return Ok(JsonView(false, "请传入有效的DeleteUserId参数!"));
  282. }
  283. if (dto.PortType < 0)
  284. {
  285. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  286. }
  287. #endregion
  288. var res = await _clientDataRepository.DelNewClientData(dto);
  289. if (res.Code != 0)
  290. {
  291. return Ok(JsonView(false, "删除失败"));
  292. }
  293. #region 客户资料表操作记录
  294. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Del, dto.DeleteUserId, dto.Id, "");
  295. #endregion
  296. //this.keyName += "_" + dto.DeleteUserId;
  297. //var exists = await RedisFactory.CreateRedisRepository().KeyExistsAsync(keyName);
  298. //if (exists) await RedisFactory.CreateRedisRepository().KeyDeleteAsync(keyName);
  299. return Ok(JsonView(true, "删除成功!"));
  300. }
  301. /// <summary>
  302. /// 获取下拉列表数据和单条数据信息
  303. /// </summary>
  304. /// <param name="dto"></param>
  305. /// <returns></returns>
  306. [HttpPost]
  307. [ApiLog("Crm_NewClientData", OperationEnum.Details)]
  308. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  309. public async Task<IActionResult> QuerySelectAndSingleData(QuerySingleDto dto)
  310. {
  311. JsonView jw = new JsonView();
  312. var result = await _clientDataRepository.QuerySelectAndSingleData(dto);
  313. if (result.Code == 0)
  314. {
  315. #region 客户资料表操作记录
  316. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Details, dto.UserId, dto.Id, "");
  317. #endregion
  318. jw = JsonView(true, result.Msg, result.Data);
  319. }
  320. else
  321. {
  322. jw = JsonView(false, result.Msg);
  323. }
  324. return Ok(jw);
  325. }
  326. /// <summary>
  327. /// 获取现有负责人
  328. /// </summary>
  329. /// <returns></returns>
  330. [HttpPost]
  331. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  332. public async Task<IActionResult> QueryUserSelect()
  333. {
  334. Result resTable = _clientDataRepository.QueryUserSelect();
  335. return Ok(JsonView(true, resTable.Msg, resTable.Data));
  336. }
  337. /// <summary>
  338. /// 获取出团数据
  339. /// </summary>
  340. /// <returns></returns>
  341. [HttpPost]
  342. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  343. public async Task<IActionResult> QueryNumberGroups()
  344. {
  345. var result = await _clientDataRepository.QueryNumberGroups();
  346. if (result.Code != 0)
  347. {
  348. return Ok(JsonView(false, result.Msg));
  349. }
  350. return Ok(JsonView(true, result.Msg, result.Data));
  351. }
  352. /// <summary>
  353. /// 新客户资料操作
  354. /// 批量分配
  355. /// </summary>
  356. /// <param name="dto"></param>
  357. /// <returns></returns>
  358. [HttpPost]
  359. [ApiLog("Crm_NewClientData", OperationEnum.BatchAssignment)]
  360. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  361. public async Task<IActionResult> PostBatchAssignment(BatchAssignmentDto dto)
  362. {
  363. #region 参数验证
  364. if (dto.UserId < 0)
  365. {
  366. return Ok(JsonView(false, "请传入有效的UserId参数!"));
  367. }
  368. if (dto.PortType < 0)
  369. {
  370. return Ok(JsonView(false, "请传入有效的PortType参数!"));
  371. }
  372. #endregion
  373. var res = await _clientDataRepository._BatchAssignment(dto);
  374. if (res.Code != 0)
  375. {
  376. return Ok(JsonView(false, res.Msg));
  377. }
  378. return Ok(JsonView(true, "操作成功!"));
  379. }
  380. private Dictionary<int, List<int>> MCRSetting()
  381. {
  382. Dictionary<int, List<int>> keyValuePairs = new Dictionary<int, List<int>>();
  383. keyValuePairs.Add(419, new List<int>() //四川
  384. {
  385. 376,377,378,381,382,387,388,389,390,753,754,1296,1303
  386. });
  387. keyValuePairs.Add(420, new List<int>() //云南
  388. {
  389. 407,408,409,410,449,451,452,453,567,754,1297,1304
  390. });
  391. keyValuePairs.Add(421, new List<int>() { 424, 425, 426, 427, 428, 429, 754, 1298, 1305, 1307, 1306 }); // 贵州
  392. keyValuePairs.Add(422, new List<int>() { 415, 416, 754, 1317, 1316, 1315, 455, 1321, 1320, 1319, 1318 }); // 西藏
  393. keyValuePairs.Add(423, new List<int>() { 417, 418, 454, 456, 754, 1313, 1314 }); // 重庆
  394. keyValuePairs.Add(578, new List<int>() { 581, 582, 583, 754, 1299, 1300 }); // 青海
  395. keyValuePairs.Add(605, new List<int>() { 588, 589, 590, 591, 592, 593, 754, 1301, 1310, 1309, 1308 }); // 陕西
  396. keyValuePairs.Add(606, new List<int>() { 597, 598, 599, 600, 601, 602, 603, 604, 754, 1324, 1323, 1322 }); // 宁夏
  397. keyValuePairs.Add(625, new List<int>() { 617, 618, 619, 620, 621, 622, 622, 623, 624, 754, 1302, 1312, 1311 }); // 甘肃
  398. keyValuePairs.Add(634, new List<int>() { 630, 631, 632, 633, 754 }); // 新疆
  399. return keyValuePairs;
  400. }
  401. private Dictionary<int, List<int>> MCRSecondSetting()
  402. {
  403. Dictionary<int, List<int>> keyValuePairs = new Dictionary<int, List<int>>();
  404. // 四川
  405. keyValuePairs.Add(349, new List<int>() { 376, 378, 381, 387, 389, 1296 }); // 四川省级
  406. keyValuePairs.Add(350, new List<int>() { 377, 382, 388, 390, 1303 }); // 成都市级
  407. keyValuePairs.Add(348, new List<int>() { 387 }); // 四川地市州 - Explicitly assigning to ensure all source2 IDs are used
  408. keyValuePairs.Add(701, new List<int>() { 388 }); // 成都区市县
  409. // 云南
  410. keyValuePairs.Add(399, new List<int>() { 407, 408, 409, 410, 451 }); // 云南省级
  411. keyValuePairs.Add(400, new List<int>() { 449, 452, 453, 1297, 1304 }); // 昆明市级
  412. keyValuePairs.Add(450, new List<int>() { 410 }); // 云南地市州
  413. keyValuePairs.Add(566, new List<int>() { 567 }); // 昆明区市县
  414. // 贵州
  415. keyValuePairs.Add(401, new List<int>() { 424, 426, 427, 428, 1298 }); // 贵州省级
  416. keyValuePairs.Add(402, new List<int>() { 425, 429, 1306, 1307, 1305 }); // 贵阳市级
  417. keyValuePairs.Add(414, new List<int>() { 428 }); // 贵州地市州
  418. //keyValuePairs.Add(1305, new List<int>() { /* Add relevant IDs if available */ }); // 贵阳区市县 - Placeholder for now
  419. // 重庆
  420. keyValuePairs.Add(403, new List<int>() { 417, 418, 454, 456, 1314 }); // 重庆市级
  421. keyValuePairs.Add(404, new List<int>() { 1313 }); // 重庆区县 - No direct match in source1
  422. // 西藏
  423. keyValuePairs.Add(405, new List<int>() { 415, 1317, 1316, 1315 }); // 西藏自治区
  424. keyValuePairs.Add(406, new List<int>() { 455, 1321, 1320, 1319, 1318 }); // 拉萨市级
  425. keyValuePairs.Add(413, new List<int>() { 416 }); // 西藏地市州
  426. // 青海
  427. keyValuePairs.Add(579, new List<int>() { 581, 582, 583, 1300 }); // 青海省级
  428. keyValuePairs.Add(580, new List<int>() { 1299 }); // 青海市州县 (Includes 地市州)
  429. // 陕西
  430. keyValuePairs.Add(585, new List<int>() { 588, 589, 590, 591, 1301 }); // 陕西省级
  431. keyValuePairs.Add(586, new List<int>() { 589 }); // 陕西地市州
  432. keyValuePairs.Add(587, new List<int>() { 592, 593, 1309, 1310, 1308 }); // 西安市级
  433. //keyValuePairs.Add(1308, new List<int>() { /* Add relevant IDs if available */ }); // 西安区市县 - Placeholder
  434. // 宁夏
  435. keyValuePairs.Add(594, new List<int>() { 597, 598, 599, 600, 601, 1322 }); // 宁夏自治区 (Includes 地市州 and 区级)
  436. keyValuePairs.Add(595, new List<int>() { 597 }); // 宁夏地市州
  437. keyValuePairs.Add(596, new List<int>() { 598, 599, 600, 603, 604, 602, 1323, 1324 }); // 银川市级 (Includes 区级)
  438. //keyValuePairs.Add(602, new List<int>()); // 银川区市县 - No direct match, but could be considered covered by "区级"
  439. // 甘肃
  440. keyValuePairs.Add(614, new List<int>() { 617, 618, 619, 620, 621, 1302 }); // 甘肃省级
  441. keyValuePairs.Add(615, new List<int>() { 618 }); // 甘肃地市州
  442. keyValuePairs.Add(616, new List<int>() { 622, 623, 624, 1312, 1311 }); // 兰州市级
  443. //keyValuePairs.Add(1311, new List<int>() { /* Add relevant IDs if available */ }); // 兰州区市县 - Placeholder
  444. // 新疆
  445. keyValuePairs.Add(627, new List<int>() { 630, 631, 632, 1327, 1326, 1325 }); // 新疆自治区级
  446. keyValuePairs.Add(628, new List<int>() { 1326 }); // 新疆地市州 - No direct match
  447. keyValuePairs.Add(629, new List<int>() { 633, 1331, 1330, 1329, 1328 }); // 乌鲁木齐市级
  448. // 中央直属企业 (Special case)
  449. keyValuePairs.Add(351, new List<int>() { 754 }); // Using "未分级" for 中央直属企业
  450. return keyValuePairs;
  451. }
  452. private Dictionary<int, List<int>> MCRLvSetting()
  453. {
  454. var keyValuePairs = new Dictionary<int, List<int>>();
  455. // 四川 (419)
  456. keyValuePairs.Add(419, new List<int>() { 348, 349, 350, 701 }); // Includes all Sichuan-related IDs from source2
  457. // 云南 (420)
  458. keyValuePairs.Add(420, new List<int>() { 399, 400, 450, 566 }); // Includes all Yunnan-related IDs
  459. // 贵州 (421)
  460. keyValuePairs.Add(421, new List<int>() { 401, 402, 414 });
  461. // 西藏 (422)
  462. keyValuePairs.Add(422, new List<int>() { 405, 406, 413 });
  463. // 重庆 (423)
  464. keyValuePairs.Add(423, new List<int>() { 403, 404 });
  465. // 青海 (578)
  466. keyValuePairs.Add(578, new List<int>() { 579, 580, 626 }); // Includes 市州县 and 西宁市级
  467. // 陕西 (605)
  468. keyValuePairs.Add(605, new List<int>() { 585, 586, 587 });
  469. // 宁夏 (606)
  470. keyValuePairs.Add(606, new List<int>() { 594, 595, 596 });
  471. // 甘肃 (625)
  472. keyValuePairs.Add(625, new List<int>() { 614, 615, 616 });
  473. // 新疆 (634)
  474. keyValuePairs.Add(634, new List<int>() { 627, 628, 629 });
  475. // 未分级 (351) - You'll likely want to remove this as it's no longer a primary key.
  476. // keyValuePairs.Add(351, new List<int>()); //Remove this line.
  477. return keyValuePairs;
  478. }
  479. [HttpPost]
  480. public IActionResult QueryClientType(QueryClientTypeDto Dto)
  481. {
  482. var jw = JsonView(true, "获取成功!");
  483. var dic_lv = MCRLvSetting();
  484. var keyValuePairs = MCRSetting();
  485. ArrayList arr = new ArrayList();
  486. ArrayList lvArr = new ArrayList();
  487. var ids = new List<int>();
  488. var lvids = new List<int>();
  489. foreach (var item in Dto.SetDataIdArr)
  490. {
  491. if (keyValuePairs.Keys.Contains(item))
  492. {
  493. ids.AddRange(keyValuePairs[item]);
  494. }
  495. if (dic_lv.Keys.Contains(item))
  496. {
  497. lvids.AddRange(dic_lv[item]);
  498. }
  499. }
  500. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  501. .Where(u => ids.Contains(u.Id) && u.IsDel == 0)
  502. .Select(x => new { x.Id, x.Name, x.Remark })
  503. .ToList());
  504. if (arr.Count == 0)
  505. {
  506. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  507. .Where(u => u.STid == 37 && u.IsDel == 0)
  508. .Select(x => new { x.Id, x.Name, x.Remark }).ToList());
  509. }
  510. // 创建比较器实例
  511. IComparer remakeComparer = new RemakeComparer();
  512. // 使用ArrayList.Sort方法和自定义比较器对arr进行排序
  513. arr.Sort(remakeComparer);
  514. var rangelv = _sqlSugar.Queryable<Sys_SetData>()
  515. .Where(u => lvids.Contains(u.Id) && u.IsDel == 0)
  516. .Select(x => new { x.Id, x.Name })
  517. .ToList();
  518. lvArr.AddRange(rangelv);
  519. if (lvArr.Count == 0)
  520. {
  521. lvArr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  522. .Where(u => u.STid == 33 && u.IsDel == 0)
  523. .Select(x => new { x.Id, x.Name }).ToList());
  524. }
  525. jw.Data = new
  526. {
  527. TypeArr = arr,
  528. LvArr = lvArr,
  529. };
  530. return Ok(jw);
  531. }
  532. [HttpPost]
  533. public IActionResult QueryClientTypeSecond(QueryClientTypeDto Dto)
  534. {
  535. var jw = JsonView(true, "获取成功!");
  536. var keyValuePairs = MCRSecondSetting();
  537. ArrayList arr = new ArrayList();
  538. var ids = new List<int>();
  539. foreach (var item in Dto.SetDataIdArr)
  540. {
  541. if (keyValuePairs.Keys.Contains(item))
  542. {
  543. ids.AddRange(keyValuePairs[item]);
  544. }
  545. }
  546. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  547. .Where(u => ids.Contains(u.Id) && u.IsDel == 0)
  548. .Select(x => new { x.Id, x.Name, x.Remark })
  549. .ToList());
  550. if (arr.Count == 0)
  551. {
  552. arr.AddRange(_sqlSugar.Queryable<Sys_SetData>()
  553. .Where(u => u.STid == 37 && u.IsDel == 0)
  554. .Select(x => new { x.Id, x.Name, x.Remark }).ToList());
  555. }
  556. // 创建比较器实例
  557. IComparer remakeComparer = new RemakeComparer();
  558. // 使用ArrayList.Sort方法和自定义比较器对arr进行排序
  559. arr.Sort(remakeComparer);
  560. jw.Data = arr;
  561. return Ok(jw);
  562. }
  563. /// <summary>
  564. /// 客户资料数据 全信息导出 excel 下载
  565. /// </summary>
  566. /// <param name="dto"></param>
  567. /// <returns></returns>
  568. [HttpPost]
  569. [ApiLog("Crm_NewClientData", OperationEnum.Download)]
  570. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  571. public async Task<IActionResult> NewClientDataExcelDownload(NewClientDataExcelDownloadDto dto)
  572. {
  573. #region 参数验证
  574. if (dto.OperationUserId < 0) return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
  575. if (dto.PortType < 0) return Ok(JsonView(false, "请传入有效的PortType参数!"));
  576. if (dto.PageId < 0) return Ok(JsonView(false, "请传入有效的PageId参数!"));
  577. #endregion
  578. #region 页面操作权限验证
  579. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.OperationUserId, dto.PageId);
  580. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  581. #endregion
  582. var dt = await _clientDataRepository.NewClientDataExcelDownload(dto);
  583. if (dt != null)
  584. {
  585. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/公司客户资料导出模板.xlsx");
  586. var designer = new WorkbookDesigner();
  587. designer.Workbook = new Workbook(tempPath);
  588. designer.SetDataSource("NCDDT", dt);
  589. designer.Process();
  590. //文件名
  591. string fileName = $"公司客户资料(全信息导出){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  592. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "NewClientDataExcelDownload/" + fileName);
  593. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/NewClientDataExcelDownload/" + fileName;
  594. #region 客户资料表操作记录
  595. var respose = JsonView(true, "成功", url);
  596. //var paramData = new
  597. //{
  598. // APIName = @"MarketCustomerResources/NewClientDataExcelDownload",
  599. // RequestParam = dto,
  600. // ResposeParam = respose
  601. //};
  602. //await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Download, dto.OperationUserId, 0, JsonConvert.SerializeObject(paramData));
  603. #endregion
  604. return Ok(respose);
  605. }
  606. return Ok(JsonView(false));
  607. }
  608. /// <summary>
  609. /// 客户资料数据 分权限导出 excel 下载
  610. /// </summary>
  611. /// <param name="dto"></param>
  612. /// <returns></returns>
  613. [HttpPost]
  614. [ApiLog("Crm_NewClientData", OperationEnum.Download)]
  615. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  616. public async Task<IActionResult> NewClientDataAuthorityExcelDownload(NewClientDataExcelDownloadDto dto)
  617. {
  618. #region 参数验证
  619. if (dto.OperationUserId < 0) return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
  620. if (dto.PortType < 0) return Ok(JsonView(false, "请传入有效的PortType参数!"));
  621. if (dto.PageId < 0) return Ok(JsonView(false, "请传入有效的PageId参数!"));
  622. #endregion
  623. #region 页面操作权限验证
  624. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.OperationUserId, dto.PageId);
  625. if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
  626. #endregion
  627. var dt = await _clientDataRepository.NewClientDataExcelDownload(dto);
  628. if (dt != null)
  629. {
  630. string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/公司客户资料分权限导出模板.xlsx");
  631. var designer = new WorkbookDesigner();
  632. designer.Workbook = new Workbook(tempPath);
  633. designer.SetDataSource("NCDDT", dt);
  634. designer.Process();
  635. //文件名
  636. string fileName = $"公司客户资料(分权限导出){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  637. designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "NewClientDataExcelDownload/" + fileName);
  638. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/NewClientDataExcelDownload/" + fileName;
  639. var respose = JsonView(true, "成功", url);
  640. return Ok(respose);
  641. }
  642. return Ok(JsonView(false));
  643. }
  644. /// <summary>
  645. /// 客户资料数据 历史记录 Init
  646. /// </summary>
  647. /// <param name="dto"></param>
  648. /// <returns></returns>
  649. [HttpPost]
  650. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  651. public async Task<IActionResult> NewClientDataRecordInit(NewClientDataRecordInitDto dto)
  652. {
  653. #region 参数验证
  654. if (dto.UserId < 0) return Ok(JsonView(false, MsgTips.UserId));
  655. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  656. if (dto.PageId < 0) return Ok(JsonView(false, MsgTips.PageId));
  657. #endregion
  658. #region 页面操作权限验证
  659. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  660. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  661. #endregion
  662. var enumfiltrates = new string[] { "NoOperation", "Audit", "Login" };
  663. var operations = EnumHelper.GetEnumDescriptions(typeof(OperationEnum), enumfiltrates);
  664. var operation1 = new List<dynamic>();
  665. foreach (var item in operations)
  666. {
  667. operation1.Add(new { value = item.Key, text = item.Value });
  668. }
  669. object userDatas = Array.Empty<object>();
  670. if (dto.UserId == 21)
  671. {
  672. var userIds = await _sqlSugar.Queryable<Crm_ClientDataAndUser>().Where(x => x.IsDel == 0).Select(x => x.usersId).Distinct().ToListAsync();
  673. if (userIds.Any())
  674. {
  675. userDatas = await _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && userIds.Contains(x.Id)).Select(x => new { value = x.Id, text = x.CnName }).ToListAsync();
  676. }
  677. }
  678. var data = new
  679. {
  680. operations = operation1,
  681. userDatas = userDatas
  682. };
  683. return Ok(JsonView(data));
  684. }
  685. /// <summary>
  686. /// 客户资料数据 历史记录
  687. /// </summary>
  688. /// <param name="dto"></param>
  689. /// <returns></returns>
  690. [HttpPost]
  691. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  692. public async Task<IActionResult> NewClientDataRecord(NewClientDataRecordDto dto)
  693. {
  694. #region 参数验证
  695. if (dto.UserId < 0) return Ok(JsonView(false, MsgTips.UserId));
  696. if (!SharingStaticData.PortTypes.Contains(dto.PortType)) return Ok(JsonView(false, MsgTips.Port));
  697. if (dto.PageId < 0) return Ok(JsonView(false, MsgTips.PageId));
  698. #endregion
  699. #region 页面操作权限验证
  700. var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
  701. if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
  702. #endregion
  703. return Ok(await _clientDataRepository.NewClientDataRecord(dto));
  704. }
  705. #region 修改数据
  706. //[HttpPost]
  707. //public IActionResult SynchronizationData()
  708. //{
  709. // var keyValuePairs = new Dictionary<int, List<string>>
  710. // {
  711. // { 5, new List<string> { "省级部门", "省级单位" } },
  712. // { 10, new List<string> { "市州" } },
  713. // { 15, new List<string> { "省属国企" } },
  714. // { 20, new List<string> { "省属学校", "省属高校" } },
  715. // { 25, new List<string> { "省级行业协会", "省级社团", "省级联合会" , "省属行业协会", "民营企业", "地方国企" } },
  716. // { 30, new List<string> { "市级部门", "市级单位" } },
  717. // { 35, new List<string> { "区市县" } },
  718. // { 40, new List<string> { "市级国企", "市属国企" } },
  719. // { 45, new List<string> { "市属学校", "市属高校" } },
  720. // { 50, new List<string> { "市级行业协会", "市级社团", "市级联合会" } }
  721. // };
  722. // var setting = MCRSetting();
  723. // var arr = new List<List<Sys_SetData>>();
  724. // foreach (var item in setting.Keys)
  725. // {
  726. // var setDataList_DB = _sqlSugar.Queryable<Sys_SetData>()
  727. // .Where(x => x.IsDel == 0 && setting[item].Contains(x.Id))
  728. // .ToList();
  729. // foreach (var setData in setDataList_DB)
  730. // {
  731. // foreach (var lv in keyValuePairs.Keys)
  732. // {
  733. // var islv = keyValuePairs[lv].Where(x => setData.Name.Contains(x)).Count() > 0;
  734. // if (islv)
  735. // {
  736. // setData.Remark = lv.ToString();
  737. // }
  738. // }
  739. // }
  740. // arr.Add(setDataList_DB);
  741. // }
  742. // _sqlSugar.Updateable(arr.SelectMany(x => x).ToList()).UpdateColumns(x => new
  743. // {
  744. // x.Remark
  745. // }).ExecuteCommand();
  746. // return Ok(arr);
  747. //}
  748. [HttpPost]
  749. public IActionResult QueryData()
  750. {
  751. var db = _sqlSugar.Queryable<Crm_NewClientData>()
  752. .Where(x => x.IsDel == 0)
  753. .Select(x => new Crm_NewClientData
  754. {
  755. Id = x.Id,
  756. Client = x.Client,
  757. Category = x.Category,
  758. Location = x.Location,
  759. }).ToList();
  760. var count = 0;
  761. var updateid = new List<int>();
  762. foreach (var item in db)
  763. {
  764. EncryptionProcessor.DecryptProperties(item);
  765. if (!string.IsNullOrWhiteSpace(item.Location) && item.Location.Contains("重庆") && item.Category == 0)
  766. {
  767. count++;
  768. //if (!string.IsNullOrWhiteSpace(item.Client) && (item.Client.Contains("大学") || item.Client.Contains("学院")))
  769. {
  770. updateid.Add(item.Id);
  771. }
  772. }
  773. }
  774. var updateCount = _sqlSugar.Updateable<Crm_NewClientData>().Where(x => updateid.Contains(x.Id))
  775. .SetColumns(x => new Crm_NewClientData { Category = 456 }).ExecuteCommand();
  776. return Ok(new
  777. {
  778. notCount = count,
  779. updateCount = updateCount
  780. });
  781. }
  782. [HttpPost]
  783. public IActionResult InsertData()
  784. {
  785. string sql = $@"SELECT * FROM [dbo].[Crm_NewClientData] WHERE ID IN (
  786. --所有四川省域的
  787. select Id from [dbo].[Crm_NewClientData] where ISDEL = 0 AND Lvlid IN (
  788. select S.Id from Sys_SetData S
  789. where STid = 33 and isdel = 0 and
  790. (Name like '%四%川%' or Name like '%成%都%')
  791. )
  792. ) AND IsDel = 0
  793. AND ID IN (
  794. SELECT NewClientDataId FROM [dbo].[Crm_ClientDataAndUser]
  795. WHERE NewClientDataId IN (
  796. --所有单独数据
  797. SELECT NewClientDataId FROM [dbo].[Crm_ClientDataAndUser]
  798. WHERE ISDEL = 0
  799. GROUP BY NewClientDataId
  800. HAVING COUNT(NewClientDataId) = 1
  801. ) AND IsDel = 0 AND UsersId = 21
  802. )";
  803. var clientList = _sqlSugar.SqlQueryable<Crm_NewClientData>(sql).Select(x => x.Id).ToList().Select(x => new Crm_ClientDataAndUser
  804. {
  805. NewClientDataId = x,
  806. usersId = 330,
  807. CreateTime = DateTime.Now,
  808. CreateUserId = 235,
  809. IsDel = 0,
  810. }).ToList();
  811. var insertCount = _sqlSugar.Insertable(clientList).ExecuteCommand();
  812. return Ok(insertCount);
  813. }
  814. [HttpPost]
  815. public IActionResult ExportData()
  816. {
  817. var soure = _sqlSugar.Queryable<Crm_NewClientData>()
  818. .InnerJoin<Crm_ClientDataAndUser>((a, b) => b.NewClientDataId == a.Id && b.IsDel == 0)
  819. .Where((a, b) => a.IsDel == 0 && b.usersId == 95)
  820. .Select((a, b) => a)
  821. .ToList();
  822. foreach (var item in soure)
  823. {
  824. EncryptionProcessor.DecryptProperties(item);
  825. }
  826. // 创建WorkbookDesigner对象
  827. WorkbookDesigner designer = new WorkbookDesigner();
  828. // 加载模板文件(包含智能标记)
  829. designer.Workbook = new Workbook("C:\\Users\\PC\\Desktop\\111.xlsx");
  830. // 设置数据源,这里假设你的List集合名为listData
  831. designer.SetDataSource("ListData", soure);
  832. // 处理智能标记以将数据填充到工作表中
  833. designer.Process();
  834. // 保存Excel文件
  835. designer.Workbook.Save("C:\\Users\\PC\\Desktop\\111000.xlsx");
  836. return Ok(1);
  837. }
  838. [HttpPost]
  839. public IActionResult DeleteData()
  840. {
  841. var soure = _sqlSugar.Queryable<Crm_NewClientData>()
  842. .InnerJoin<Crm_ClientDataAndUser>((a, b) => b.NewClientDataId == a.Id && b.IsDel == 0)
  843. .Where((a, b) => a.IsDel == 0 && b.usersId == 330)
  844. .Select((a, b) => b.Id)
  845. .ToList();
  846. var count = _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  847. .Where(u => soure.Contains(u.Id) && u.IsDel == 0)
  848. .SetColumns(x => new Crm_ClientDataAndUser
  849. {
  850. DeleteTime = DateTime.Now.ToString(),
  851. DeleteUserId = 235,
  852. IsDel = 1
  853. }).ExecuteCommand();
  854. return Ok(count);
  855. }
  856. [HttpPost]
  857. public IActionResult ReassignCustomers()
  858. {
  859. var user_Client = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  860. .Where(x => x.usersId == 302 && x.IsDel == 0)
  861. .Select(x => new
  862. {
  863. x.Id,
  864. x.NewClientDataId
  865. })
  866. .ToList();
  867. var ids = user_Client.Select(x => x.NewClientDataId).ToList();
  868. string setDataSql = $"select * from Sys_SetData where STid = 33 and isdel = 0 and (Name like '%重庆%') ";
  869. var setDataids = _sqlSugar.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();
  870. var clients = _sqlSugar.Queryable<Crm_NewClientData>().Where(x => ids.Contains(x.Id) && setDataids.Contains(x.Lvlid) && x.IsDel == 0).ToList();
  871. var clients_ids = clients.Select(x => x.Id).ToList();
  872. int updateCount = 0;
  873. _sqlSugar.BeginTran();
  874. if (clients.Count == 223)
  875. {
  876. updateCount = _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  877. .Where(x => x.usersId == 302 && clients_ids.Contains(x.NewClientDataId) && x.IsDel == 0)
  878. .SetColumns(x => new Crm_ClientDataAndUser
  879. {
  880. usersId = 21
  881. })
  882. .ExecuteCommand();
  883. }
  884. if (updateCount == clients.Count)
  885. {
  886. _sqlSugar.CommitTran();
  887. }
  888. else
  889. {
  890. _sqlSugar.RollbackTran();
  891. }
  892. return Ok(new
  893. {
  894. count = clients.Count,
  895. updateCount,
  896. });
  897. }
  898. [HttpPost]
  899. public IActionResult InsertDataJiang()
  900. {
  901. var list_DB = _sqlSugar.Queryable<Crm_NewClientData>().Where(x => x.IsDel == 0).ToList();
  902. foreach (var item in list_DB)
  903. {
  904. EncryptionProcessor.DecryptProperties(item);
  905. }
  906. list_DB = list_DB.Where(x => !string.IsNullOrWhiteSpace(x.Client) && (x.Client.Contains("学院") || x.Client.Contains("大学"))).ToList();
  907. var arr = list_DB.Select(x => x.Id).ToList().Select(x => new Crm_ClientDataAndUser
  908. {
  909. NewClientDataId = x,
  910. usersId = 327,
  911. CreateTime = DateTime.Now,
  912. CreateUserId = 235,
  913. IsDel = 0,
  914. }).ToList();
  915. var insertCount = _sqlSugar.Insertable(arr).ExecuteCommand();
  916. return Ok(insertCount);
  917. }
  918. [HttpPost]
  919. public IActionResult InsertDataGu()
  920. {
  921. string sql = @"SELECT * FROM Crm_NewClientData cncd WHERE IsDel = 0
  922. AND Lvlid in (
  923. select Id from Sys_SetData where STid = 33 and isdel = 0
  924. and (Name like '%云%南%' or Name like '%昆%明%')
  925. )";
  926. var list = _sqlSugar.SqlQueryable<Crm_NewClientData>(sql).Select(x => x.Id).ToList();
  927. var toUserList = new List<Crm_ClientDataAndUser>();
  928. foreach (var item in list)
  929. {
  930. toUserList.Add(new Crm_ClientDataAndUser
  931. {
  932. CreateTime = DateTime.Now,
  933. CreateUserId = 235,
  934. NewClientDataId = item,
  935. usersId = 364,
  936. IsDel = 0,
  937. });
  938. }
  939. var updateCount = 0;
  940. if (toUserList.Count == 327)
  941. {
  942. updateCount = _sqlSugar.Insertable(toUserList).ExecuteCommand();
  943. }
  944. return Ok(new
  945. {
  946. updateCount
  947. });
  948. }
  949. [HttpPost]
  950. public IActionResult CloneUserClient(CloneUserClientDto dto)
  951. {
  952. var list = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  953. .Where(x => x.IsDel == 0 && x.usersId == dto.UserId)
  954. .ToList();
  955. foreach (var item in list)
  956. {
  957. item.usersId = dto.ToUserId;
  958. }
  959. var count = _sqlSugar.Insertable<Crm_ClientDataAndUser>(list).ExecuteCommand();
  960. return Ok(new
  961. {
  962. count,
  963. });
  964. }
  965. #endregion
  966. /// <summary>
  967. /// 客户资料 操作记录记录查询
  968. /// </summary>
  969. /// <param name="userId"></param>
  970. /// <returns></returns>
  971. [HttpGet]
  972. [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
  973. public async Task<IActionResult> NewClientDataOperatingRrecord(int userId)
  974. {
  975. var datas = await _sqlSugar.Queryable<Crm_TableOperationRecord, Crm_NewClientData, Sys_Users>((tor, ncd, u) =>
  976. new JoinQueryInfos(
  977. JoinType.Left, tor.DataId == ncd.Id,
  978. JoinType.Left, tor.CreateUserId == u.Id
  979. ))
  980. .Where((tor, ncd, u) => tor.TableName == "Crm_NewClientData" && tor.CreateUserId == userId && (int)tor.OperationItem > 1)
  981. .Select((tor, ncd, u) => new
  982. {
  983. tor.PortType,
  984. tor.OperationItem,
  985. tor.DataId,
  986. ncd.Client,
  987. u.CnName,
  988. tor.CreateTime
  989. }).ToListAsync();
  990. var view = new List<dynamic>();
  991. if (datas.Any())
  992. {
  993. datas = datas.OrderByDescending(x => x.CreateTime).ToList();
  994. foreach (var item in datas)
  995. {
  996. var text = item.OperationItem.GetDescription();
  997. view.Add(new
  998. {
  999. Client = AesEncryptionHelper.Decrypt(item.Client),
  1000. item.PortType,
  1001. item.OperationItem,
  1002. text = text,
  1003. item.DataId,
  1004. item.CnName,
  1005. item.CreateTime
  1006. });
  1007. }
  1008. }
  1009. return Ok(JsonView(view));
  1010. }
  1011. [HttpPost]
  1012. public async Task<IActionResult> SearchClientByKeyword(SearchClientByKeywordDto dto)
  1013. {
  1014. var jw = JsonView(true);
  1015. var expression = Expressionable.Create<Crm_NewClientData>()
  1016. .And(x => x.IsDel == 0)
  1017. .AndIF(dto.Lvlid != 0, x => x.Lvlid == dto.Lvlid)
  1018. .AndIF(dto.Category != 0, x => x.Category == dto.Category);
  1019. if (dto.Range != 0)
  1020. {
  1021. var rangeSetDataList = await _clientDataRepository.GetCachedRangeSetDataAsync(dto.Range);
  1022. expression = expression.And(x => rangeSetDataList.Contains(x.Lvlid));
  1023. }
  1024. this.keyName += "_" + dto.UserId;
  1025. //获取个人的客户
  1026. if (dto.UserId != 21)
  1027. {
  1028. var userList = _clientDataRepository.GetNewExistClient(dto.UserId).Select(x => x.Id);
  1029. var newClientData = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1030. .Where(x => x.IsDel == 0 && userList.Contains(x.usersId))
  1031. .Select(x => x.NewClientDataId)
  1032. .Distinct()
  1033. .ToList();
  1034. expression = expression.And(x => newClientData.Contains(x.Id));
  1035. }
  1036. var exists = false;
  1037. //var exists = await RedisFactory.CreateRedisRepository().KeyExistsAsync(keyName);
  1038. //if (exists) exists = await RedisFactory.CreateRedisRepository().HashFieldExistAsync(keyName, dto.Keyword);
  1039. if (!exists)
  1040. {
  1041. string field = "Id,Client";
  1042. var newClitnData = _sqlSugar.Queryable<Crm_NewClientData>()
  1043. .Where(expression.ToExpression())
  1044. .Select(field)
  1045. .ToList();
  1046. foreach (var item in newClitnData)
  1047. {
  1048. EncryptionProcessor.DecryptProperties(item);
  1049. }
  1050. var keywordArray = dto.Keyword.ToCharArray();
  1051. var matches = newClitnData
  1052. .Where(fullString => !string.IsNullOrWhiteSpace(fullString.Client) &&
  1053. keywordArray.All(keyword => fullString.Client.Contains(keyword)))
  1054. .Select(x => new
  1055. {
  1056. x.Client,
  1057. x.Id
  1058. })
  1059. .DistinctBy(x => x.Client)
  1060. .ToList();
  1061. if (matches.Any())
  1062. {
  1063. //await RedisFactory.CreateRedisRepository().HashSetAsync(keyName, dto.Keyword, matches);
  1064. //await RedisFactory.CreateRedisRepository().KeyExpireInAsync(keyName, new TimeSpan(0,1,0));
  1065. jw.Data = matches;
  1066. }
  1067. else
  1068. {
  1069. jw.Code = 201;
  1070. jw.Msg = "empty list";
  1071. jw.Data = new List<string>(1);
  1072. }
  1073. }
  1074. else
  1075. {
  1076. jw.Data = await RedisFactory.CreateRedisRepository().HashGetAsync<List<string>>(keyName, dto.Keyword);
  1077. }
  1078. return Ok(jw);
  1079. }
  1080. [HttpGet("{userId}")]
  1081. public async Task<IActionResult> SearchClientByUserId(int userId)
  1082. {
  1083. var sw = Stopwatch.StartNew();
  1084. var jw = JsonView(true);
  1085. if (!await _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0 && x.Id == userId).AnyAsync())
  1086. {
  1087. jw.Code = StatusCodes.Status400BadRequest;
  1088. jw.Msg = $"请传入有效的UserId";
  1089. return Ok(jw);
  1090. }
  1091. var expression = Expressionable.Create<Crm_NewClientData>().And(x => x.IsDel == 0);
  1092. //获取个人的客户
  1093. if (userId != 21)
  1094. {
  1095. var userList = _clientDataRepository.GetNewExistClient(userId).Select(x => x.Id);
  1096. var newClientData = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1097. .Where(x => x.IsDel == 0 && userList.Contains(x.usersId))
  1098. .Select(x => x.NewClientDataId)
  1099. .Distinct()
  1100. .ToList();
  1101. expression = expression.And(x => newClientData.Contains(x.Id));
  1102. }
  1103. string field = "Id,Client";
  1104. var newClitnData = _sqlSugar.Queryable<Crm_NewClientData>()
  1105. .Where(expression.ToExpression())
  1106. .Select(field)
  1107. .ToList();
  1108. foreach (var item in newClitnData)
  1109. {
  1110. EncryptionProcessor.DecryptProperties(item);
  1111. }
  1112. var matches = newClitnData
  1113. .Where(fullString => !string.IsNullOrWhiteSpace(fullString.Client))
  1114. .OrderByDescending(x => x.Id)
  1115. .Select(x => new { x.Id, x.Client })
  1116. .DistinctBy(x => x.Client)
  1117. .ToList();
  1118. if (matches.Any())
  1119. {
  1120. jw.Data = matches;
  1121. jw.Count = matches.Count();
  1122. }
  1123. else
  1124. {
  1125. jw.Code = 201;
  1126. jw.Msg = "empty list";
  1127. jw.Data = new List<string>(1);
  1128. }
  1129. sw.Stop();
  1130. jw.Msg = $"操作成功!耗时:{sw.Elapsed.TotalMilliseconds}ms.";
  1131. return Ok(jw);
  1132. }
  1133. [HttpPost]
  1134. public async Task<IActionResult> QueryUnlockDropList()
  1135. {
  1136. var jw = JsonView(true);
  1137. var userList = await _sqlSugar.Queryable<Sys_SetData>().FirstAsync
  1138. (x => x.Id == 1434 && x.IsDel == 0);
  1139. try
  1140. {
  1141. if (userList != null)
  1142. {
  1143. var result = JsonConvert.DeserializeObject<List<int>>(userList.Remark);
  1144. jw.Data = result;
  1145. }
  1146. }
  1147. catch (Exception)
  1148. {
  1149. jw.Code = 500;
  1150. jw.Msg = "数据源错误!";
  1151. jw.Data = new List<int>(1);
  1152. }
  1153. return Ok(jw);
  1154. }
  1155. [HttpPost]
  1156. public IActionResult InsertDataExcel(InsertDataExcelDto dto)
  1157. {
  1158. //string client = dto.Client;
  1159. int toUser = dto.ToUser;
  1160. var clietnArr = dto.Client;
  1161. var count = 0;
  1162. //var notClentUser = new List<int>() { 21, 95 , 327 };
  1163. var notClentUser = new List<int>() { 213, 327 };
  1164. var insertList = new List<Crm_ClientDataAndUser>();
  1165. if (clietnArr.Count > 0)
  1166. {
  1167. _sqlSugar.BeginTran();
  1168. //检索相关客户数据
  1169. var newClientArr = _sqlSugar.Queryable<Crm_NewClientData>()
  1170. .Where(x => x.IsDel == 0)
  1171. .Select(x => new Crm_NewClientData
  1172. {
  1173. Client = x.Client,
  1174. Id = x.Id
  1175. })
  1176. .ToList()
  1177. .Select(x => new
  1178. {
  1179. Client = AesEncryptionHelper.Decrypt(x.Client),
  1180. Id = x.Id
  1181. });
  1182. foreach (var item in clietnArr)
  1183. {
  1184. var searchClient = newClientArr.Where(x => x.Client == item).ToList();
  1185. foreach (var clientData in searchClient)
  1186. {
  1187. var clientDataAndUser = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1188. .Where(x => x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1189. .ToList();
  1190. if (clientDataAndUser.Count > 0)
  1191. {
  1192. //清除关联表数据
  1193. _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  1194. .Where(x => !notClentUser.Contains(x.usersId)
  1195. && x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1196. .SetColumns(x => new Crm_ClientDataAndUser
  1197. {
  1198. IsDel = 1,
  1199. DeleteTime = DateTime.Now.ToString(),
  1200. DeleteUserId = 235
  1201. })
  1202. .ExecuteCommand();
  1203. }
  1204. insertList.Add(new Crm_ClientDataAndUser
  1205. {
  1206. usersId = toUser,
  1207. NewClientDataId = clientData.Id,
  1208. CreateTime = DateTime.Now,
  1209. CreateUserId = 235,
  1210. });
  1211. }
  1212. }
  1213. count = _sqlSugar.Insertable(insertList).ExecuteCommand();
  1214. _sqlSugar.CommitTran();
  1215. }
  1216. return Ok(new
  1217. {
  1218. count,
  1219. });
  1220. }
  1221. /// <summary>
  1222. /// 客户资料分配(按照数据ID) - UserId
  1223. /// </summary>
  1224. /// <param name="file"></param>
  1225. /// <returns></returns>
  1226. [HttpPost]
  1227. public IActionResult InsertDataExcel1(IFormFile file)
  1228. {
  1229. // 检查文件是否为空
  1230. if (file == null || file.Length == 0)
  1231. {
  1232. return BadRequest("No file uploaded.");
  1233. }
  1234. // 保存文件到服务器
  1235. var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "File");
  1236. if (!Directory.Exists(uploadsFolder))
  1237. {
  1238. Directory.CreateDirectory(uploadsFolder);
  1239. }
  1240. var filePath = Path.Combine(uploadsFolder, file.FileName);
  1241. using (var stream = new FileStream(filePath, FileMode.Create))
  1242. {
  1243. file.CopyToAsync(stream);
  1244. }
  1245. Workbook workbook = new Workbook(filePath);
  1246. // 获取第一个工作表
  1247. Worksheet worksheet = workbook.Worksheets[0];
  1248. // 获取表头(第一行作为列名)
  1249. int headerRowIndex = 0; // 假设第一行是表头
  1250. Aspose.Cells.Row headerRow = worksheet.Cells.Rows[headerRowIndex];
  1251. int colCount = worksheet.Cells.MaxDataColumn + 1;
  1252. // 动态存储列名
  1253. var clients = new List<Crm_ClientDataAndUser>();
  1254. // 遍历数据行(从第二行开始)
  1255. int rowCount = worksheet.Cells.MaxDataRow + 1;
  1256. for (int row = headerRowIndex + 1; row < rowCount; row++)
  1257. {
  1258. var cellVal1 = worksheet.Cells[row, 0].Value; //序号
  1259. var cellVal2 = worksheet.Cells[row, 1].Value; //数据Id
  1260. var cellVal3 = worksheet.Cells[row, 2].Value; //userId
  1261. int parentId = !string.IsNullOrEmpty(cellVal2?.ToString()) ? int.Parse(cellVal2?.ToString()) : 0;
  1262. int userId = !string.IsNullOrEmpty(cellVal3?.ToString()) ? int.Parse(cellVal3?.ToString()) : 0;
  1263. var rowData = new Crm_ClientDataAndUser()
  1264. {
  1265. usersId = userId,
  1266. NewClientDataId = parentId
  1267. };
  1268. clients.Add(rowData); // 将当前行数据添加到集合中
  1269. }
  1270. var count = 0;
  1271. //var notClentUser = new List<int>() { 21, 95 , 327 };
  1272. var notClentUser = new List<int>() { 21, 95, 327, 213 };
  1273. var insertList = new List<Crm_ClientDataAndUser>();
  1274. if (clients.Count > 0)
  1275. {
  1276. _sqlSugar.BeginTran();
  1277. //检索相关客户数据
  1278. var newClientArr = _sqlSugar.Queryable<Crm_NewClientData>()
  1279. .Where(x => x.IsDel == 0)
  1280. .Select(x => new Crm_NewClientData
  1281. {
  1282. Client = x.Client,
  1283. Id = x.Id
  1284. })
  1285. .ToList();
  1286. foreach (var item in clients)
  1287. {
  1288. var searchClient = newClientArr.Where(x => x.Id == item.NewClientDataId).ToList();
  1289. foreach (var clientData in searchClient)
  1290. {
  1291. var clientDataAndUser = _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1292. .Where(x => x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1293. .ToList();
  1294. if (clientDataAndUser.Count > 0)
  1295. {
  1296. //清除关联表数据
  1297. _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  1298. .Where(x => !notClentUser.Contains(x.usersId)
  1299. && x.NewClientDataId == clientData.Id && x.IsDel == 0)
  1300. .SetColumns(x => new Crm_ClientDataAndUser
  1301. {
  1302. IsDel = 1,
  1303. DeleteTime = DateTime.Now.ToString(),
  1304. DeleteUserId = 235
  1305. })
  1306. .ExecuteCommand();
  1307. }
  1308. insertList.Add(new Crm_ClientDataAndUser
  1309. {
  1310. usersId = item.usersId,
  1311. NewClientDataId = clientData.Id,
  1312. CreateTime = DateTime.Now,
  1313. CreateUserId = 235,
  1314. });
  1315. }
  1316. }
  1317. count = _sqlSugar.Insertable(insertList).ExecuteCommand();
  1318. _sqlSugar.CommitTran();
  1319. }
  1320. return Ok(new
  1321. {
  1322. count,
  1323. });
  1324. }
  1325. /// <summary>
  1326. /// 读取excel分配客户
  1327. /// </summary>
  1328. /// <returns></returns>
  1329. [HttpPost]
  1330. public IActionResult ReadExcelAllocation(IFormFile file, int userId)
  1331. {
  1332. if (file == null || file.Length == 0)
  1333. {
  1334. return BadRequest("No file uploaded.");
  1335. }
  1336. var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), "File");
  1337. if (!Directory.Exists(uploadsFolder))
  1338. {
  1339. Directory.CreateDirectory(uploadsFolder);
  1340. }
  1341. var filePath = Path.Combine(uploadsFolder, file.FileName);
  1342. using (var stream = new FileStream(filePath, FileMode.Create))
  1343. {
  1344. file.CopyTo(stream);
  1345. }
  1346. Workbook workbook = new Workbook(filePath);
  1347. Worksheet worksheet = workbook.Worksheets[0];
  1348. int headerRowIndex = 0; // 第一行为表头
  1349. int rowCount = worksheet.Cells.MaxDataRow + 1;
  1350. var notids = 0;
  1351. // 第1列(索引0):NewClientDataId(客户数据ID)
  1352. var clients = new List<Crm_ClientDataAndUser>();
  1353. for (int row = headerRowIndex + 1; row < rowCount; row++)
  1354. {
  1355. var cellVal1 = worksheet.Cells[row, 0].Value; // 数据id
  1356. int newClientDataId = !string.IsNullOrEmpty(cellVal1?.ToString())
  1357. ? int.Parse(cellVal1.ToString())
  1358. : 0;
  1359. if (newClientDataId <= 0)
  1360. {
  1361. notids++;
  1362. // 跳过无效行
  1363. continue;
  1364. }
  1365. clients.Add(new Crm_ClientDataAndUser
  1366. {
  1367. NewClientDataId = newClientDataId,
  1368. usersId = userId,
  1369. CreateTime = DateTime.Now,
  1370. CreateUserId = 235,
  1371. IsDel = 0,
  1372. });
  1373. }
  1374. var count = 0;
  1375. var updateCount = 0;
  1376. var ids = clients.Select(x => x.NewClientDataId).ToList();
  1377. if (clients.Count > 0)
  1378. {
  1379. _sqlSugar.BeginTran();
  1380. //清除所有id旧数据
  1381. updateCount = _sqlSugar.Updateable<Crm_ClientDataAndUser>()
  1382. .Where(x => x.IsDel == 0)
  1383. .Where(x => ids.Contains(x.NewClientDataId))
  1384. .SetColumns(x => new Crm_ClientDataAndUser
  1385. {
  1386. IsDel = 1,
  1387. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1388. DeleteUserId = 235
  1389. })
  1390. .ExecuteCommand();
  1391. //分配新数据
  1392. count = _sqlSugar.Insertable(clients).ExecuteCommand();
  1393. _sqlSugar.CommitTran();
  1394. }
  1395. return Ok(new
  1396. {
  1397. insertCount = count,
  1398. updateCount = updateCount,
  1399. notids
  1400. });
  1401. }
  1402. [HttpPost]
  1403. public IActionResult SchoolAllocation()
  1404. {
  1405. var clients = _sqlSugar.Queryable<Crm_NewClientData>()
  1406. .Where(x => x.IsDel == 0)
  1407. .Select(x => new Crm_NewClientData { Id = x.Id, Client = x.Client })
  1408. .ToList();
  1409. var keys = new List<string>()
  1410. {
  1411. "大学", "学院", "中学", "教育", "学校", "一中", "二中", "七中", "十五中", "二十五中","高校"
  1412. };
  1413. var count = 0;
  1414. var insertArr = new List<Crm_ClientDataAndBusiness>();
  1415. // --368 教育
  1416. foreach (var item in clients)
  1417. {
  1418. EncryptionProcessor.DecryptProperties(item);
  1419. foreach (var key in keys)
  1420. {
  1421. if (!string.IsNullOrWhiteSpace(item.Client) && item.Client.Contains(key))
  1422. {
  1423. insertArr.Add(new Crm_ClientDataAndBusiness
  1424. {
  1425. NewClientDataId = item.Id,
  1426. SetDataId = 368, // 教育
  1427. CreateTime = DateTime.Now,
  1428. CreateUserId = 235,
  1429. IsDel = 0
  1430. });
  1431. }
  1432. }
  1433. }
  1434. count = _sqlSugar.Insertable(insertArr)
  1435. .ExecuteCommand();
  1436. return count > 0 ? Ok(JsonView(true, "分配成功!", count)) : Ok(JsonView(false, "分配失败!"));
  1437. }
  1438. /// <summary>
  1439. /// 根据提供的数据id导出对应的excel
  1440. /// </summary>
  1441. /// <param name="ids">数据id</param>
  1442. /// <returns></returns>
  1443. [HttpPost]
  1444. public async Task<IActionResult> ExportExcelByIds(List<int> ids)
  1445. {
  1446. try
  1447. {
  1448. if (ids == null || ids.Count == 0)
  1449. {
  1450. return Ok(JsonView(false, "请提供要导出的客户数据ID"));
  1451. }
  1452. // 查询客户数据
  1453. var clientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()
  1454. .Where(x => ids.Contains(x.Id) && x.IsDel == 0)
  1455. .OrderByDescending(x => x.CreateTime)
  1456. .ToListAsync();
  1457. if (clientDatas == null || clientDatas.Count == 0)
  1458. {
  1459. return Ok(JsonView(false, "未找到要导出的客户数据"));
  1460. }
  1461. var newClientDataView = new List<NewClientDataExcelDownloadView>();
  1462. foreach (var client in clientDatas)
  1463. {
  1464. var view = new NewClientDataExcelDownloadView
  1465. {
  1466. Id = client.Id,
  1467. Number = client.Number,
  1468. Lvlid = client.Lvlid,
  1469. Client = client.Client,
  1470. Weight = client.Weight,
  1471. ClientShort = client.ClientShort,
  1472. Contact = client.Contact,
  1473. Gender = client.Gender,
  1474. Passport = client.Passport,
  1475. PassportDate = client.PassportDate,
  1476. Job = client.Job,
  1477. Telephone = client.Telephone,
  1478. Phone = client.Phone,
  1479. Email = client.Email,
  1480. Location = client.Location,
  1481. Address = client.Address,
  1482. Birthday = client.Birthday,
  1483. OtherInfo = client.OtherInfo,
  1484. Wechat = client.Wechat,
  1485. Category = client.Category,
  1486. PreDele = client.PreDele,
  1487. FinlishedDele = client.FinlishedDele,
  1488. LastUpdateUserId = client.LastUpdateUserId,
  1489. LastUpdateTime = client.LastUpdateTime,
  1490. CreateTime = client.CreateTime,
  1491. CreateUserId = client.CreateUserId,
  1492. IsDel = client.IsDel
  1493. };
  1494. newClientDataView.Add(view);
  1495. }
  1496. // 查询关联数据
  1497. var userDatas = await _sqlSugar.Queryable<Sys_Users>().ToListAsync();
  1498. var setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
  1499. var clientIds = clientDatas.Select(x => x.Id).ToList();
  1500. List<AscribedUser> ascribedUser = new List<AscribedUser>();
  1501. List<AscribedDepartment> ascribedDepartment = new List<AscribedDepartment>();
  1502. if (clientIds.Count > 0)
  1503. {
  1504. ascribedUser = await _sqlSugar.SqlQueryable<AscribedUser>(
  1505. $"select u1.UsersId as UserId ,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id AND u1.ISDEL = 0 AND u1.NewClientDataId IN ({string.Join(",", clientIds)})")
  1506. .ToListAsync();
  1507. ascribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>(
  1508. $"select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id AND d1.ISDEL = 0 AND d1.NewClientDataId IN ({string.Join(",", clientIds)})")
  1509. .ToListAsync();
  1510. }
  1511. // 填充额外字段
  1512. int index = 1;
  1513. foreach (var item in newClientDataView)
  1514. {
  1515. EncryptionProcessor.DecryptProperties(item); // 解密
  1516. item.RowNumber = index;
  1517. item.CreateUserName = userDatas.Find(x => x.Id == item.CreateUserId)?.CnName ?? "-";
  1518. item.CategoryStr = setDatas.Find(x => x.Id == item.Category)?.Name ?? "-";
  1519. item.LvlidStr = setDatas.Find(x => x.Id == item.Lvlid)?.Name ?? "-";
  1520. var currAscribedUser = ascribedUser.Where(x => x.NewClientDataId == item.Id).ToList();
  1521. if (currAscribedUser.Any())
  1522. {
  1523. item.AscribedUserLable = string.Join("、", currAscribedUser.Select(x => x.CnName).ToList());
  1524. }
  1525. var currAscribedDepartment = ascribedDepartment.Where(x => x.NewClientDataId == item.Id).ToList();
  1526. if (currAscribedDepartment.Any())
  1527. {
  1528. item.AscribedDepartmentLable = string.Join("、", currAscribedDepartment.Select(x => x.Name).ToList());
  1529. }
  1530. index++;
  1531. }
  1532. // 使用模板生成Excel
  1533. string tempPath = AppSettingsHelper.Get("ExcelBasePath") + "Template/公司客户资料导出模板.xlsx";
  1534. var designer = new WorkbookDesigner();
  1535. designer.Workbook = new Workbook(tempPath);
  1536. designer.SetDataSource("NCDDT", newClientDataView);
  1537. designer.Process();
  1538. // 文件名
  1539. string fileName = $"公司客户资料(按ID导出){DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
  1540. // 确保目录存在
  1541. string savePath = AppSettingsHelper.Get("ExcelBasePath") + "NewClientDataExcelDownload/";
  1542. if (!Directory.Exists(savePath))
  1543. {
  1544. Directory.CreateDirectory(savePath);
  1545. }
  1546. designer.Workbook.Save(savePath + fileName);
  1547. string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/NewClientDataExcelDownload/" + fileName;
  1548. return Ok(JsonView(true, "导出成功", url));
  1549. }
  1550. catch (Exception ex)
  1551. {
  1552. return Ok(JsonView(false, $"导出失败:{ex.Message}"));
  1553. }
  1554. }
  1555. /// <summary>
  1556. /// 获取IP信息
  1557. /// </summary>
  1558. /// <param name="ip">ipv4 or ipv6</param>
  1559. /// <returns></returns>
  1560. private async Task<(string ip, string local)> GetIpInfo(string ip)
  1561. {
  1562. string local = string.Empty;
  1563. if (IPAddress.TryParse(ip, out _))
  1564. {
  1565. using HttpClient _httpClient = new HttpClient();
  1566. var response = await _httpClient.GetAsync($"https://api.vore.top/api/IPdata?ip={ip}");
  1567. response.EnsureSuccessStatusCode();
  1568. var json = await response.Content.ReadAsStringAsync();
  1569. var ipInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
  1570. if (ipInfo.code == 200)
  1571. {
  1572. ip = ipInfo.ipinfo.text;
  1573. local = $"{ipInfo.adcode.o}";
  1574. }
  1575. }
  1576. return (ip, local);
  1577. }
  1578. #region 回滚数据记录
  1579. //[HttpPost]
  1580. //public async Task<IActionResult> actionResult()
  1581. //{
  1582. // var jw = JsonView(true);
  1583. // var sql = @" SELECT * FROM OA2023DB.dbo.Crm_TableOperationRecord
  1584. // WHERE TableName ='Crm_NewClientData'
  1585. // AND OperationItem IN(4) AND CreateTime > '2025-02-03' AND CreateTime < '2025-03-06'
  1586. // AND ReturnResult LIKE '%修改成功%' ";
  1587. // var list = _sqlSugar.SqlQueryable<Crm_TableOperationRecord>(sql).Select(x=>new Crm_TableOperationRecord
  1588. // {
  1589. // RequestParam = x.RequestParam
  1590. // }).ToList();
  1591. // foreach (var item in list)
  1592. // {
  1593. // var string1 = item.RequestParam.Trim('"').Replace("\\", "");
  1594. // //if (!string.IsNullOrEmpty(item.RequestParam))
  1595. // //{
  1596. // // var req = item.RequestParam;
  1597. // // if (CommonFun.IsValidJson(item.RequestParam))
  1598. // // {
  1599. // // var res1 = JToken.Parse(item.RequestParam);
  1600. // // }
  1601. // // NewClientOpDto dto = JsonConvert.DeserializeObject<NewClientOpDto>(JsonConvert.DeserializeObject<string>(item.RequestParam));
  1602. // NewClientOpDto dto1 = JsonConvert.DeserializeObject<NewClientOpDto>(string1);
  1603. // var result = await this.NewClientOp(dto1);
  1604. // //}
  1605. // }
  1606. // return Ok(jw);
  1607. //}
  1608. #endregion
  1609. }
  1610. }