NewClientDataRepository.cs 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  1. using AutoMapper;
  2. using AutoMapper.Execution;
  3. using EyeSoft.Collections.Generic;
  4. using EyeSoft.Extensions;
  5. using MySqlX.XDevAPI.Relational;
  6. using Newtonsoft.Json;
  7. using NPOI.OpenXmlFormats.Dml.Diagram;
  8. using NPOI.SS.Formula.Functions;
  9. using NPOI.SS.UserModel;
  10. using NPOI.Util;
  11. using OASystem.Domain;
  12. using OASystem.Domain.AesEncryption;
  13. using OASystem.Domain.AutoMappers;
  14. using OASystem.Domain.Dtos;
  15. using OASystem.Domain.Dtos.CRM;
  16. using OASystem.Domain.Entities.Customer;
  17. using OASystem.Domain.Entities.Resource;
  18. using OASystem.Domain.Enums;
  19. using OASystem.Domain.ViewModels.CRM;
  20. using OASystem.Domain.ViewModels.JuHeExchangeRate;
  21. using OASystem.Domain.ViewModels.QiYeWeChat;
  22. using OASystem.Infrastructure.Tools;
  23. using OASystem.RedisRepository;
  24. using OASystem.RedisRepository.RedisAsyncHelper;
  25. using SqlSugar;
  26. using System;
  27. using System.Collections;
  28. using System.Collections.Generic;
  29. using System.ComponentModel.Design;
  30. using System.Diagnostics;
  31. using System.Diagnostics.Contracts;
  32. using System.Linq;
  33. using System.Reflection.Metadata;
  34. using System.Runtime.Intrinsics.Arm;
  35. using System.Text;
  36. using System.Threading.Tasks;
  37. using System.Xml.Linq;
  38. using System.Runtime.Serialization;
  39. using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
  40. using static OASystem.Domain.Dtos.CRM.NewClientDataQueryDto;
  41. using Autofac;
  42. namespace OASystem.Infrastructure.Repositories.CRM
  43. {
  44. /// <summary>
  45. /// 客户资料仓储类
  46. /// </summary>
  47. public class NewClientDataRepository : BaseRepository<Crm_NewClientData, NewClientDataView>
  48. {
  49. private readonly IMapper _mapper;
  50. private readonly IRedisHelper _redisHelper;
  51. private readonly ILifetimeScope _scope;
  52. public NewClientDataRepository(SqlSugarClient sqlSugar, IMapper mapper, ILifetimeScope scope) :
  53. base(sqlSugar)
  54. {
  55. _mapper = mapper;
  56. _redisHelper = RedisFactory.CreateRedisRepository();
  57. this._scope = scope;
  58. }
  59. /// <summary>
  60. /// 下拉框数据模型
  61. /// </summary>
  62. [Serializable]
  63. public class DropdownItem
  64. {
  65. public int Id { get; set; }
  66. public string Name { get; set; }
  67. public string Remark { get; set; }
  68. }
  69. /// <summary>
  70. /// 下拉框数据缓存模型
  71. /// </summary>
  72. [Serializable]
  73. public class DropdownData
  74. {
  75. public List<DropdownItem> Users { get; set; } = new List<DropdownItem>();
  76. public List<DropdownItem> Province { get; set; } = new List<DropdownItem>();
  77. public List<DropdownItem> Level { get; set; } = new List<DropdownItem>();
  78. public List<DropdownItem> CustomerClass { get; set; } = new List<DropdownItem>();
  79. public List<DropdownItem> ServiceClass { get; set; } = new List<DropdownItem>();
  80. }
  81. /// <summary>
  82. /// 获取缓存的下拉框数据
  83. /// </summary>
  84. /// <param name="operationUserId">操作用户ID</param>
  85. /// <returns></returns>
  86. private async Task<DropdownData> GetCachedDropdownDataAsync(int operationUserId)
  87. {
  88. var cacheKey = $"NewClientData_Dropdown_{operationUserId}";
  89. var cachedData = await _redisHelper.StringGetAsync<DropdownData>(cacheKey);
  90. if (cachedData != null)
  91. {
  92. return cachedData;
  93. }
  94. var setDatas = new List<Sys_SetData>();
  95. using var newScope = _scope.BeginLifetimeScope();
  96. using (SqlSugarClient sc = newScope.Resolve<SqlSugarClient>())
  97. {
  98. setDatas = await sc.Queryable<Sys_SetData>()
  99. .Where(x => x.IsDel == 0)
  100. .ToListAsync();
  101. }
  102. var dropdownData = new DropdownData();
  103. //负责人下拉框
  104. dropdownData.Users = GetNewExistClient(operationUserId)
  105. .Select(x => new DropdownItem { Id = x.Id, Name = x.CnName })
  106. .ToList();
  107. //省域数据
  108. dropdownData.Province = setDatas
  109. .Where(u => u.STid == 42)
  110. .Select(x => new DropdownItem { Id = x.Id, Name = x.Name })
  111. .ToList();
  112. //客户级别数据
  113. dropdownData.Level = setDatas
  114. .Where(u => u.STid == 33)
  115. .Select(x => new DropdownItem { Id = x.Id, Name = x.Name })
  116. .ToList();
  117. //客户类别
  118. var customerClassList = new List<DropdownItem>();
  119. List<Sys_SetData> CustomerClass = setDatas
  120. .Where(u => u.STid == 37 && u.IsDel == 0)
  121. .ToList();
  122. foreach (Sys_SetData item in CustomerClass)
  123. {
  124. customerClassList.Add(new DropdownItem
  125. {
  126. Id = item.Id,
  127. Name = item.Name,
  128. Remark = item.Remark
  129. });
  130. }
  131. // 按ID排序客户类别
  132. dropdownData.CustomerClass = customerClassList.OrderBy(x => x.Id).ToList();
  133. //业务分类
  134. dropdownData.ServiceClass = setDatas
  135. .Where(u => u.STid == 36)
  136. .Select(x => new DropdownItem { Id = x.Id, Name = x.Name })
  137. .ToList();
  138. // 缓存30分钟
  139. await _redisHelper.StringSetAsync(cacheKey, dropdownData, TimeSpan.FromMinutes(30));
  140. return dropdownData;
  141. }
  142. /// <summary>
  143. /// 可序列化的关联用户信息
  144. /// </summary>
  145. [Serializable]
  146. public class SerializableAscribedUser
  147. {
  148. public int UserId { get; set; }
  149. public string CnName { get; set; }
  150. public int NewClientDataId { get; set; }
  151. }
  152. /// <summary>
  153. /// 可序列化的关联部门信息
  154. /// </summary>
  155. [Serializable]
  156. public class SerializableAscribedDepartment
  157. {
  158. public int Id { get; set; }
  159. public string Name { get; set; }
  160. public int NewClientDataId { get; set; }
  161. }
  162. /// <summary>
  163. /// 获取缓存的客户资料关联信息
  164. /// </summary>
  165. /// <param name="clientIds">客户ID列表</param>
  166. /// <returns></returns>
  167. private async Task<(List<AscribedUser> ascribedUsers, List<AscribedDepartment> ascribedDepartments)> GetCachedClientRelationsAsync(List<int> clientIds)
  168. {
  169. if (clientIds == null || !clientIds.Any())
  170. return (new List<AscribedUser>(), new List<AscribedDepartment>());
  171. var cacheKey = $"NewClientData_Relations_{string.Join("_", clientIds.OrderBy(x => x))}";
  172. var cachedData = await _redisHelper.StringGetAsync<(List<SerializableAscribedUser>, List<SerializableAscribedDepartment>)>(cacheKey);
  173. if (cachedData.Item1 != null && cachedData.Item2 != null)
  174. {
  175. // 转换为原始类型
  176. var ascribedUsers = cachedData.Item1.Select(x => new AscribedUser
  177. {
  178. UserId = x.UserId,
  179. CnName = x.CnName,
  180. NewClientDataId = x.NewClientDataId
  181. }).ToList();
  182. var ascribedDepartments = cachedData.Item2.Select(x => new AscribedDepartment
  183. {
  184. Id = x.Id,
  185. Name = x.Name,
  186. NewClientDataId = x.NewClientDataId
  187. }).ToList();
  188. return (ascribedUsers, ascribedDepartments);
  189. }
  190. // 批量查询关联信息 - 使用同步方法避免数据读取器问题
  191. var queriedUsers = _sqlSugar.SqlQueryable<AscribedUser>(
  192. "select u1.UsersId as UserId ,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id and NewClientDataId in (" + string.Join(",", clientIds) + ") AND u1.ISDEL = 0")
  193. .ToList();
  194. var queriedDepartments = _sqlSugar.SqlQueryable<AscribedDepartment>(
  195. "select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id and NewClientDataId in (" + string.Join(",", clientIds) + ") AND d1.ISDEL = 0")
  196. .ToList();
  197. // 转换为可序列化类型进行缓存
  198. var serializableUsers = queriedUsers.Select(x => new SerializableAscribedUser
  199. {
  200. UserId = x.UserId,
  201. CnName = x.CnName,
  202. NewClientDataId = x.NewClientDataId
  203. }).ToList();
  204. var serializableDepartments = queriedDepartments.Select(x => new SerializableAscribedDepartment
  205. {
  206. Id = x.Id,
  207. Name = x.Name,
  208. NewClientDataId = x.NewClientDataId
  209. }).ToList();
  210. var result = (serializableUsers, serializableDepartments);
  211. // 缓存10分钟
  212. await _redisHelper.StringSetAsync(cacheKey, result, TimeSpan.FromMinutes(10));
  213. return (queriedUsers, queriedDepartments);
  214. }
  215. /// <summary>
  216. /// 获取缓存的省域数据
  217. /// </summary>
  218. /// <param name="range">省域范围</param>
  219. /// <returns></returns>
  220. private async Task<List<int>> GetCachedRangeSetDataAsync(int range)
  221. {
  222. if (range == 0) return new List<int>();
  223. var cacheKey = $"NewClientData_Range_{range}";
  224. var cachedData = await _redisHelper.StringGetAsync<List<int>>(cacheKey);
  225. if (cachedData != null)
  226. {
  227. return cachedData;
  228. }
  229. string setDataSql = "select * from Sys_SetData where STid = 33 and isdel = 0 ";
  230. switch (range)
  231. {
  232. case 419:
  233. setDataSql += " and (Name like '%四%川%' or Name like '%成%都%')";
  234. break;
  235. case 421:
  236. setDataSql += " and (Name like '%贵%州%' or Name like '%贵%阳%')";
  237. break;
  238. case 420:
  239. setDataSql += " and (Name like '%云%南%' or Name like '%昆%明%')";
  240. break;
  241. case 423:
  242. setDataSql += " and (Name like '%重庆%')";
  243. break;
  244. case 422:
  245. setDataSql += " and (Name like '%西%藏%' or Name like '%拉%萨%')";
  246. break;
  247. case 578:
  248. setDataSql += " and (Name like '%青%海%' or Name like '%西%宁%')";
  249. break;
  250. case 605:
  251. setDataSql += " and (Name like '%陕%西%' or Name like '%西%安%')";
  252. break;
  253. case 606:
  254. setDataSql += " and (Name like '%宁%夏%' or Name like '%银%川%')";
  255. break;
  256. case 625:
  257. setDataSql += " and (Name like '%甘%肃%' or Name like '%兰%州%')";
  258. break;
  259. case 634:
  260. setDataSql += " and (Name like '%新%疆%' or Name like '%乌%鲁%木%齐%')";
  261. break;
  262. }
  263. var rangeSetDataList = new List<int>();
  264. using var newScope = _scope.BeginLifetimeScope();
  265. using (SqlSugarClient sc = newScope.Resolve<SqlSugarClient>())
  266. {
  267. rangeSetDataList = sc.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();
  268. }
  269. // 缓存1小时
  270. await _redisHelper.StringSetAsync(cacheKey, rangeSetDataList, TimeSpan.FromHours(1));
  271. return rangeSetDataList;
  272. }
  273. /// <summary>
  274. /// 客户资料
  275. /// 基础数据源
  276. /// </summary>
  277. /// <param name="dto"></param>
  278. /// <returns></returns>
  279. public async Task<Result> _Init(MarketCustomerInitDto Dto)
  280. {
  281. Result result = new Result() { Code = -2, Msg = "未知错误" };
  282. var portType = Dto.PortType;
  283. if (portType == 1 || portType == 2 || portType == 3)
  284. {
  285. #region 下拉框初始化数据
  286. //负责人下拉框
  287. //List<dynamic> _Users = new List<dynamic>();
  288. //var _Users = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0).Select(x => new
  289. //{
  290. // x.Id,
  291. // Name = x.CnName
  292. //}).ToList();
  293. var _Users = GetNewExistClient(Dto.UserId)
  294. .Select(x => new
  295. {
  296. x.Id,
  297. Name = x.CnName
  298. }).ToList();
  299. //List<Sys_Users> users = GetNewExistClient();
  300. //foreach (Sys_Users user in users)
  301. //{
  302. // var data = new
  303. // {
  304. // Id = user.Id,
  305. // Name = user.CnName
  306. // };
  307. // _Users.Add(data);
  308. //};
  309. List<Sys_SetData> initData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();
  310. //客户级别数据
  311. List<dynamic> _level = new List<dynamic>();
  312. List<Sys_SetData> level = initData.Where(u => u.STid == 33 && u.IsDel == 0).ToList();
  313. foreach (Sys_SetData item in level)
  314. {
  315. var data = new
  316. {
  317. Id = item.Id,
  318. Name = item.Name
  319. };
  320. _level.Add(data);
  321. };
  322. //客户类别
  323. ArrayList _CustomerClass = new ArrayList();
  324. List<Sys_SetData> CustomerClass = initData.Where(u => u.STid == 37 && u.IsDel == 0).ToList();
  325. foreach (Sys_SetData item in CustomerClass)
  326. {
  327. var data = new
  328. {
  329. Id = item.Id,
  330. Name = item.Name,
  331. item.Remark
  332. };
  333. _CustomerClass.Add(data);
  334. };
  335. // 创建比较器实例
  336. IComparer remakeComparer = new RemakeComparer();
  337. _CustomerClass.Sort(remakeComparer);
  338. //业务分类
  339. List<dynamic> _ServiceClass = new List<dynamic>();
  340. List<Sys_SetData> ServiceClass = initData.Where(u => u.STid == 36 && u.IsDel == 0).ToList();
  341. foreach (Sys_SetData item in ServiceClass)
  342. {
  343. var data = new
  344. {
  345. Id = item.Id,
  346. Name = item.Name
  347. };
  348. _ServiceClass.Add(data);
  349. };
  350. //身份分类
  351. List<dynamic> _ProvinceClass = new List<dynamic>();
  352. List<Sys_SetData> ProvinceClass = initData.Where(u => u.STid == 42 && u.IsDel == 0).ToList();
  353. foreach (Sys_SetData item in ProvinceClass)
  354. {
  355. var data = new
  356. {
  357. Id = item.Id,
  358. Name = item.Name
  359. };
  360. _ProvinceClass.Add(data);
  361. };
  362. #endregion
  363. var data1 = new {
  364. Users = _Users,
  365. Level = _level,
  366. CustomerClass = _CustomerClass,
  367. ServiceClass= _ServiceClass,
  368. ProvinceClass = _ProvinceClass
  369. };
  370. return result = new Result()
  371. {
  372. Code = 0,
  373. Msg = "查询成功",
  374. Data = data1
  375. };
  376. }
  377. else
  378. {
  379. result.Msg = string.Format("请传入有效的PortType参数!");
  380. }
  381. return result;
  382. }
  383. /// <summary>
  384. /// 市场客户资料数据
  385. /// 详情
  386. /// </summary>
  387. /// <param name="dto"></param>
  388. /// <returns></returns>
  389. public async Task<Result> _Details(int portType,int id)
  390. {
  391. Result result = new Result() { Code = -2, Msg = "未知错误" };
  392. if (portType == 1 || portType == 2 || portType == 3)
  393. {
  394. if (id < 0)
  395. {
  396. result.Msg = string.Format("请传入有效的Id参数!");
  397. return result;
  398. }
  399. string infoSql = string.Format(@" Select * From Crm_NewClientData Where Isdel = 0 And Id = {0}", id);
  400. var info = await _sqlSugar.SqlQueryable<DetailsView>(infoSql).FirstAsync();
  401. if (info != null)
  402. {
  403. EncryptionProcessor.DecryptProperties(info);
  404. List<AscribedUser> AscribedUser = await _sqlSugar.SqlQueryable<AscribedUser>
  405. ("select u1.UsersId as UserId ,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id and NewClientDataId=" + info.Id + " AND u1.ISDEL = 0").ToListAsync();
  406. info.AscribedUser = AscribedUser.Select(it => it.UserId).ToList();
  407. List<AscribedDepartment> AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>
  408. ("select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id and NewClientDataId=" + info.Id + " AND d1.ISDEL = 0").ToListAsync();
  409. info.AscribedDepartment = AscribedDepartment.Select(it => it.Id).ToList();
  410. result.Code = 0;
  411. result.Data = info;
  412. }
  413. }
  414. else result.Msg = MsgTips.Port;
  415. return result;
  416. }
  417. /// <summary>
  418. /// 客户资料查询 - 优化版本
  419. /// </summary>
  420. /// <param name="dto"></param>
  421. /// <returns></returns>
  422. public async Task<Result> QueryNewClientData(NewClientDataQueryDto dto)
  423. {
  424. Stopwatch stopwatch = Stopwatch.StartNew();
  425. Result result = new Result() { Code = -2, Msg = "未知错误" };
  426. int pageIndex = dto.PageIndex, pageSize = dto.PageSize;
  427. try
  428. {
  429. // 并行获取缓存数据
  430. var rangeSetDataTask = GetCachedRangeSetDataAsync(dto.Range);
  431. var dropdownDataTask = GetCachedDropdownDataAsync(dto.OperationUserId);
  432. #region 交集计算优化
  433. List<int> intList = new List<int>();
  434. int state = 0;
  435. // 负责人筛选
  436. if (dto.OperationUserId != 21 && string.IsNullOrWhiteSpace(dto.Userid))
  437. {
  438. dto.Userid = dto.OperationUserId.ToString();
  439. }
  440. List<int> NewClientDataId1 = new List<int>();
  441. List<int> NewClientDataId2 = new List<int>();
  442. if (!string.IsNullOrWhiteSpace(dto.Userid))
  443. {
  444. string sql = string.Format(@"
  445. select u1.NewClientDataId
  446. from Crm_ClientDataAndUser u1
  447. where u1.IsDel = 0 AND u1.UsersId in ({0})
  448. ", dto.Userid);
  449. NewClientDataId1 = _sqlSugar.Ado.SqlQuery<int>(sql).ToList();
  450. state = -1;
  451. }
  452. // 业务归属筛选
  453. if (!string.IsNullOrWhiteSpace(dto.Business))
  454. {
  455. string sql = string.Format(@"
  456. select d1.NewClientDataId
  457. from Crm_ClientDataAndBusiness d1
  458. where d1.SetDataId in ({0}) and d1.isdel = 0
  459. ", dto.Business);
  460. NewClientDataId2 = _sqlSugar.Ado.SqlQuery<int>(sql).ToList();
  461. state = -1;
  462. }
  463. // 交集计算
  464. if (NewClientDataId1.Count != 0 && NewClientDataId2.Count != 0)
  465. {
  466. intList = NewClientDataId1.Intersect(NewClientDataId2).ToList();
  467. }
  468. else if (NewClientDataId1.Count != 0)
  469. {
  470. intList = NewClientDataId1;
  471. }
  472. else if (NewClientDataId2.Count != 0 && dto.OperationUserId == 21)
  473. {
  474. intList = NewClientDataId2;
  475. }
  476. if (state == -1 && intList.Count < 1)
  477. {
  478. intList.Add(-1);
  479. }
  480. #endregion
  481. // 等待缓存数据
  482. var rangeSetDataList = await rangeSetDataTask;
  483. var dropdownData = await dropdownDataTask;
  484. #region 模糊搜索优化
  485. var searchDataIds = new List<int>();
  486. var isSelectSearch = false;
  487. string contact = dto.Contact, location = dto.Location, clientDto = dto.Client;
  488. if (!string.IsNullOrEmpty(contact) || !string.IsNullOrEmpty(location) || !string.IsNullOrEmpty(clientDto))
  489. {
  490. isSelectSearch = true;
  491. // 使用缓存键进行搜索
  492. var searchCacheKey = $"NewClientData_Search_{contact}_{location}_{clientDto}_{dto.PortType}";
  493. var cachedSearchIds = await _redisHelper.StringGetAsync<List<int>>(searchCacheKey);
  494. if (cachedSearchIds != null)
  495. {
  496. searchDataIds = cachedSearchIds;
  497. }
  498. else
  499. {
  500. var searchClientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()
  501. .Where(x => x.IsDel == 0)
  502. .Select(x => new Crm_NewClientData() { Id = x.Id, Client = x.Client, Location = x.Location, Contact = x.Contact })
  503. .ToListAsync();
  504. // 批量解密
  505. foreach (var item in searchClientDatas)
  506. {
  507. EncryptionProcessor.DecryptProperties(item);
  508. }
  509. if (dto.PortType == 1)
  510. {
  511. searchDataIds = searchClientDatas
  512. .WhereIF(!string.IsNullOrEmpty(contact), x => !string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(contact))
  513. .WhereIF(!string.IsNullOrEmpty(location), x => !string.IsNullOrEmpty(x.Location) && x.Location.Contains(location))
  514. .WhereIF(!string.IsNullOrEmpty(clientDto), x => !string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto))
  515. .Select(x => x.Id)
  516. .ToList();
  517. }
  518. else if (dto.PortType == 2 || dto.PortType == 3)
  519. {
  520. searchDataIds = searchClientDatas
  521. .Where(x => (!string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(clientDto)) ||
  522. (!string.IsNullOrEmpty(x.Location) && x.Location.Contains(clientDto)) ||
  523. (!string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto)))
  524. .Select(x => x.Id)
  525. .ToList();
  526. }
  527. if (searchDataIds.Count < 1) searchDataIds.Add(0);
  528. // 缓存搜索结果5分钟
  529. await _redisHelper.StringSetAsync(searchCacheKey, searchDataIds, TimeSpan.FromMinutes(5));
  530. }
  531. }
  532. #endregion
  533. #region 主查询
  534. RefAsync<int> total = 0;
  535. var clientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()
  536. .Where(x => x.IsDel == 0)
  537. .WhereIF(state == -1 && intList.Count > 0, x => intList.Contains(x.Id))
  538. .WhereIF(dto.Lvlid != 0, x => x.Lvlid == dto.Lvlid)
  539. .WhereIF(rangeSetDataList.Count > 0, x => rangeSetDataList.Contains(x.Lvlid))
  540. .WhereIF(dto.Category > 0, x => x.Category == dto.Category)
  541. .WhereIF(isSelectSearch && searchDataIds.Count > 0, x => searchDataIds.Contains(x.Id))
  542. .OrderByDescending(x => x.LastUpdateTime)
  543. .ToPageListAsync(pageIndex, pageSize, total);
  544. var NewClientDataView = _mapper.Map<List<NewClientDataView>>(clientDatas);
  545. var count = total;
  546. #endregion
  547. // 计算出团总量
  548. var groupNumber = await QueryNumberGroups();
  549. if (NewClientDataView.Count > 0)
  550. {
  551. float totalPage = (float)count / dto.PageSize;
  552. if (totalPage == 0) totalPage = 1;
  553. else totalPage = (int)Math.Ceiling((double)totalPage);
  554. if (dto.PortType == 1)
  555. {
  556. // 批量获取关联信息
  557. var clientIds = NewClientDataView.Select(x => x.Id).ToList();
  558. var (ascribedUsers, ascribedDepartments) = await GetCachedClientRelationsAsync(clientIds);
  559. // 获取设置数据用于显示名称
  560. var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToList();
  561. int index = 1;
  562. foreach (var item in NewClientDataView)
  563. {
  564. // 批量解密
  565. item.Weight = AesEncryptionHelper.Decrypt(item.Weight);
  566. item.Client = AesEncryptionHelper.Decrypt(item.Client);
  567. item.Contact = AesEncryptionHelper.Decrypt(item.Contact);
  568. item.Job = AesEncryptionHelper.Decrypt(item.Job);
  569. item.Telephone = AesEncryptionHelper.Decrypt(item.Telephone);
  570. item.Phone = AesEncryptionHelper.Decrypt(item.Phone);
  571. item.Location = AesEncryptionHelper.Decrypt(item.Location);
  572. item.Remark = AesEncryptionHelper.Decrypt(item.Remark);
  573. item.RowNumber = index;
  574. item.CategoryStr = setDatas.Find(x => x.Id == item.Category)?.Name ?? "-";
  575. item.LvlidStr = setDatas.Find(x => x.Id == item.Lvlid)?.Name ?? "-";
  576. // 从批量查询结果中获取关联信息
  577. item.AscribedUser = ascribedUsers.Where(x => x.NewClientDataId == item.Id).ToList();
  578. item.AscribedDepartment = ascribedDepartments.Where(x => x.NewClientDataId == item.Id).ToList();
  579. index++;
  580. }
  581. var Data = new
  582. {
  583. ClientTableData = new { pageCount = count.Value, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },
  584. Users = dropdownData.Users,
  585. Province = dropdownData.Province,
  586. level = dropdownData.Level,
  587. CustomerClass = dropdownData.CustomerClass,
  588. ServiceClass = dropdownData.ServiceClass,
  589. groupNumber = groupNumber.Data,
  590. };
  591. return result = new Result()
  592. {
  593. Code = 0,
  594. Msg = $"查询成功!总耗时: {stopwatch.ElapsedMilliseconds} 毫秒",
  595. Data = Data
  596. };
  597. }
  598. else if (dto.PortType == 2 || dto.PortType == 3)
  599. {
  600. List<NewClientDataAndroidIOSView> newClientDataIOSViews = new List<NewClientDataAndroidIOSView>();
  601. int index = 1;
  602. foreach (var item in NewClientDataView)
  603. {
  604. newClientDataIOSViews.Add(new NewClientDataAndroidIOSView()
  605. {
  606. RowNumber = index,
  607. Id = item.Id,
  608. Client = AesEncryptionHelper.Decrypt(item.Client),
  609. Contact = AesEncryptionHelper.Decrypt(item.Contact),
  610. Job = AesEncryptionHelper.Decrypt(item.Job),
  611. Telephone = AesEncryptionHelper.Decrypt(item.Telephone),
  612. Location = AesEncryptionHelper.Decrypt(item.Location),
  613. });
  614. index++;
  615. }
  616. result = new Result()
  617. {
  618. Code = 0,
  619. Msg = $"查询成功!总耗时: {stopwatch.ElapsedMilliseconds} 毫秒",
  620. Data = new { pageCount = count.Value, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = newClientDataIOSViews },
  621. };
  622. }
  623. }
  624. else
  625. {
  626. if (dto.PortType == 2 || dto.PortType == 3)
  627. {
  628. var Data = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView };
  629. result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };
  630. }
  631. else
  632. {
  633. var Data = new
  634. {
  635. ClientTableData = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },
  636. Users = dropdownData.Users,
  637. Province = dropdownData.Province,
  638. level = dropdownData.Level,
  639. CustomerClass = dropdownData.CustomerClass,
  640. ServiceClass = dropdownData.ServiceClass,
  641. groupNumber = groupNumber.Data,
  642. };
  643. result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };
  644. }
  645. }
  646. }
  647. catch (Exception ex)
  648. {
  649. //记录详细错误信息
  650. //Console.WriteLine($"QueryNewClientData 异常: {ex.Message}");
  651. //Console.WriteLine($"异常堆栈: {ex.StackTrace}");
  652. result = new Result() { Code = -2, Msg = $"查询异常: {ex.Message}" };
  653. }
  654. finally
  655. {
  656. stopwatch.Stop();
  657. if (result.Code == 0)
  658. {
  659. result.Msg = $"查询成功!总耗时: {stopwatch.ElapsedMilliseconds} 毫秒";
  660. }
  661. }
  662. return result;
  663. }
  664. /// <summary>
  665. /// 客户资料初识初始化
  666. /// </summary>
  667. /// <param name="dto"></param>
  668. /// <returns></returns>
  669. public async Task<Result> QueryNewClientData1(NewClientDataQueryDto dto)
  670. {
  671. Result result = new Result() { Code = -2, Msg = "未知错误" };
  672. try
  673. {
  674. #region 交集
  675. List<int> NewClientDataId1 = new List<int>();
  676. List<int> NewClientDataId2 = new List<int>();
  677. string NewClientDataId = "";
  678. int state = 0;
  679. #region 负责人
  680. if (dto.OperationUserId != 21)
  681. {
  682. if (string.IsNullOrWhiteSpace(dto.Userid))
  683. {
  684. dto.Userid = dto.OperationUserId.ToString();
  685. }
  686. }
  687. if (!string.IsNullOrWhiteSpace(dto.Userid))
  688. {
  689. string sql = string.Format(@"select u1.UsersId as UserId,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id and u1.UsersId in ({0}) and u1.IsDel = 0", dto.Userid);
  690. List<AscribedUser> userList = await _sqlSugar.SqlQueryable<AscribedUser>(sql).ToListAsync();
  691. if (userList.Count != 0)
  692. {
  693. foreach (var ascribedUser in userList)
  694. {
  695. if (ascribedUser.NewClientDataId != 0)
  696. {
  697. NewClientDataId1.Add(ascribedUser.NewClientDataId);
  698. }
  699. }
  700. }
  701. else
  702. {
  703. result = new Result() { Code = -1, Msg = "暂无数据" };
  704. }
  705. state = -1;
  706. }
  707. #endregion
  708. #region 业务归属
  709. if (!string.IsNullOrWhiteSpace(dto.Business))
  710. {
  711. string sql = string.Format(@"select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id and d1.SetDataId in ({0}) and d1.isdel = 0", dto.Business);
  712. List<AscribedDepartment> deptList = await _sqlSugar.SqlQueryable<AscribedDepartment>(sql).ToListAsync();
  713. if (deptList.Count != 0)
  714. {
  715. foreach (var item in deptList)
  716. {
  717. if (item.NewClientDataId != 0)
  718. {
  719. NewClientDataId2.Add(item.NewClientDataId);
  720. }
  721. }
  722. }
  723. else
  724. {
  725. result = new Result() { Code = -1, Msg = "暂无数据" };
  726. }
  727. state = -1;
  728. }
  729. #endregion
  730. List<int> intList = new List<int>();
  731. if (NewClientDataId1.Count != 0 && NewClientDataId2.Count != 0)
  732. {
  733. intList = NewClientDataId1.Intersect(NewClientDataId2).ToList();
  734. }
  735. else if (NewClientDataId1.Count != 0)
  736. {
  737. intList = NewClientDataId1;
  738. }
  739. else if (NewClientDataId2.Count != 0)
  740. {
  741. intList = NewClientDataId2;
  742. }
  743. #endregion
  744. foreach (var item in intList)
  745. {
  746. NewClientDataId += item + ",";
  747. }
  748. if (!string.IsNullOrWhiteSpace(NewClientDataId))
  749. {
  750. NewClientDataId = NewClientDataId.Substring(0, NewClientDataId.Length - 1);
  751. }
  752. string sqlWhere = string.Empty;
  753. if (dto.PortType == 1)
  754. {
  755. #region 联系人条件
  756. if (!string.IsNullOrWhiteSpace(dto.Contact))
  757. {
  758. sqlWhere += string.Format(@" And s.Contact like '%{0}%'", dto.Contact);
  759. }
  760. #endregion
  761. #region 地区条件
  762. if (!string.IsNullOrWhiteSpace(dto.Location))
  763. {
  764. sqlWhere += string.Format(@" And s.Location like '%{0}%'", dto.Location);
  765. }
  766. #endregion
  767. #region 单位条件
  768. if (!string.IsNullOrWhiteSpace(dto.Client))
  769. {
  770. sqlWhere += string.Format(@" And s.Client like '%{0}%'", dto.Client);
  771. }
  772. #endregion
  773. }
  774. else if (dto.PortType == 2 || dto.PortType == 3)
  775. {
  776. sqlWhere += string.Format("And (Contact like '%{0}%' or Location like '%{0}%' or Client like '%{0}%' )", dto.Client);
  777. }
  778. if (state == -1)
  779. {
  780. if (string.IsNullOrWhiteSpace(NewClientDataId))
  781. {
  782. NewClientDataId = "0";
  783. }
  784. sqlWhere += string.Format(@" And s.Id in({0})", NewClientDataId);
  785. }
  786. #region 地市州条件
  787. if (dto.Lvlid != 0)
  788. {
  789. sqlWhere += string.Format(@" And s.Lvlid={0}", dto.Lvlid);
  790. }
  791. #endregion
  792. #region 省域条件
  793. if (dto.Range != 0)
  794. {
  795. string setDataSql = "select * from Sys_SetData where STid = 33 and isdel = 0 ";
  796. switch (dto.Range)
  797. {
  798. case 419:
  799. setDataSql += " and (Name like '%四%川%' or Name like '%成%都%')";
  800. break;
  801. case 421:
  802. setDataSql += " and (Name like '%贵%州%' or Name like '%贵%阳%')";
  803. break;
  804. case 420:
  805. setDataSql += " and (Name like '%云%南%' or Name like '%昆%明%')";
  806. break;
  807. case 423:
  808. setDataSql += " and (Name like '%重庆%')";
  809. break;
  810. case 422:
  811. setDataSql += " and (Name like '%西%藏%' or Name like '%拉%萨%')";
  812. break;
  813. case 578:
  814. setDataSql += " and (Name like '%青%海%' or Name like '%西%宁%')";
  815. break;
  816. case 605:
  817. setDataSql += " and (Name like '%陕%西%' or Name like '%西%安%')";
  818. break;
  819. case 606:
  820. setDataSql += " and (Name like '%宁%夏%' or Name like '%银%川%')";
  821. break;
  822. case 625:
  823. setDataSql += " and (Name like '%甘%肃%' or Name like '%兰%州%')";
  824. break;
  825. case 634:
  826. setDataSql += " and (Name like '%新%疆%' or Name like '%乌%鲁%木%齐%')";
  827. break;
  828. }
  829. var RangeSetDataList = _sqlSugar.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();
  830. string lvlds = string.Join(',', RangeSetDataList).TrimEnd(',');
  831. if (!string.IsNullOrEmpty(lvlds))
  832. {
  833. sqlWhere += string.Format(@" And s.Lvlid in ({0}) ", lvlds);
  834. }
  835. }
  836. #endregion
  837. #region 客户类别
  838. if (dto.Category != 0)
  839. {
  840. sqlWhere += string.Format(@" And s.Category = {0}", dto.Category);
  841. }
  842. #endregion
  843. sqlWhere += string.Format(@" And s.Lvlid=s1.Id And s.IsDel={0} ", 0);
  844. if (!string.IsNullOrEmpty(sqlWhere.Trim()))
  845. {
  846. Regex r = new Regex("And");
  847. sqlWhere = r.Replace(sqlWhere, "Where", 1);
  848. }
  849. int pIndex = dto.PageIndex * dto.PageSize - dto.PageSize + 1;
  850. int pSize = dto.PageIndex * dto.PageSize;
  851. string sqlNew = string.Format(@"select (SELECT COUNT(1) FROM Crm_NewClientData s left Join Sys_SetData s1 On s.Lvlid=s1.Id {0}) AS CountPage,* from (select ROW_NUMBER()
  852. over(order by s.CreateTime desc) RowNumber,s.*,s1.Name as 'LvlName' from Crm_NewClientData s left Join Sys_SetData s1 On s.Lvlid=s1.Id {0}) as co where
  853. RowNumber between {1} and {2} ", sqlWhere, pIndex, pSize);
  854. List<NewClientDataView> NewClientDataView = await _sqlSugar.SqlQueryable<NewClientDataView>(sqlNew).ToListAsync();
  855. foreach (var item in NewClientDataView)
  856. {
  857. Sys_SetData CategoryStr = _sqlSugar.Queryable<Sys_SetData>().Single(it => it.Id == item.Category);
  858. if (CategoryStr != null)
  859. {
  860. item.CategoryStr = CategoryStr != null ? CategoryStr.Name : null;
  861. }
  862. Sys_SetData lvlStr = _sqlSugar.Queryable<Sys_SetData>().Single(it => it.Id == item.Lvlid);
  863. if (lvlStr != null)
  864. {
  865. item.LvlidStr = lvlStr != null ? lvlStr.Name : null;
  866. }
  867. }
  868. #region 下拉框初始化数据
  869. //负责人下拉框
  870. List<dynamic> _Users = new List<dynamic>();
  871. List<Sys_Users> users = GetNewExistClient(dto.OperationUserId);
  872. foreach (Sys_Users user in users)
  873. {
  874. var data = new
  875. {
  876. Id = user.Id,
  877. Name = user.CnName
  878. };
  879. _Users.Add(data);
  880. };
  881. //省域数据
  882. List<dynamic> _Province = new List<dynamic>();
  883. List<Sys_SetData> province = _sqlSugar.Queryable<Sys_SetData>()
  884. .Where(u => u.STid == 42 && u.IsDel == 0).ToList();
  885. foreach (Sys_SetData item in province)
  886. {
  887. var data = new
  888. {
  889. Id = item.Id,
  890. Name = item.Name
  891. };
  892. _Province.Add(data);
  893. };
  894. //客户级别数据
  895. List<dynamic> _level = new List<dynamic>();
  896. List<Sys_SetData> level = _sqlSugar.Queryable<Sys_SetData>()
  897. .Where(u => u.STid == 33 && u.IsDel == 0).ToList();
  898. foreach (Sys_SetData item in level)
  899. {
  900. var data = new
  901. {
  902. Id = item.Id,
  903. Name = item.Name
  904. };
  905. _level.Add(data);
  906. };
  907. //客户类别
  908. ArrayList _CustomerClass = new ArrayList();
  909. List<Sys_SetData> CustomerClass = _sqlSugar.Queryable<Sys_SetData>()
  910. .Where(u => u.STid == 37 && u.IsDel == 0).ToList();
  911. foreach (Sys_SetData item in CustomerClass)
  912. {
  913. var data = new
  914. {
  915. Id = item.Id,
  916. Name = item.Name,
  917. item.Remark
  918. };
  919. _CustomerClass.Add(data);
  920. };
  921. // 创建比较器实例
  922. IComparer remakeComparer = new RemakeComparer();
  923. _CustomerClass.Sort(remakeComparer);
  924. //业务分类
  925. List<dynamic> _ServiceClass = new List<dynamic>();
  926. List<Sys_SetData> ServiceClass = _sqlSugar.Queryable<Sys_SetData>()
  927. .Where(u => u.STid == 36 && u.IsDel == 0).ToList();
  928. foreach (Sys_SetData item in ServiceClass)
  929. {
  930. var data = new
  931. {
  932. Id = item.Id,
  933. Name = item.Name
  934. };
  935. _ServiceClass.Add(data);
  936. };
  937. #endregion
  938. var groupNumber = await QueryNumberGroups();
  939. if (NewClientDataView.Count > 0)
  940. {
  941. int count = NewClientDataView[0].CountPage;
  942. float totalPage = (float)count / dto.PageSize;//总页数
  943. if (totalPage == 0) totalPage = 1;
  944. else totalPage = (int)Math.Ceiling((double)totalPage);
  945. if (dto.PortType == 1)
  946. {
  947. foreach (var item in NewClientDataView)
  948. {
  949. List<AscribedUser> AscribedUser = await _sqlSugar.SqlQueryable<AscribedUser>
  950. ("select u1.UsersId as UserId ,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id and NewClientDataId=" + item.Id + " AND u1.ISDEL = 0").ToListAsync();
  951. item.AscribedUser = AscribedUser;
  952. List<AscribedDepartment> AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>
  953. ("select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id and NewClientDataId=" + item.Id + " AND d1.ISDEL = 0").ToListAsync();
  954. item.AscribedDepartment = AscribedDepartment;
  955. }
  956. var Data = new
  957. {
  958. ClientTableData = new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },
  959. Users = _Users,
  960. Province = _Province,
  961. level = _level,
  962. CustomerClass = _CustomerClass,
  963. ServiceClass = _ServiceClass,
  964. groupNumber = groupNumber.Data,
  965. };
  966. return result = new Result()
  967. {
  968. Code = 0,
  969. Msg = "查询成功",
  970. Data = Data
  971. };
  972. }
  973. else if (dto.PortType == 2 || dto.PortType == 3)
  974. {
  975. List<NewClientDataAndroidIOSView> newClientDataIOSViews = new List<NewClientDataAndroidIOSView>();
  976. foreach (var item in NewClientDataView)
  977. {
  978. newClientDataIOSViews.Add(new NewClientDataAndroidIOSView()
  979. {
  980. RowNumber = item.RowNumber,
  981. Id = item.Id,
  982. Client = item.Client,
  983. Contact = item.Contact,
  984. Job = item.Job,
  985. Telephone = item.Telephone,
  986. Location = item.Location,
  987. });
  988. }
  989. result = new Result()
  990. {
  991. Code = 0,
  992. Msg = "查询成功",
  993. Data = new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = newClientDataIOSViews },
  994. };
  995. }
  996. }
  997. else
  998. {
  999. if (dto.PortType == 2 || dto.PortType == 3)
  1000. {
  1001. var Data = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView };
  1002. result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };
  1003. }
  1004. else
  1005. {
  1006. var Data = new
  1007. {
  1008. ClientTableData = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },
  1009. Users = _Users,
  1010. Province = _Province,
  1011. level = _level,
  1012. CustomerClass = _CustomerClass,
  1013. ServiceClass = _ServiceClass,
  1014. groupNumber = groupNumber.Data,
  1015. };
  1016. result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };
  1017. }
  1018. }
  1019. }
  1020. catch (Exception ex)
  1021. {
  1022. result = new Result() { Code = -2, Msg = "未知错误" };
  1023. }
  1024. return result;
  1025. }
  1026. public Result QueryUserSelect()
  1027. {
  1028. Result result = new Result() { Code = -2, Msg = "未知错误" };
  1029. try
  1030. {
  1031. //负责人下拉框
  1032. List<dynamic> _Users = new List<dynamic>();
  1033. List<Sys_Users> users = _sqlSugar.Queryable<Sys_Users>()
  1034. .Where(u => u.IsDel == 0).ToList();
  1035. foreach (Sys_Users user in users)
  1036. {
  1037. var data = new
  1038. {
  1039. Id = user.Id,
  1040. Name = user.CnName
  1041. };
  1042. _Users.Add(data);
  1043. };
  1044. if (_Users.Count == 0)
  1045. {
  1046. result = new Result() { Code = -1, Msg = "暂无数据" };
  1047. }
  1048. result = new Result() { Code = 0, Msg = "查询成功!", Data = _Users };
  1049. }
  1050. catch (Exception)
  1051. {
  1052. result = new Result() { Code = -2, Msg = "未知错误" };
  1053. }
  1054. return result;
  1055. }
  1056. public async Task<Result> NewClientOp(NewClientOpDto dto)
  1057. {
  1058. Result result = new Result() { Code = -2, Msg = "未知错误" };
  1059. bool istrue = false;
  1060. int AddReturnId = -1;
  1061. string BirthdayStr = string.Empty;
  1062. if (!string.IsNullOrWhiteSpace(dto.Birthday))
  1063. {
  1064. DateTime Birthday = new DateTime();
  1065. var isParse = DateTime.TryParse(dto.Birthday, out Birthday);
  1066. BirthdayStr = isParse ? Birthday.ToString("yyyy-MM-dd") : "";
  1067. }
  1068. //if (string.IsNullOrWhiteSpace(dto.PassportDate))
  1069. //{
  1070. // dto.PassportDate = string.Empty;
  1071. //}
  1072. var newClientDataUnEncrypted = _mapper.Map<Crm_NewClientData>(dto);
  1073. newClientDataUnEncrypted.Birthday = BirthdayStr;
  1074. if (newClientDataUnEncrypted.PassportDate == DateTime.MinValue) newClientDataUnEncrypted.PassportDate = null;
  1075. newClientDataUnEncrypted.LastUpdateTime = DateTime.Now;
  1076. newClientDataUnEncrypted.LastUpdateUserId = dto.CreateUserId;
  1077. var newClientDataEncrypted = newClientDataUnEncrypted;
  1078. EncryptionProcessor.EncryptProperties(newClientDataEncrypted); //加密
  1079. try
  1080. {
  1081. BeginTran();
  1082. if (dto.Status == 1)//添加
  1083. {
  1084. string selectSql = string.Format(@"select * from Crm_NewClientData where Client='{0}' And Contact='{1}' And IsDel={2}"
  1085. , newClientDataEncrypted.Client, newClientDataEncrypted.Contact, 0);
  1086. var NewClientData = await _sqlSugar.SqlQueryable<Crm_NewClientData>(selectSql).FirstAsync();//查询是否存在
  1087. if (NewClientData != null)
  1088. {
  1089. result = new Result() { Code = -1, Msg = "该信息已存在,请勿重复添加!" };
  1090. }
  1091. int id = await AddAsyncReturnId(newClientDataEncrypted); //添加市场客户资料表数据
  1092. if (id == 0)
  1093. {
  1094. result = new Result() { Code = -1, Msg = "添加失败!" };
  1095. }
  1096. else
  1097. {
  1098. result = new Result() { Code = 0, Msg = "添加成功!", Data = id };
  1099. istrue = true;
  1100. AddReturnId = id;
  1101. newClientDataUnEncrypted.Id = id;
  1102. }
  1103. }
  1104. else if (dto.Status == 2)//修改
  1105. {
  1106. //DateTime? PassportDate = null;
  1107. //try
  1108. //{
  1109. // PassportDate = DateTime.Parse(dto.PassportDate);
  1110. //}
  1111. //catch (Exception)
  1112. //{
  1113. // PassportDate = null;
  1114. //}
  1115. var res = await _sqlSugar.Updateable(newClientDataEncrypted).IgnoreColumns(x => new { x.DeleteTime, x.DeleteUserId, x.CreateTime, x.CreateUserId }).ExecuteCommandAsync();
  1116. if (res > 0)
  1117. {
  1118. istrue = true;
  1119. AddReturnId = dto.Id == 0 ? -1 : dto.Id;
  1120. if (AddReturnId != -1)
  1121. {
  1122. await _sqlSugar.Updateable<Crm_ClientDataAndUser>().Where(x=>x.NewClientDataId == AddReturnId).SetColumns(a => new Crm_ClientDataAndUser()
  1123. {
  1124. IsDel = 1,
  1125. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
  1126. }).ExecuteCommandAsync();
  1127. await _sqlSugar.Updateable<Crm_ClientDataAndBusiness>().Where(x => x.NewClientDataId == AddReturnId).SetColumns(a => new Crm_ClientDataAndBusiness()
  1128. {
  1129. IsDel = 1,
  1130. DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
  1131. }).ExecuteCommandAsync();
  1132. }
  1133. newClientDataUnEncrypted.Id = AddReturnId;
  1134. result = new Result() { Code = 0, Msg = "修改成功!" };
  1135. }
  1136. else
  1137. {
  1138. result = new Result() { Code = -1, Msg = "修改失败!" };
  1139. }
  1140. }
  1141. else
  1142. {
  1143. result = new Result() { Code = -1, Msg = "请传入Status参数,1添加 2修改!" };
  1144. }
  1145. if (istrue)
  1146. {
  1147. Adds<Crm_ClientDataAndUser>(dto.AscribedUser.Select(x => new Crm_ClientDataAndUser
  1148. {
  1149. CreateTime = DateTime.Now,
  1150. CreateUserId = dto.CreateUserId,
  1151. IsDel = 0,
  1152. NewClientDataId = AddReturnId,
  1153. usersId = x
  1154. }).ToList());
  1155. Adds<Crm_ClientDataAndBusiness>(dto.AscribedDepartment.Select(x => new Crm_ClientDataAndBusiness
  1156. {
  1157. CreateUserId = dto.CreateUserId,
  1158. IsDel = 0,
  1159. CreateTime = DateTime.Now,
  1160. NewClientDataId = AddReturnId,
  1161. SetDataId = x,
  1162. }).ToList());
  1163. CommitTran();
  1164. ////缓存添加信息
  1165. //var optype = 0;
  1166. //if (dto.Status == 1) optype = 3;
  1167. //else if (dto.Status == 2) optype = 4;
  1168. ////操作缓存(未加密数据)
  1169. //await NewClientDataRedis(optype, newClientDataUnEncrypted);
  1170. result.Data = AddReturnId;
  1171. }
  1172. else
  1173. {
  1174. RollbackTran();
  1175. }
  1176. }
  1177. catch (Exception)
  1178. {
  1179. RollbackTran();
  1180. result = new Result() { Code = -2, Msg = "未知错误" };
  1181. }
  1182. return result;
  1183. }
  1184. public async Task<Result> QueryNumberGroups()
  1185. {
  1186. Result result = new Result();
  1187. //preDeleAll 预计总量
  1188. //finlishedDeleAll 已出总量
  1189. DataTable preDeleAndfinlishedDeleAll = await GetDataTableAsync("select SUM(PreDele) as PreDeleAll ,SUM(FinlishedDele) as FinlishedDeleAll from Crm_NewClientData");
  1190. var preDeleAll = preDeleAndfinlishedDeleAll.Rows[0]["PreDeleAll"].ToString();
  1191. var finlishedDeleAll = preDeleAndfinlishedDeleAll.Rows[0]["finlishedDeleAll"].ToString();
  1192. result.Code = 0;
  1193. result.Msg = "成功!";
  1194. result.Data = new
  1195. {
  1196. preDeleAll,
  1197. finlishedDeleAll
  1198. };
  1199. return result;
  1200. }
  1201. /// <summary>
  1202. /// 获取下拉列表数据和单条数据信息
  1203. /// </summary>
  1204. /// <param name="dto"></param>
  1205. public async Task<Result> QuerySelectAndSingleData(QuerySingleDto dto)
  1206. {
  1207. Result rest = new Result();
  1208. //var QueryData1 = await NewClientDataRedis(2, new Crm_NewClientData() { Id = dto.Id });
  1209. //var QueryData = QueryData1.FirstOrDefault();
  1210. var QueryData = await _sqlSugar.Queryable<Crm_NewClientData>().Where(x => x.IsDel == 0 && x.Id == dto.Id).FirstAsync();
  1211. NewClientDataView MapQueryData = null;
  1212. if (QueryData != null)
  1213. {
  1214. EncryptionProcessor.DecryptProperties(QueryData);
  1215. MapQueryData = _mapper.Map<NewClientDataView>(QueryData);
  1216. MapQueryData.AscribedUser = await _sqlSugar.SqlQueryable<AscribedUser>
  1217. ("select u1.UsersId as UserId,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id and NewClientDataId=" + dto.Id + " and u1.isdel = 0").ToListAsync();
  1218. MapQueryData.AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>
  1219. ("select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id and NewClientDataId=" + dto.Id + " and d1.isdel = 0").ToListAsync();
  1220. }
  1221. #region 下拉框初始化数据
  1222. //负责人下拉框
  1223. List<dynamic> _Users = new List<dynamic>();
  1224. List<Sys_Users> users = _sqlSugar.Queryable<Sys_Users>()
  1225. .Where(u => u.IsDel == 0).ToList();
  1226. foreach (Sys_Users user in users)
  1227. {
  1228. var data = new
  1229. {
  1230. Id = user.Id,
  1231. Name = user.CnName
  1232. };
  1233. _Users.Add(data);
  1234. };
  1235. //客户级别数据
  1236. List<dynamic> _level = new List<dynamic>();
  1237. List<Sys_SetData> level = _sqlSugar.Queryable<Sys_SetData>()
  1238. .Where(u => u.STid == 33 && u.IsDel == 0).ToList();
  1239. foreach (Sys_SetData item in level)
  1240. {
  1241. var data = new
  1242. {
  1243. Id = item.Id,
  1244. Name = item.Name
  1245. };
  1246. _level.Add(data);
  1247. };
  1248. //客户类别
  1249. ArrayList _CustomerClass = new ArrayList();
  1250. List<Sys_SetData> CustomerClass = _sqlSugar.Queryable<Sys_SetData>()
  1251. .Where(u => u.STid == 37 && u.IsDel == 0).ToList();
  1252. foreach (Sys_SetData item in CustomerClass)
  1253. {
  1254. var data = new
  1255. {
  1256. Id = item.Id,
  1257. Name = item.Name,
  1258. item.Remark
  1259. };
  1260. _CustomerClass.Add(data);
  1261. };
  1262. // 创建比较器实例
  1263. IComparer remakeComparer = new RemakeComparer();
  1264. _CustomerClass.Sort(remakeComparer);
  1265. //业务分类
  1266. List<dynamic> _ServiceClass = new List<dynamic>();
  1267. List<Sys_SetData> ServiceClass = _sqlSugar.Queryable<Sys_SetData>()
  1268. .Where(u => u.STid == 36 && u.IsDel == 0).ToList();
  1269. foreach (Sys_SetData item in ServiceClass)
  1270. {
  1271. var data = new
  1272. {
  1273. Id = item.Id,
  1274. Name = item.Name
  1275. };
  1276. _ServiceClass.Add(data);
  1277. };
  1278. #endregion
  1279. rest.Code = 0;
  1280. rest.Data = new
  1281. {
  1282. data = MapQueryData,
  1283. Users = _Users,
  1284. level = _level,
  1285. CustomerClass = _CustomerClass,
  1286. ServiceClass = _ServiceClass,
  1287. };
  1288. rest.Msg = "获取成功!";
  1289. return rest;
  1290. }
  1291. /// <summary>
  1292. /// 删除市场客户资料数据
  1293. /// </summary>
  1294. /// <param name="dto"></param>
  1295. /// <returns></returns>
  1296. public async Task<Result> DelNewClientData(DelBaseDto dto)
  1297. {
  1298. Result AcrionResult = new Result();
  1299. BeginTran();
  1300. var DBresult = await SoftDeleteByIdAsync<Crm_NewClientData>(dto.Id.ToString(), dto.DeleteUserId);
  1301. try
  1302. {
  1303. if (DBresult)
  1304. {
  1305. AcrionResult.Code = 0;
  1306. string sqlSet = $"isdel = 1, DeleteUserId = {dto.DeleteUserId} ,DeleteTime = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
  1307. string sql = $" update Crm_ClientDataAndUser set {sqlSet} where NewClientDataId = {dto.Id} ";
  1308. await ExecuteCommandAsync(sql);
  1309. sql = $" update Crm_ClientDataAndBusiness set {sqlSet} where NewClientDataId = {dto.Id} ";
  1310. await ExecuteCommandAsync(sql);
  1311. CommitTran();
  1312. //await NewClientDataRedis(5, new Crm_NewClientData() { Id = dto.Id });
  1313. AcrionResult.Code = 0;
  1314. }
  1315. }
  1316. catch (Exception ex)
  1317. {
  1318. RollbackTran();
  1319. AcrionResult.Msg = ex.Message;
  1320. AcrionResult.Code = -1;
  1321. }
  1322. return AcrionResult;
  1323. }
  1324. /// <summary>
  1325. /// 市场客户资料数据
  1326. /// 批量指派
  1327. /// </summary>
  1328. /// <param name="dto"></param>
  1329. /// <returns></returns>
  1330. public async Task<Result> _BatchAssignment(BatchAssignmentDto dto)
  1331. {
  1332. Result AcrionResult = new Result() { Code = -1,Msg="操作失败"};
  1333. if (dto.UserIdItem == null || dto.UserIdItem.Count < 1)
  1334. {
  1335. AcrionResult.Msg = "用户ID集合不能为空!";
  1336. return AcrionResult;
  1337. }
  1338. if (dto.ClientDataIdItem == null || dto.ClientDataIdItem.Count < 1)
  1339. {
  1340. AcrionResult.Msg = "客户资料ID集合不能为空!";
  1341. return AcrionResult;
  1342. }
  1343. List<Crm_ClientDataAndUser> _ClientDataAndUsers = new List<Crm_ClientDataAndUser>();
  1344. List<Crm_ClientDataAndUser> _ClientDataAndUsers1 = await _sqlSugar.Queryable<Crm_ClientDataAndUser>()
  1345. .Where(it =>
  1346. it.IsDel == 0 &&
  1347. dto.ClientDataIdItem.Contains(it.NewClientDataId) &&
  1348. dto.UserIdItem.Contains(it.usersId)
  1349. )
  1350. .ToListAsync();
  1351. var existsCount = 0;
  1352. foreach (var clientDataId in dto.ClientDataIdItem)
  1353. {
  1354. foreach (var userId1 in dto.UserIdItem)
  1355. {
  1356. Crm_ClientDataAndUser _ClientDataAndUsers2 = _ClientDataAndUsers1.Where(it => it.NewClientDataId == clientDataId &&
  1357. it.usersId == userId1
  1358. ).FirstOrDefault();
  1359. if (_ClientDataAndUsers2 == null)
  1360. {
  1361. _ClientDataAndUsers.Add(new Crm_ClientDataAndUser()
  1362. {
  1363. CreateUserId = dto.UserId,
  1364. NewClientDataId = clientDataId,
  1365. usersId = userId1
  1366. });
  1367. }
  1368. else
  1369. {
  1370. existsCount++;
  1371. }
  1372. }
  1373. }
  1374. if (_ClientDataAndUsers.Count > 0)
  1375. {
  1376. var adds = await _sqlSugar.Insertable(_ClientDataAndUsers).ExecuteCommandAsync();
  1377. if (adds > 0)
  1378. {
  1379. #region 客户资料表操作记录 批量添加
  1380. //List<Crm_TableOperationRecord> _TableOperationRecords = new List<Crm_TableOperationRecord>();
  1381. //foreach (var item in _ClientDataAndUsers)
  1382. //{
  1383. // _TableOperationRecords.Add(
  1384. // new Crm_TableOperationRecord() {
  1385. // TableName = "Crm_TableOperationRecord",
  1386. // PortType = dto.PortType,
  1387. // OperationItem = OperationEnum.BatchAssignment,
  1388. // DataId = item.NewClientDataId,
  1389. // CreateUserId = dto.UserId,
  1390. // CreateTime = DateTime.Now,
  1391. // Remark = "",
  1392. // IsDel = 0
  1393. // });
  1394. //}
  1395. //if (_TableOperationRecords.Count > 0)
  1396. //{
  1397. // await _sqlSugar.Insertable(_TableOperationRecords).ExecuteCommandAsync();
  1398. //}
  1399. #endregion
  1400. AcrionResult.Code = 0;
  1401. return AcrionResult;
  1402. }
  1403. }
  1404. else
  1405. {
  1406. if(existsCount > 0)
  1407. AcrionResult.Msg += $" {existsCount}条数据已被指派,无法重复指派!";
  1408. }
  1409. return AcrionResult;
  1410. }
  1411. public List<Sys_Users> GetNewExistClient(int userid)
  1412. {
  1413. string sql = "SELECT * FROM Sys_Users su where su.id in (\r\n\t select distinct usersid from Crm_ClientDataAndUser WHERE IsDel = 0 \r\n) \r\n";
  1414. var userArr = _sqlSugar.SqlQueryable<Sys_Users>(sql).ToList();
  1415. var dic = new Dictionary<int, int[]>()
  1416. {
  1417. { 95, new int []{ 95 , 337 , 302, 350, 355, 357, 353 , 359 , 361, 368, 364, 366, 369} }
  1418. };
  1419. try
  1420. {
  1421. var sqSetting = _sqlSugar.Queryable<Sys_SetData>().First(x => x.Id == 1417);
  1422. if (sqSetting != null)
  1423. {
  1424. Dictionary<int, int[]> result = JsonConvert.DeserializeObject<Dictionary<int, int[]>>(sqSetting.Remark);
  1425. foreach (var item in result.Keys)
  1426. {
  1427. if (dic.Keys.Contains(item))
  1428. {
  1429. int[] dilatation = new int[dic[item].Length + result[item].Length];
  1430. Array.Copy(dic[item], dilatation, dic[item].Length);
  1431. Array.Copy(result[item], 0, dilatation, dic[item].Length, result[item].Length);
  1432. dic[item] = dilatation;
  1433. }
  1434. else
  1435. {
  1436. dic.Add(item, result[item]);
  1437. }
  1438. }
  1439. }
  1440. }
  1441. catch (Exception)
  1442. {}
  1443. if (dic.Keys.Contains(userid))
  1444. {
  1445. return userArr.Where(x=> dic[userid].Contains(x.Id)).ToList();
  1446. }
  1447. return userArr.WhereIF(userid != 21 ,x=>x.Id == userid).ToList();
  1448. }
  1449. /// <summary>
  1450. /// 客户资料
  1451. /// excel download
  1452. /// </summary>
  1453. /// <param name="dto"></param>
  1454. /// <returns></returns>
  1455. public async Task<List<NewClientDataExcelDownloadView>> NewClientDataExcelDownload(NewClientDataExcelDownloadDto dto)
  1456. {
  1457. var dt = new List<NewClientDataExcelDownloadView>();
  1458. try
  1459. {
  1460. #region 交集
  1461. List<int> NewClientDataId1 = new List<int>();
  1462. List<int> NewClientDataId2 = new List<int>();
  1463. int state = 0;
  1464. #region 负责人
  1465. if (dto.OperationUserId != 21)
  1466. {
  1467. if (string.IsNullOrWhiteSpace(dto.Userid))
  1468. {
  1469. dto.Userid = dto.OperationUserId.ToString();
  1470. }
  1471. }
  1472. if (!string.IsNullOrWhiteSpace(dto.Userid))
  1473. {
  1474. string sql = string.Format(@"select u1.UsersId as UserId,u2.CnName,u1.NewClientDataId from Crm_ClientDataAndUser u1,Sys_Users u2 where u1.UsersId=u2.Id and u1.UsersId in ({0}) and u1.IsDel = 0", dto.Userid);
  1475. List<AscribedUser> ascribedUsers = await _sqlSugar.SqlQueryable<AscribedUser>(sql).ToListAsync();
  1476. if (ascribedUsers.Count != 0)
  1477. {
  1478. foreach (var ascribedUser1 in ascribedUsers)
  1479. {
  1480. if (ascribedUser1.NewClientDataId != 0)
  1481. {
  1482. NewClientDataId1.Add(ascribedUser1.NewClientDataId);
  1483. }
  1484. }
  1485. }
  1486. else
  1487. {
  1488. dt = null;
  1489. }
  1490. state = -1;
  1491. }
  1492. #endregion
  1493. #region 业务归属
  1494. if (!string.IsNullOrWhiteSpace(dto.Business))
  1495. {
  1496. string sql = string.Format(@"select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id and d1.SetDataId in ({0}) and d1.isdel = 0", dto.Business);
  1497. List<AscribedDepartment> AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>(sql).ToListAsync();
  1498. if (AscribedDepartment.Count != 0)
  1499. {
  1500. foreach (var item in AscribedDepartment)
  1501. {
  1502. if (item.NewClientDataId != 0)
  1503. {
  1504. NewClientDataId2.Add(item.NewClientDataId);
  1505. }
  1506. }
  1507. }
  1508. else
  1509. {
  1510. dt = null;
  1511. }
  1512. state = -1;
  1513. }
  1514. #endregion
  1515. List<int> intList = new List<int>();
  1516. if (NewClientDataId1.Count != 0 && NewClientDataId2.Count != 0)
  1517. {
  1518. intList = NewClientDataId1.Intersect(NewClientDataId2).ToList();
  1519. }
  1520. else if (NewClientDataId1.Count != 0)
  1521. {
  1522. intList = NewClientDataId1;
  1523. }
  1524. else if (NewClientDataId2.Count != 0)
  1525. {
  1526. if (dto.OperationUserId == 21)
  1527. {
  1528. intList = NewClientDataId2;
  1529. }
  1530. }
  1531. if (state == -1)
  1532. {
  1533. if (intList.Count < 1) intList.Add(-1);
  1534. }
  1535. #endregion
  1536. #region 省域条件
  1537. var rangeSetDataList = new List<int>();
  1538. if (dto.Range != 0)
  1539. {
  1540. string setDataSql = "select * from Sys_SetData where STid = 33 and isdel = 0 ";
  1541. switch (dto.Range)
  1542. {
  1543. case 419:
  1544. setDataSql += " and (Name like '%四%川%' or Name like '%成%都%')";
  1545. break;
  1546. case 421:
  1547. setDataSql += " and (Name like '%贵%州%' or Name like '%贵%阳%')";
  1548. break;
  1549. case 420:
  1550. setDataSql += " and (Name like '%云%南%' or Name like '%昆%明%')";
  1551. break;
  1552. case 423:
  1553. setDataSql += " and (Name like '%重庆%')";
  1554. break;
  1555. case 422:
  1556. setDataSql += " and (Name like '%西%藏%' or Name like '%拉%萨%')";
  1557. break;
  1558. case 578:
  1559. setDataSql += " and (Name like '%青%海%' or Name like '%西%宁%')";
  1560. break;
  1561. case 605:
  1562. setDataSql += " and (Name like '%陕%西%' or Name like '%西%安%')";
  1563. break;
  1564. case 606:
  1565. setDataSql += " and (Name like '%宁%夏%' or Name like '%银%川%')";
  1566. break;
  1567. case 625:
  1568. setDataSql += " and (Name like '%甘%肃%' or Name like '%兰%州%')";
  1569. break;
  1570. case 634:
  1571. setDataSql += " and (Name like '%新%疆%' or Name like '%乌%鲁%木%齐%')";
  1572. break;
  1573. }
  1574. rangeSetDataList = _sqlSugar.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();
  1575. }
  1576. #endregion
  1577. var NewClientDataView = new List<NewClientDataExcelDownloadView>();
  1578. //var count = 0;
  1579. string contact = dto.Contact, location = dto.Location, clientDto = dto.Client;
  1580. var isSelectSearch = false;
  1581. var searchDataIds = new List<int>();
  1582. if (string.IsNullOrEmpty(contact) || string.IsNullOrEmpty(location) || string.IsNullOrEmpty(clientDto))
  1583. {
  1584. isSelectSearch = true;
  1585. var searchClientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()
  1586. .Where(x => x.IsDel == 0)
  1587. .Select(x => new Crm_NewClientData() { Id = x.Id, Client = x.Client, Location = x.Location, Contact = x.Contact })
  1588. .ToListAsync();
  1589. foreach (var item in searchClientDatas) EncryptionProcessor.DecryptProperties(item);
  1590. if (dto.PortType == 1)
  1591. {
  1592. searchDataIds = searchClientDatas
  1593. .WhereIF(!string.IsNullOrEmpty(contact), x => !string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(contact)) //联系人条件
  1594. .WhereIF(!string.IsNullOrEmpty(location), x => !string.IsNullOrEmpty(x.Location) && x.Location.Contains(location)) //地区条件
  1595. .WhereIF(!string.IsNullOrEmpty(clientDto), x => !string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto)) //单位条件
  1596. .Select(x => x.Id)
  1597. .ToList();
  1598. }
  1599. else if (dto.PortType == 2 || dto.PortType == 3)
  1600. {
  1601. searchDataIds = searchClientDatas
  1602. .Where(x => (!string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(clientDto)) ||
  1603. (!string.IsNullOrEmpty(x.Location) && x.Location.Contains(clientDto)) ||
  1604. (!string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto)))
  1605. .Select(x => x.Id)
  1606. .ToList();
  1607. }
  1608. if (searchDataIds.Count < 1) searchDataIds.Add(0);
  1609. }
  1610. var clientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()
  1611. .Where(x => x.IsDel == 0)
  1612. .WhereIF(state == -1 && intList.Count > 0, x => intList.Contains(x.Id))
  1613. .WhereIF(dto.Lvlid != 0, x => x.Lvlid == dto.Lvlid) //地市州条件
  1614. .WhereIF(rangeSetDataList.Count > 0, x => rangeSetDataList.Contains(x.Lvlid)) //省域条件
  1615. .WhereIF(dto.Category > 0, x => x.Category == dto.Category) //客户类别
  1616. .WhereIF(isSelectSearch && searchDataIds.Count > 0, x => searchDataIds.Contains(x.Id)) //条件模糊查询
  1617. .OrderByDescending(x => x.CreateTime)
  1618. .ToListAsync();
  1619. NewClientDataView = _mapper.Map<List<NewClientDataExcelDownloadView>>(clientDatas);
  1620. if (!NewClientDataView.Any()) return dt;
  1621. var userDatas = await _sqlSugar.Queryable<Sys_Users>().ToListAsync();
  1622. var setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();
  1623. var ascribedUser = await _sqlSugar.SqlQueryable<AscribedUser>
  1624. ("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").ToListAsync();
  1625. var ascribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>
  1626. ("select d2.Id,d2.Name,d1.NewClientDataId from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id AND d1.ISDEL = 0").ToListAsync();
  1627. int index = 1;
  1628. foreach (var item in NewClientDataView)
  1629. {
  1630. EncryptionProcessor.DecryptProperties(item); //解密
  1631. item.RowNumber = index;
  1632. item.CreateUserName = userDatas.Find(x => x.Id == item.CreateUserId)?.CnName ?? "-";
  1633. item.CategoryStr = setDatas.Find(x => x.Id == item.Category)?.Name ?? "-";
  1634. item.LvlidStr = setDatas.Find(x => x.Id == item.Lvlid)?.Name ?? "-";
  1635. var currAscribedUser = ascribedUser.Where(x => x.NewClientDataId == item.Id).ToList();
  1636. if (currAscribedUser.Any()) item.AscribedUserLable = string.Join("、", currAscribedUser.Select(x => x.CnName).ToList());
  1637. var currAscribedDepartment = ascribedDepartment.Where(x => x.NewClientDataId == item.Id).ToList();
  1638. if (currAscribedDepartment.Any()) item.AscribedDepartmentLable = string.Join("、", currAscribedDepartment.Select(x => x.Name).ToList());
  1639. index++;
  1640. }
  1641. return NewClientDataView;
  1642. }
  1643. catch (Exception ex)
  1644. {
  1645. return dt;
  1646. }
  1647. }
  1648. /// <summary>
  1649. /// 客户资料操作记录
  1650. /// </summary>
  1651. /// <param name="dto"></param>
  1652. /// <returns></returns>
  1653. public async Task<JsonView> NewClientDataRecord(NewClientDataRecordDto dto)
  1654. {
  1655. var jsonView = new JsonView();
  1656. string whereSql = string.Empty;
  1657. if (dto.UserId != 21) whereSql += string.Format(" AND tor.CreateUserId = '{0}'", dto.UserId);
  1658. else
  1659. {
  1660. if (!string.IsNullOrEmpty(dto.OpUserLabel))
  1661. {
  1662. var userIdArray = dto.OpUserLabel.Split(',')
  1663. .Select(userId =>
  1664. {
  1665. if (int.TryParse(userId, out int id)) return id;
  1666. else return -1;
  1667. })
  1668. .ToArray();
  1669. if (userIdArray.Any(x => x != -1)) whereSql += string.Format(" AND tor.CreateUserId IN ({0})", string.Join(",", userIdArray.Where(x => x != -1).ToList()));
  1670. }
  1671. }
  1672. if (!string.IsNullOrEmpty(dto.OpTypeLabel))
  1673. {
  1674. var enumArray = dto.OpTypeLabel.Split(',')
  1675. .Select(status =>
  1676. {
  1677. if (Enum.TryParse(status, out OperationEnum result)) return result;
  1678. else return default;
  1679. })
  1680. .ToList();
  1681. //移除默认值
  1682. if (enumArray.Contains(OperationEnum.NoOperation)) enumArray.Remove(OperationEnum.NoOperation);
  1683. if (enumArray.Any())
  1684. {
  1685. if (enumArray.Contains(OperationEnum.List)) enumArray.Add(OperationEnum.NoOperation);
  1686. if (enumArray.Any()) whereSql += string.Format(" AND tor.OperationItem IN ({0})", string.Join(",", enumArray.Select(status => ((int)status).ToString())));
  1687. }
  1688. }
  1689. bool beginDateBool = DateTime.TryParse(dto.BeginTime,out _),
  1690. endDateBool = DateTime.TryParse(dto.EndTime,out _);
  1691. if (beginDateBool && endDateBool)
  1692. {
  1693. string beginLable = $"{dto.BeginTime} 00:00:00",
  1694. endLable = $"{dto.EndTime} 23:59:59";
  1695. whereSql += string.Format(" AND tor.CreateTime BETWEEN '{0}' AND '{1}'", beginLable, endLable);
  1696. }
  1697. string sql = string.Format(@"SELECT
  1698. row_number() OVER (
  1699. ORDER BY
  1700. tor.CreateTime DESC
  1701. ) 'RowNum',
  1702. tor.Id,
  1703. tor.PortType,
  1704. tor.OperationItem,
  1705. tor.DataId,
  1706. ncd.Client,
  1707. tor.CreateUserId,
  1708. u.CnName 'CreateUserName',
  1709. tor.CreateTime,
  1710. tor.UpdatePreData,
  1711. tor.UpdateBefData
  1712. FROM
  1713. OA2023DB.dbo.Crm_TableOperationRecord tor
  1714. LEFT JOIN sys_users u On tor.CreateUserId = u.Id
  1715. LEFT JOIN Crm_NewClientData ncd On tor.DataId = ncd.Id
  1716. Where
  1717. TableName = 'Crm_NewClientData'
  1718. {0}", whereSql);
  1719. RefAsync<int> total = 0;
  1720. var datas = await _sqlSugar.SqlQueryable<NewClientDataRecordInfoView>(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total);
  1721. var viewData = datas.Select(x => new NewClientDataRecordView() { RowIndex = x.RowIndex, Label = x.Label, CreateTime = x.CreateTime }).ToList();
  1722. jsonView.Data = viewData;
  1723. jsonView.Code = 200;
  1724. jsonView.Count = total;
  1725. jsonView.Msg = "查询成功!";
  1726. return jsonView;
  1727. }
  1728. }
  1729. }