NewClientDataRepository.cs 82 KB

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