NewClientDataRepository.cs 82 KB

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