NewClientDataRepository.cs 82 KB

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