| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948 | using AutoMapper;using AutoMapper.Execution;using EyeSoft.Collections.Generic;using EyeSoft.Extensions;using MySqlX.XDevAPI.Relational;using Newtonsoft.Json;using NPOI.OpenXmlFormats.Dml.Diagram;using NPOI.SS.Formula.Functions;using NPOI.SS.UserModel;using NPOI.Util;using OASystem.Domain;using OASystem.Domain.AesEncryption;using OASystem.Domain.AutoMappers;using OASystem.Domain.Dtos;using OASystem.Domain.Dtos.CRM;using OASystem.Domain.Entities.Customer;using OASystem.Domain.Entities.Resource;using OASystem.Domain.Enums;using OASystem.Domain.ViewModels.CRM;using OASystem.Domain.ViewModels.JuHeExchangeRate;using OASystem.Domain.ViewModels.QiYeWeChat;using OASystem.Infrastructure.Tools;using OASystem.RedisRepository;using OASystem.RedisRepository.RedisAsyncHelper;using SqlSugar;using System;using System.Collections;using System.Collections.Generic;using System.ComponentModel.Design;using System.Diagnostics;using System.Diagnostics.Contracts;using System.Linq;using System.Reflection.Metadata;using System.Runtime.Intrinsics.Arm;using System.Text;using System.Threading.Tasks;using System.Xml.Linq;using System.Runtime.Serialization;using static Google.Protobuf.Reflection.SourceCodeInfo.Types;using static OASystem.Domain.Dtos.CRM.NewClientDataQueryDto;using Autofac;namespace OASystem.Infrastructure.Repositories.CRM{    /// <summary>    /// 客户资料仓储类    /// </summary>    public class NewClientDataRepository : BaseRepository<Crm_NewClientData, NewClientDataView>    {        private readonly IMapper _mapper;        private readonly IRedisHelper _redisHelper;        private readonly ILifetimeScope _scope;        public NewClientDataRepository(SqlSugarClient sqlSugar, IMapper mapper, ILifetimeScope scope) :         base(sqlSugar)        {            _mapper = mapper;            _redisHelper = RedisFactory.CreateRedisRepository();            this._scope = scope;        }        /// <summary>        /// 下拉框数据模型        /// </summary>        [Serializable]        public class DropdownItem        {            public int Id { get; set; }            public string Name { get; set; }            public string Remark { get; set; }        }        /// <summary>        /// 下拉框数据缓存模型        /// </summary>        [Serializable]        public class DropdownData        {            public List<DropdownItem> Users { get; set; } = new List<DropdownItem>();            public List<DropdownItem> Province { get; set; } = new List<DropdownItem>();            public List<DropdownItem> Level { get; set; } = new List<DropdownItem>();            public List<DropdownItem> CustomerClass { get; set; } = new List<DropdownItem>();            public List<DropdownItem> ServiceClass { get; set; } = new List<DropdownItem>();        }        /// <summary>        /// 获取缓存的下拉框数据        /// </summary>        /// <param name="operationUserId">操作用户ID</param>        /// <returns></returns>        private async Task<DropdownData> GetCachedDropdownDataAsync(int operationUserId)        {            var cacheKey = $"NewClientData_Dropdown_{operationUserId}";            var cachedData = await _redisHelper.StringGetAsync<DropdownData>(cacheKey);                        if (cachedData != null)            {                return cachedData;            }            var setDatas = new List<Sys_SetData>();            using var newScope = _scope.BeginLifetimeScope();            using (SqlSugarClient sc = newScope.Resolve<SqlSugarClient>())            {                setDatas = await sc.Queryable<Sys_SetData>()                .Where(x => x.IsDel == 0)                .ToListAsync();            }            var dropdownData = new DropdownData();                        //负责人下拉框            dropdownData.Users = GetNewExistClient(operationUserId)                .Select(x => new DropdownItem { Id = x.Id, Name = x.CnName })                .ToList();            //省域数据            dropdownData.Province = setDatas                .Where(u => u.STid == 42)                .Select(x => new DropdownItem { Id = x.Id, Name = x.Name })                .ToList();            //客户级别数据            dropdownData.Level = setDatas                .Where(u => u.STid == 33)                .Select(x => new DropdownItem { Id = x.Id, Name = x.Name })                .ToList();            //客户类别            var customerClassList = new List<DropdownItem>();            List<Sys_SetData> CustomerClass = setDatas                .Where(u => u.STid == 37 && u.IsDel == 0)                .ToList();            foreach (Sys_SetData item in CustomerClass)            {                customerClassList.Add(new DropdownItem                {                    Id = item.Id,                    Name = item.Name,                    Remark = item.Remark                });            }            // 按ID排序客户类别            dropdownData.CustomerClass = customerClassList.OrderBy(x => x.Id).ToList();            //业务分类             dropdownData.ServiceClass = setDatas                .Where(u => u.STid == 36)                .Select(x => new DropdownItem { Id = x.Id, Name = x.Name })                .ToList();            // 缓存30分钟            await _redisHelper.StringSetAsync(cacheKey, dropdownData, TimeSpan.FromMinutes(30));                        return dropdownData;        }        /// <summary>        /// 可序列化的关联用户信息        /// </summary>        [Serializable]        public class SerializableAscribedUser        {            public int UserId { get; set; }            public string CnName { get; set; }            public int NewClientDataId { get; set; }        }        /// <summary>        /// 可序列化的关联部门信息        /// </summary>        [Serializable]        public class SerializableAscribedDepartment        {            public int Id { get; set; }            public string Name { get; set; }            public int NewClientDataId { get; set; }        }        /// <summary>        /// 获取缓存的客户资料关联信息        /// </summary>        /// <param name="clientIds">客户ID列表</param>        /// <returns></returns>        private async Task<(List<AscribedUser> ascribedUsers, List<AscribedDepartment> ascribedDepartments)> GetCachedClientRelationsAsync(List<int> clientIds)        {            if (clientIds == null || !clientIds.Any())                return (new List<AscribedUser>(), new List<AscribedDepartment>());            var cacheKey = $"NewClientData_Relations_{string.Join("_", clientIds.OrderBy(x => x))}";            var cachedData = await _redisHelper.StringGetAsync<(List<SerializableAscribedUser>, List<SerializableAscribedDepartment>)>(cacheKey);                        if (cachedData.Item1 != null && cachedData.Item2 != null)            {                // 转换为原始类型                var ascribedUsers = cachedData.Item1.Select(x => new AscribedUser                {                    UserId = x.UserId,                    CnName = x.CnName,                    NewClientDataId = x.NewClientDataId                }).ToList();                var ascribedDepartments = cachedData.Item2.Select(x => new AscribedDepartment                {                    Id = x.Id,                    Name = x.Name,                    NewClientDataId = x.NewClientDataId                }).ToList();                return (ascribedUsers, ascribedDepartments);            }            // 批量查询关联信息 - 使用同步方法避免数据读取器问题            var queriedUsers = _sqlSugar.SqlQueryable<AscribedUser>(                "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")                .ToList();            var queriedDepartments = _sqlSugar.SqlQueryable<AscribedDepartment>(                "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")                .ToList();            // 转换为可序列化类型进行缓存            var serializableUsers = queriedUsers.Select(x => new SerializableAscribedUser            {                UserId = x.UserId,                CnName = x.CnName,                NewClientDataId = x.NewClientDataId            }).ToList();            var serializableDepartments = queriedDepartments.Select(x => new SerializableAscribedDepartment            {                Id = x.Id,                Name = x.Name,                NewClientDataId = x.NewClientDataId            }).ToList();            var result = (serializableUsers, serializableDepartments);                        // 缓存10分钟            await _redisHelper.StringSetAsync(cacheKey, result, TimeSpan.FromMinutes(10));                        return (queriedUsers, queriedDepartments);        }        /// <summary>        /// 获取缓存的省域数据        /// </summary>        /// <param name="range">省域范围</param>        /// <returns></returns>        private async Task<List<int>> GetCachedRangeSetDataAsync(int range)        {            if (range == 0) return new List<int>();            var cacheKey = $"NewClientData_Range_{range}";            var cachedData = await _redisHelper.StringGetAsync<List<int>>(cacheKey);                        if (cachedData != null)            {                return cachedData;            }            string setDataSql = "select * from Sys_SetData where STid = 33 and isdel = 0  ";            switch (range)            {                case 419:                    setDataSql += " and (Name like '%四%川%' or Name like '%成%都%')";                    break;                case 421:                    setDataSql += " and (Name like '%贵%州%' or Name like '%贵%阳%')";                    break;                case 420:                    setDataSql += " and (Name like '%云%南%' or Name like '%昆%明%')";                    break;                case 423:                    setDataSql += " and (Name like '%重庆%')";                    break;                case 422:                    setDataSql += " and (Name like '%西%藏%' or Name like '%拉%萨%')";                    break;                case 578:                    setDataSql += " and (Name like '%青%海%' or Name like '%西%宁%')";                    break;                case 605:                    setDataSql += " and (Name like '%陕%西%' or Name like '%西%安%')";                    break;                case 606:                    setDataSql += " and (Name like '%宁%夏%' or Name like '%银%川%')";                    break;                case 625:                    setDataSql += " and (Name like '%甘%肃%' or Name like '%兰%州%')";                    break;                case 634:                    setDataSql += " and (Name like '%新%疆%' or Name like '%乌%鲁%木%齐%')";                    break;            }            var rangeSetDataList = new List<int>();            using var newScope = _scope.BeginLifetimeScope();            using (SqlSugarClient sc = newScope.Resolve<SqlSugarClient>())            {                rangeSetDataList = sc.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();            }                        // 缓存1小时            await _redisHelper.StringSetAsync(cacheKey, rangeSetDataList, TimeSpan.FromHours(1));                        return rangeSetDataList;        }        /// <summary>        /// 客户资料        /// 基础数据源        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> _Init(MarketCustomerInitDto Dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            var portType = Dto.PortType;            if (portType == 1 || portType == 2 || portType == 3)            {                #region 下拉框初始化数据                //负责人下拉框                //List<dynamic> _Users = new List<dynamic>();                //var _Users = _sqlSugar.Queryable<Sys_Users>().Where(x => x.IsDel == 0).Select(x => new                //{                //    x.Id,                //    Name = x.CnName                //}).ToList();                var _Users = GetNewExistClient(Dto.UserId)                .Select(x => new                 {                     x.Id,                     Name = x.CnName                 }).ToList();                //List<Sys_Users> users = GetNewExistClient();                //foreach (Sys_Users user in users)                   //{                //    var data = new                //    {                //        Id = user.Id,                //        Name = user.CnName                //    };                //    _Users.Add(data);                //};                List<Sys_SetData> initData = _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToList();                //客户级别数据                List<dynamic> _level = new List<dynamic>();                List<Sys_SetData> level = initData.Where(u => u.STid == 33 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in level)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name                    };                    _level.Add(data);                };                //客户类别                ArrayList _CustomerClass = new ArrayList();                List<Sys_SetData> CustomerClass = initData.Where(u => u.STid == 37 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in CustomerClass)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name,                        item.Remark                    };                    _CustomerClass.Add(data);                };                // 创建比较器实例                IComparer remakeComparer = new RemakeComparer();                _CustomerClass.Sort(remakeComparer);                //业务分类                 List<dynamic> _ServiceClass = new List<dynamic>();                List<Sys_SetData> ServiceClass = initData.Where(u => u.STid == 36 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in ServiceClass)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name                    };                    _ServiceClass.Add(data);                };                //身份分类                List<dynamic> _ProvinceClass = new List<dynamic>();                List<Sys_SetData> ProvinceClass = initData.Where(u => u.STid == 42 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in ProvinceClass)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name                    };                    _ProvinceClass.Add(data);                };                #endregion                var data1 = new {                    Users = _Users,                    Level = _level,                    CustomerClass = _CustomerClass,                    ServiceClass= _ServiceClass,                    ProvinceClass = _ProvinceClass                };                return result = new Result()                {                    Code = 0,                    Msg = "查询成功",                    Data = data1                };            }            else            {                result.Msg = string.Format("请传入有效的PortType参数!");            }            return result;        }        /// <summary>        /// 市场客户资料数据        /// 详情        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> _Details(int portType,int id)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            if (portType == 1 || portType == 2 || portType == 3)            {                if (id < 0)                {                    result.Msg = string.Format("请传入有效的Id参数!");                    return result;                }                string infoSql = string.Format(@" Select * From  Crm_NewClientData Where Isdel = 0 And Id = {0}", id);                var info = await _sqlSugar.SqlQueryable<DetailsView>(infoSql).FirstAsync();                if (info != null)                {                    EncryptionProcessor.DecryptProperties(info);                    List<AscribedUser> AscribedUser = await _sqlSugar.SqlQueryable<AscribedUser>                           ("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();                    info.AscribedUser = AscribedUser.Select(it => it.UserId).ToList();                    List<AscribedDepartment> AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>                  ("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();                    info.AscribedDepartment = AscribedDepartment.Select(it => it.Id).ToList();                    result.Code = 0;                    result.Data = info;                }            }            else result.Msg = MsgTips.Port;            return result;        }        /// <summary>        /// 客户资料查询 - 优化版本        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> QueryNewClientData(NewClientDataQueryDto dto)        {            Stopwatch stopwatch = Stopwatch.StartNew();            Result result = new Result() { Code = -2, Msg = "未知错误" };            int pageIndex = dto.PageIndex, pageSize = dto.PageSize;            try            {                // 并行获取缓存数据                var rangeSetDataTask = GetCachedRangeSetDataAsync(dto.Range);                var dropdownDataTask = GetCachedDropdownDataAsync(dto.OperationUserId);                #region 交集计算优化                List<int> intList = new List<int>();                int state = 0;                // 负责人筛选                if (dto.OperationUserId != 21 && string.IsNullOrWhiteSpace(dto.Userid))                {                    dto.Userid = dto.OperationUserId.ToString();                }                List<int> NewClientDataId1 = new List<int>();                List<int> NewClientDataId2 = new List<int>();                if (!string.IsNullOrWhiteSpace(dto.Userid))                {                    string sql = string.Format(@"                      select u1.NewClientDataId                      from Crm_ClientDataAndUser u1                      where u1.IsDel = 0 AND u1.UsersId in ({0})                    ", dto.Userid);                    NewClientDataId1 = _sqlSugar.Ado.SqlQuery<int>(sql).ToList();                    state = -1;                }                // 业务归属筛选                if (!string.IsNullOrWhiteSpace(dto.Business))                {                    string sql = string.Format(@"                        select d1.NewClientDataId                      from Crm_ClientDataAndBusiness d1                      where d1.SetDataId in ({0}) and d1.isdel = 0                    ", dto.Business);                    NewClientDataId2 = _sqlSugar.Ado.SqlQuery<int>(sql).ToList();                    state = -1;                }                // 交集计算                if (NewClientDataId1.Count != 0 && NewClientDataId2.Count != 0)                {                    intList = NewClientDataId1.Intersect(NewClientDataId2).ToList();                }                else if (NewClientDataId1.Count != 0)                {                    intList = NewClientDataId1;                }                else if (NewClientDataId2.Count != 0 && dto.OperationUserId == 21)                {                    intList = NewClientDataId2;                }                if (state == -1 && intList.Count < 1)                 {                    intList.Add(-1);                }                #endregion                // 等待缓存数据                var rangeSetDataList = await rangeSetDataTask;                var dropdownData = await dropdownDataTask;                #region 模糊搜索优化                var searchDataIds = new List<int>();                var isSelectSearch = false;                string contact = dto.Contact, location = dto.Location, clientDto = dto.Client;                if (!string.IsNullOrEmpty(contact) || !string.IsNullOrEmpty(location) || !string.IsNullOrEmpty(clientDto))                {                    isSelectSearch = true;                                        // 使用缓存键进行搜索                    var searchCacheKey = $"NewClientData_Search_{contact}_{location}_{clientDto}_{dto.PortType}";                    var cachedSearchIds = await _redisHelper.StringGetAsync<List<int>>(searchCacheKey);                                        if (cachedSearchIds != null)                    {                        searchDataIds = cachedSearchIds;                    }                    else                    {                        var searchClientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()                            .Where(x => x.IsDel == 0)                            .Select(x => new Crm_NewClientData() { Id = x.Id, Client = x.Client, Location = x.Location, Contact = x.Contact })                            .ToListAsync();                        // 批量解密                        foreach (var item in searchClientDatas)                         {                            EncryptionProcessor.DecryptProperties(item);                        }                        if (dto.PortType == 1)                        {                            searchDataIds = searchClientDatas                                .WhereIF(!string.IsNullOrEmpty(contact), x => !string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(contact))                                .WhereIF(!string.IsNullOrEmpty(location), x => !string.IsNullOrEmpty(x.Location) && x.Location.Contains(location))                                .WhereIF(!string.IsNullOrEmpty(clientDto), x => !string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto))                                .Select(x => x.Id)                                .ToList();                        }                        else if (dto.PortType == 2 || dto.PortType == 3)                        {                            searchDataIds = searchClientDatas                                .Where(x => (!string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(clientDto)) ||                                            (!string.IsNullOrEmpty(x.Location) && x.Location.Contains(clientDto)) ||                                            (!string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto)))                                .Select(x => x.Id)                                .ToList();                        }                        if (searchDataIds.Count < 1) searchDataIds.Add(0);                                                // 缓存搜索结果5分钟                        await _redisHelper.StringSetAsync(searchCacheKey, searchDataIds, TimeSpan.FromMinutes(5));                    }                }                #endregion                #region 主查询                RefAsync<int> total = 0;                var clientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()                    .Where(x => x.IsDel == 0)                    .WhereIF(state == -1 && intList.Count > 0, x => intList.Contains(x.Id))                    .WhereIF(dto.Lvlid != 0, x => x.Lvlid == dto.Lvlid)                    .WhereIF(rangeSetDataList.Count > 0, x => rangeSetDataList.Contains(x.Lvlid))                    .WhereIF(dto.Category > 0, x => x.Category == dto.Category)                    .WhereIF(isSelectSearch && searchDataIds.Count > 0, x => searchDataIds.Contains(x.Id))                    .OrderByDescending(x => x.LastUpdateTime)                    .ToPageListAsync(pageIndex, pageSize, total);                var NewClientDataView = _mapper.Map<List<NewClientDataView>>(clientDatas);                var count = total;                #endregion                // 计算出团总量                var groupNumber = await QueryNumberGroups();                if (NewClientDataView.Count > 0)                {                    float totalPage = (float)count / dto.PageSize;                    if (totalPage == 0) totalPage = 1;                    else totalPage = (int)Math.Ceiling((double)totalPage);                    if (dto.PortType == 1)                    {                        // 批量获取关联信息                        var clientIds = NewClientDataView.Select(x => x.Id).ToList();                        var (ascribedUsers, ascribedDepartments) = await GetCachedClientRelationsAsync(clientIds);                        // 获取设置数据用于显示名称                        var setDatas = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToList();                        int index = 1;                        foreach (var item in NewClientDataView)                        {                            // 批量解密                            item.Weight = AesEncryptionHelper.Decrypt(item.Weight);                            item.Client = AesEncryptionHelper.Decrypt(item.Client);                            item.Contact = AesEncryptionHelper.Decrypt(item.Contact);                            item.Job = AesEncryptionHelper.Decrypt(item.Job);                            item.Telephone = AesEncryptionHelper.Decrypt(item.Telephone);                            item.Phone = AesEncryptionHelper.Decrypt(item.Phone);                            item.Location = AesEncryptionHelper.Decrypt(item.Location);                            item.Remark = AesEncryptionHelper.Decrypt(item.Remark);                            item.RowNumber = index;                            item.CategoryStr = setDatas.Find(x => x.Id == item.Category)?.Name ?? "-";                            item.LvlidStr = setDatas.Find(x => x.Id == item.Lvlid)?.Name ?? "-";                            // 从批量查询结果中获取关联信息                            item.AscribedUser = ascribedUsers.Where(x => x.NewClientDataId == item.Id).ToList();                            item.AscribedDepartment = ascribedDepartments.Where(x => x.NewClientDataId == item.Id).ToList();                                                        index++;                        }                        var Data = new                        {                            ClientTableData = new { pageCount = count.Value, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },                            Users = dropdownData.Users,                            Province = dropdownData.Province,                            level = dropdownData.Level,                            CustomerClass = dropdownData.CustomerClass,                            ServiceClass = dropdownData.ServiceClass,                            groupNumber = groupNumber.Data,                        };                                                return result = new Result()                        {                            Code = 0,                            Msg = $"查询成功!总耗时: {stopwatch.ElapsedMilliseconds} 毫秒",                            Data = Data                        };                    }                    else if (dto.PortType == 2 || dto.PortType == 3)                    {                        List<NewClientDataAndroidIOSView> newClientDataIOSViews = new List<NewClientDataAndroidIOSView>();                        int index = 1;                        foreach (var item in NewClientDataView)                        {                            newClientDataIOSViews.Add(new NewClientDataAndroidIOSView()                            {                                RowNumber = index,                                Id = item.Id,                                Client = AesEncryptionHelper.Decrypt(item.Client),                                Contact = AesEncryptionHelper.Decrypt(item.Contact),                                Job = AesEncryptionHelper.Decrypt(item.Job),                                Telephone = AesEncryptionHelper.Decrypt(item.Telephone),                                Location = AesEncryptionHelper.Decrypt(item.Location),                            });                            index++;                        }                        result = new Result()                        {                            Code = 0,                            Msg = $"查询成功!总耗时: {stopwatch.ElapsedMilliseconds} 毫秒",                            Data = new { pageCount = count.Value, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = newClientDataIOSViews },                        };                    }                }                else                {                    if (dto.PortType == 2 || dto.PortType == 3)                    {                        var Data = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView };                        result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };                    }                    else                    {                        var Data = new                        {                            ClientTableData = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },                            Users = dropdownData.Users,                            Province = dropdownData.Province,                            level = dropdownData.Level,                            CustomerClass = dropdownData.CustomerClass,                            ServiceClass = dropdownData.ServiceClass,                            groupNumber = groupNumber.Data,                        };                        result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };                    }                }            }            catch (Exception ex)            {                //记录详细错误信息                //Console.WriteLine($"QueryNewClientData 异常: {ex.Message}");                //Console.WriteLine($"异常堆栈: {ex.StackTrace}");                                result = new Result() { Code = -2, Msg = $"查询异常: {ex.Message}" };            }            finally            {                stopwatch.Stop();                if (result.Code == 0)                {                    result.Msg = $"查询成功!总耗时: {stopwatch.ElapsedMilliseconds} 毫秒";                }            }            return result;        }        /// <summary>        /// 客户资料初识初始化        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> QueryNewClientData1(NewClientDataQueryDto dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            try            {                #region 交集                List<int> NewClientDataId1 = new List<int>();                List<int> NewClientDataId2 = new List<int>();                string NewClientDataId = "";                int state = 0;                #region 负责人                if (dto.OperationUserId != 21)                {                    if (string.IsNullOrWhiteSpace(dto.Userid))                    {                        dto.Userid = dto.OperationUserId.ToString();                    }                }                if (!string.IsNullOrWhiteSpace(dto.Userid))                {                    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);                    List<AscribedUser> userList = await _sqlSugar.SqlQueryable<AscribedUser>(sql).ToListAsync();                    if (userList.Count != 0)                    {                        foreach (var ascribedUser in userList)                        {                            if (ascribedUser.NewClientDataId != 0)                            {                                NewClientDataId1.Add(ascribedUser.NewClientDataId);                            }                        }                    }                    else                    {                        result = new Result() { Code = -1, Msg = "暂无数据" };                    }                    state = -1;                }                #endregion                #region 业务归属                if (!string.IsNullOrWhiteSpace(dto.Business))                {                    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);                    List<AscribedDepartment> deptList = await _sqlSugar.SqlQueryable<AscribedDepartment>(sql).ToListAsync();                    if (deptList.Count != 0)                    {                        foreach (var item in deptList)                        {                            if (item.NewClientDataId != 0)                            {                                NewClientDataId2.Add(item.NewClientDataId);                            }                        }                    }                    else                    {                        result = new Result() { Code = -1, Msg = "暂无数据" };                    }                    state = -1;                }                #endregion                List<int> intList = new List<int>();                if (NewClientDataId1.Count != 0 && NewClientDataId2.Count != 0)                {                    intList = NewClientDataId1.Intersect(NewClientDataId2).ToList();                }                else if (NewClientDataId1.Count != 0)                {                    intList = NewClientDataId1;                }                else if (NewClientDataId2.Count != 0)                {                    intList = NewClientDataId2;                }                #endregion                foreach (var item in intList)                {                    NewClientDataId += item + ",";                }                if (!string.IsNullOrWhiteSpace(NewClientDataId))                {                    NewClientDataId = NewClientDataId.Substring(0, NewClientDataId.Length - 1);                }                string sqlWhere = string.Empty;                if (dto.PortType == 1)                {                    #region 联系人条件                    if (!string.IsNullOrWhiteSpace(dto.Contact))                    {                        sqlWhere += string.Format(@" And s.Contact like '%{0}%'", dto.Contact);                    }                    #endregion                    #region 地区条件                    if (!string.IsNullOrWhiteSpace(dto.Location))                    {                        sqlWhere += string.Format(@" And s.Location like '%{0}%'", dto.Location);                    }                    #endregion                    #region 单位条件                    if (!string.IsNullOrWhiteSpace(dto.Client))                    {                        sqlWhere += string.Format(@" And s.Client like '%{0}%'", dto.Client);                    }                    #endregion                }                else if (dto.PortType == 2 || dto.PortType == 3)                {                    sqlWhere += string.Format("And (Contact like '%{0}%' or Location  like '%{0}%' or Client like '%{0}%' )", dto.Client);                }                if (state == -1)                {                    if (string.IsNullOrWhiteSpace(NewClientDataId))                    {                        NewClientDataId = "0";                    }                    sqlWhere += string.Format(@" And s.Id in({0})", NewClientDataId);                }                #region 地市州条件                if (dto.Lvlid != 0)                {                    sqlWhere += string.Format(@" And s.Lvlid={0}", dto.Lvlid);                }                #endregion                #region 省域条件                if (dto.Range != 0)                {                    string setDataSql = "select * from Sys_SetData where STid = 33 and isdel = 0  ";                    switch (dto.Range)                    {                        case 419:                            setDataSql += " and (Name like '%四%川%' or Name like '%成%都%')";                            break;                        case 421:                            setDataSql += " and (Name like '%贵%州%' or Name like '%贵%阳%')";                            break;                        case 420:                            setDataSql += " and (Name like '%云%南%' or Name like '%昆%明%')";                            break;                        case 423:                            setDataSql += " and (Name like '%重庆%')";                            break;                        case 422:                            setDataSql += " and (Name like '%西%藏%' or Name like '%拉%萨%')";                            break;                        case 578:                            setDataSql += " and (Name like '%青%海%' or Name like '%西%宁%')";                            break;                        case 605:                            setDataSql += " and (Name like '%陕%西%' or Name like '%西%安%')";                            break;                        case 606:                            setDataSql += " and (Name like '%宁%夏%' or Name like '%银%川%')";                            break;                        case 625:                            setDataSql += " and (Name like '%甘%肃%' or Name like '%兰%州%')";                            break;                        case 634:                            setDataSql += " and (Name like '%新%疆%' or Name like '%乌%鲁%木%齐%')";                            break;                    }                    var RangeSetDataList = _sqlSugar.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();                    string lvlds = string.Join(',', RangeSetDataList).TrimEnd(',');                    if (!string.IsNullOrEmpty(lvlds))                    {                        sqlWhere += string.Format(@" And s.Lvlid in ({0}) ", lvlds);                    }                }                #endregion                #region 客户类别                if (dto.Category != 0)                {                    sqlWhere += string.Format(@" And s.Category = {0}", dto.Category);                }                #endregion                sqlWhere += string.Format(@" And s.Lvlid=s1.Id And s.IsDel={0} ", 0);                if (!string.IsNullOrEmpty(sqlWhere.Trim()))                {                    Regex r = new Regex("And");                    sqlWhere = r.Replace(sqlWhere, "Where", 1);                }                int pIndex = dto.PageIndex * dto.PageSize - dto.PageSize + 1;                int pSize = dto.PageIndex * dto.PageSize;                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()                                                     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                                                        RowNumber between {1} and {2} ", sqlWhere, pIndex, pSize);                List<NewClientDataView> NewClientDataView = await _sqlSugar.SqlQueryable<NewClientDataView>(sqlNew).ToListAsync();                foreach (var item in NewClientDataView)                {                    Sys_SetData CategoryStr = _sqlSugar.Queryable<Sys_SetData>().Single(it => it.Id == item.Category);                    if (CategoryStr != null)                    {                        item.CategoryStr = CategoryStr != null ? CategoryStr.Name : null;                    }                    Sys_SetData lvlStr = _sqlSugar.Queryable<Sys_SetData>().Single(it => it.Id == item.Lvlid);                    if (lvlStr != null)                    {                        item.LvlidStr = lvlStr != null ? lvlStr.Name : null;                    }                }                #region 下拉框初始化数据                //负责人下拉框                List<dynamic> _Users = new List<dynamic>();                List<Sys_Users> users = GetNewExistClient(dto.OperationUserId);                foreach (Sys_Users user in users)                {                    var data = new                    {                        Id = user.Id,                        Name = user.CnName                    };                    _Users.Add(data);                };                //省域数据                List<dynamic> _Province = new List<dynamic>();                List<Sys_SetData> province = _sqlSugar.Queryable<Sys_SetData>()                .Where(u => u.STid == 42 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in province)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name                    };                    _Province.Add(data);                };                //客户级别数据                List<dynamic> _level = new List<dynamic>();                List<Sys_SetData> level = _sqlSugar.Queryable<Sys_SetData>()                .Where(u => u.STid == 33 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in level)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name                    };                    _level.Add(data);                };                //客户类别                ArrayList _CustomerClass = new ArrayList();                List<Sys_SetData> CustomerClass = _sqlSugar.Queryable<Sys_SetData>()                    .Where(u => u.STid == 37 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in CustomerClass)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name,                        item.Remark                    };                    _CustomerClass.Add(data);                };                // 创建比较器实例                IComparer remakeComparer = new RemakeComparer();                _CustomerClass.Sort(remakeComparer);                //业务分类                 List<dynamic> _ServiceClass = new List<dynamic>();                List<Sys_SetData> ServiceClass = _sqlSugar.Queryable<Sys_SetData>()                .Where(u => u.STid == 36 && u.IsDel == 0).ToList();                foreach (Sys_SetData item in ServiceClass)                {                    var data = new                    {                        Id = item.Id,                        Name = item.Name                    };                    _ServiceClass.Add(data);                };                #endregion                var groupNumber = await QueryNumberGroups();                if (NewClientDataView.Count > 0)                {                    int count = NewClientDataView[0].CountPage;                    float totalPage = (float)count / dto.PageSize;//总页数                    if (totalPage == 0) totalPage = 1;                    else totalPage = (int)Math.Ceiling((double)totalPage);                    if (dto.PortType == 1)                    {                        foreach (var item in NewClientDataView)                        {                            List<AscribedUser> AscribedUser = await _sqlSugar.SqlQueryable<AscribedUser>                           ("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();                            item.AscribedUser = AscribedUser;                            List<AscribedDepartment> AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>                          ("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();                            item.AscribedDepartment = AscribedDepartment;                        }                        var Data = new                        {                            ClientTableData = new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },                            Users = _Users,                            Province = _Province,                            level = _level,                            CustomerClass = _CustomerClass,                            ServiceClass = _ServiceClass,                            groupNumber = groupNumber.Data,                        };                        return result = new Result()                        {                            Code = 0,                            Msg = "查询成功",                            Data = Data                        };                    }                    else if (dto.PortType == 2 || dto.PortType == 3)                    {                        List<NewClientDataAndroidIOSView> newClientDataIOSViews = new List<NewClientDataAndroidIOSView>();                        foreach (var item in NewClientDataView)                        {                            newClientDataIOSViews.Add(new NewClientDataAndroidIOSView()                            {                                RowNumber = item.RowNumber,                                Id = item.Id,                                Client = item.Client,                                Contact = item.Contact,                                Job = item.Job,                                Telephone = item.Telephone,                                Location = item.Location,                            });                        }                        result = new Result()                        {                            Code = 0,                            Msg = "查询成功",                            Data = new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = newClientDataIOSViews },                        };                    }                }                else                {                    if (dto.PortType == 2 || dto.PortType == 3)                    {                        var Data = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView };                        result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };                    }                     else                    {                        var Data = new                        {                            ClientTableData = new { pageCount = 0, totalPage = 0, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = NewClientDataView },                            Users = _Users,                            Province = _Province,                            level = _level,                            CustomerClass = _CustomerClass,                            ServiceClass = _ServiceClass,                            groupNumber = groupNumber.Data,                        };                        result = new Result() { Code = 0, Msg = "获取成功!", Data = Data };                    }                                    }            }            catch (Exception ex)            {                result = new Result() { Code = -2, Msg = "未知错误" };            }            return result;        }        public Result QueryUserSelect()        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            try            {                //负责人下拉框                List<dynamic> _Users = new List<dynamic>();                List<Sys_Users> users = _sqlSugar.Queryable<Sys_Users>()                .Where(u =>  u.IsDel == 0).ToList();                foreach (Sys_Users user in users)                {                    var data = new                    {                        Id = user.Id,                        Name = user.CnName                    };                    _Users.Add(data);                };                if (_Users.Count == 0)                {                    result = new Result() { Code = -1, Msg = "暂无数据" };                }                result = new Result() { Code = 0, Msg = "查询成功!", Data = _Users };            }            catch (Exception)            {                result = new Result() { Code = -2, Msg = "未知错误" };            }            return result;        }        public async Task<Result> NewClientOp(NewClientOpDto dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            bool istrue = false;            int AddReturnId = -1;                        string BirthdayStr = string.Empty;            if (!string.IsNullOrWhiteSpace(dto.Birthday))            {                DateTime Birthday = new DateTime();                var isParse = DateTime.TryParse(dto.Birthday, out Birthday);                BirthdayStr = isParse ? Birthday.ToString("yyyy-MM-dd") : "";            }            //if (string.IsNullOrWhiteSpace(dto.PassportDate))            //{            //    dto.PassportDate = string.Empty;            //}            var newClientDataUnEncrypted = _mapper.Map<Crm_NewClientData>(dto);            newClientDataUnEncrypted.Birthday = BirthdayStr;            if (newClientDataUnEncrypted.PassportDate == DateTime.MinValue) newClientDataUnEncrypted.PassportDate = null;            newClientDataUnEncrypted.LastUpdateTime = DateTime.Now;            newClientDataUnEncrypted.LastUpdateUserId = dto.CreateUserId;            var newClientDataEncrypted = newClientDataUnEncrypted;             EncryptionProcessor.EncryptProperties(newClientDataEncrypted); //加密            try            {                BeginTran();                if (dto.Status == 1)//添加                {                    string selectSql = string.Format(@"select * from Crm_NewClientData where Client='{0}' And Contact='{1}' And IsDel={2}"                                                       , newClientDataEncrypted.Client, newClientDataEncrypted.Contact, 0);                    var NewClientData = await _sqlSugar.SqlQueryable<Crm_NewClientData>(selectSql).FirstAsync();//查询是否存在                    if (NewClientData != null)                    {                        result = new Result() { Code = -1, Msg = "该信息已存在,请勿重复添加!" };                    }                    int id = await AddAsyncReturnId(newClientDataEncrypted); //添加市场客户资料表数据                    if (id == 0)                    {                        result = new Result() { Code = -1, Msg = "添加失败!" };                    }                    else                    {                        result = new Result() { Code = 0, Msg = "添加成功!", Data = id };                        istrue = true;                        AddReturnId = id;                        newClientDataUnEncrypted.Id = id;                    }                }                else if (dto.Status == 2)//修改                {                    //DateTime? PassportDate = null;                    //try                    //{                    //    PassportDate = DateTime.Parse(dto.PassportDate);                    //}                    //catch (Exception)                    //{                    //    PassportDate = null;                    //}                    var res = await _sqlSugar.Updateable(newClientDataEncrypted).IgnoreColumns(x => new { x.DeleteTime, x.DeleteUserId, x.CreateTime, x.CreateUserId }).ExecuteCommandAsync();                    if (res > 0)                    {                        istrue = true;                        AddReturnId = dto.Id == 0 ? -1 : dto.Id;                        if (AddReturnId != -1)                        {                            await _sqlSugar.Updateable<Crm_ClientDataAndUser>().Where(x=>x.NewClientDataId == AddReturnId).SetColumns(a => new Crm_ClientDataAndUser()                            {                                IsDel = 1,                                DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")                            }).ExecuteCommandAsync();                            await _sqlSugar.Updateable<Crm_ClientDataAndBusiness>().Where(x => x.NewClientDataId == AddReturnId).SetColumns(a => new Crm_ClientDataAndBusiness()                            {                                IsDel = 1,                                DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")                            }).ExecuteCommandAsync();                        }                        newClientDataUnEncrypted.Id = AddReturnId;                        result = new Result() { Code = 0, Msg = "修改成功!" };                    }                    else                    {                        result = new Result() { Code = -1, Msg = "修改失败!" };                    }                }                else                {                    result = new Result() { Code = -1, Msg = "请传入Status参数,1添加 2修改!" };                }                if (istrue)                {                    Adds<Crm_ClientDataAndUser>(dto.AscribedUser.Select(x => new Crm_ClientDataAndUser                    {                        CreateTime = DateTime.Now,                        CreateUserId = dto.CreateUserId,                        IsDel = 0,                        NewClientDataId = AddReturnId,                        usersId = x                    }).ToList());                    Adds<Crm_ClientDataAndBusiness>(dto.AscribedDepartment.Select(x => new Crm_ClientDataAndBusiness                    {                        CreateUserId = dto.CreateUserId,                        IsDel = 0,                        CreateTime = DateTime.Now,                        NewClientDataId = AddReturnId,                        SetDataId = x,                    }).ToList());                    CommitTran();                    ////缓存添加信息                    //var optype = 0;                    //if (dto.Status == 1) optype = 3;                    //else if (dto.Status == 2) optype = 4;                    ////操作缓存(未加密数据)                    //await NewClientDataRedis(optype, newClientDataUnEncrypted);                    result.Data = AddReturnId;                }                else                {                    RollbackTran();                }            }            catch (Exception)            {                RollbackTran();                result = new Result() { Code = -2, Msg = "未知错误" };            }            return result;        }        public async Task<Result> QueryNumberGroups()        {            Result result = new Result();            //preDeleAll 预计总量            //finlishedDeleAll 已出总量            DataTable preDeleAndfinlishedDeleAll = await GetDataTableAsync("select SUM(PreDele) as PreDeleAll ,SUM(FinlishedDele) as FinlishedDeleAll from Crm_NewClientData");            var preDeleAll = preDeleAndfinlishedDeleAll.Rows[0]["PreDeleAll"].ToString();            var finlishedDeleAll = preDeleAndfinlishedDeleAll.Rows[0]["finlishedDeleAll"].ToString();            result.Code = 0;            result.Msg = "成功!";            result.Data = new            {                preDeleAll,                finlishedDeleAll            };            return result;        }        /// <summary>        /// 获取下拉列表数据和单条数据信息        /// </summary>        /// <param name="dto"></param>        public async Task<Result> QuerySelectAndSingleData(QuerySingleDto dto)        {            Result rest = new Result();            //var QueryData1 = await NewClientDataRedis(2, new Crm_NewClientData() { Id = dto.Id });            //var QueryData = QueryData1.FirstOrDefault();            var QueryData = await _sqlSugar.Queryable<Crm_NewClientData>().Where(x => x.IsDel == 0 && x.Id == dto.Id).FirstAsync();            NewClientDataView MapQueryData = null;            if (QueryData != null)            {                EncryptionProcessor.DecryptProperties(QueryData);                MapQueryData = _mapper.Map<NewClientDataView>(QueryData);                MapQueryData.AscribedUser = await _sqlSugar.SqlQueryable<AscribedUser>        ("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();                MapQueryData.AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>              ("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();            }            #region 下拉框初始化数据            //负责人下拉框            List<dynamic> _Users = new List<dynamic>();            List<Sys_Users> users = _sqlSugar.Queryable<Sys_Users>()            .Where(u =>  u.IsDel == 0).ToList();            foreach (Sys_Users user in users)            {                var data = new                {                    Id = user.Id,                    Name = user.CnName                };                _Users.Add(data);            };                        //客户级别数据            List<dynamic> _level = new List<dynamic>();            List<Sys_SetData> level = _sqlSugar.Queryable<Sys_SetData>()            .Where(u => u.STid == 33 && u.IsDel == 0).ToList();            foreach (Sys_SetData item in level)            {                var data = new                {                    Id = item.Id,                    Name = item.Name                };                _level.Add(data);            };            //客户类别            ArrayList _CustomerClass = new ArrayList();            List<Sys_SetData> CustomerClass = _sqlSugar.Queryable<Sys_SetData>()                .Where(u => u.STid == 37 && u.IsDel == 0).ToList();            foreach (Sys_SetData item in CustomerClass)            {                var data = new                {                    Id = item.Id,                    Name = item.Name,                    item.Remark                };                _CustomerClass.Add(data);            };            // 创建比较器实例            IComparer remakeComparer = new RemakeComparer();            _CustomerClass.Sort(remakeComparer);            //业务分类             List<dynamic> _ServiceClass = new List<dynamic>();            List<Sys_SetData> ServiceClass = _sqlSugar.Queryable<Sys_SetData>()            .Where(u => u.STid == 36 && u.IsDel == 0).ToList();            foreach (Sys_SetData item in ServiceClass)            {                var data = new                {                    Id = item.Id,                    Name = item.Name                };                _ServiceClass.Add(data);            };            #endregion            rest.Code = 0;            rest.Data = new            {                data = MapQueryData,                Users = _Users,                level = _level,                CustomerClass = _CustomerClass,                ServiceClass = _ServiceClass,            };            rest.Msg = "获取成功!";            return rest;        }        /// <summary>        /// 删除市场客户资料数据        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> DelNewClientData(DelBaseDto dto)        {            Result AcrionResult = new Result();            BeginTran();            var DBresult = await SoftDeleteByIdAsync<Crm_NewClientData>(dto.Id.ToString(), dto.DeleteUserId);            try            {                if (DBresult)                {                    AcrionResult.Code = 0;                    string sqlSet = $"isdel = 1, DeleteUserId = {dto.DeleteUserId} ,DeleteTime = '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";                    string sql = $" update Crm_ClientDataAndUser set {sqlSet} where NewClientDataId = {dto.Id} ";                    await ExecuteCommandAsync(sql);                    sql = $" update Crm_ClientDataAndBusiness set {sqlSet} where NewClientDataId = {dto.Id} ";                    await ExecuteCommandAsync(sql);                    CommitTran();                    //await NewClientDataRedis(5, new Crm_NewClientData() { Id = dto.Id });                    AcrionResult.Code = 0;                }            }            catch (Exception ex)            {                RollbackTran();                AcrionResult.Msg = ex.Message;                AcrionResult.Code = -1;            }            return AcrionResult;        }        /// <summary>        /// 市场客户资料数据        /// 批量指派        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> _BatchAssignment(BatchAssignmentDto dto)        {            Result AcrionResult = new Result() { Code = -1,Msg="操作失败"};            if (dto.UserIdItem == null || dto.UserIdItem.Count < 1)            {                AcrionResult.Msg = "用户ID集合不能为空!";                return AcrionResult;            }            if (dto.ClientDataIdItem == null || dto.ClientDataIdItem.Count < 1)            {                AcrionResult.Msg = "客户资料ID集合不能为空!";                return AcrionResult;            }            List<Crm_ClientDataAndUser> _ClientDataAndUsers = new List<Crm_ClientDataAndUser>();            List<Crm_ClientDataAndUser> _ClientDataAndUsers1 = await _sqlSugar.Queryable<Crm_ClientDataAndUser>()                                                                              .Where(it =>                                                                                           it.IsDel == 0 &&                                                                                           dto.ClientDataIdItem.Contains(it.NewClientDataId) &&                                                                                           dto.UserIdItem.Contains(it.usersId)                                                                                     )                                                                              .ToListAsync();            var existsCount = 0;            foreach (var clientDataId in dto.ClientDataIdItem)            {                foreach (var userId1 in dto.UserIdItem)                {                    Crm_ClientDataAndUser _ClientDataAndUsers2 = _ClientDataAndUsers1.Where(it => it.NewClientDataId == clientDataId &&                                                                                                   it.usersId == userId1                                                                                            ).FirstOrDefault();                    if (_ClientDataAndUsers2 == null)                    {                        _ClientDataAndUsers.Add(new Crm_ClientDataAndUser()                        {                            CreateUserId = dto.UserId,                            NewClientDataId = clientDataId,                            usersId = userId1                        });                    }                    else                    {                        existsCount++;                    }                }            }            if (_ClientDataAndUsers.Count > 0)            {                var adds = await _sqlSugar.Insertable(_ClientDataAndUsers).ExecuteCommandAsync();                if (adds > 0)                {                    #region 客户资料表操作记录 批量添加                    //List<Crm_TableOperationRecord> _TableOperationRecords = new List<Crm_TableOperationRecord>();                    //foreach (var item in _ClientDataAndUsers)                    //{                    //    _TableOperationRecords.Add(                    //        new Crm_TableOperationRecord() {                     //            TableName = "Crm_TableOperationRecord",                    //            PortType = dto.PortType,                    //            OperationItem = OperationEnum.BatchAssignment,                    //            DataId = item.NewClientDataId,                    //            CreateUserId = dto.UserId,                    //            CreateTime = DateTime.Now,                    //            Remark = "",                    //            IsDel = 0                    //        });                    //}                    //if (_TableOperationRecords.Count > 0)                    //{                    //    await _sqlSugar.Insertable(_TableOperationRecords).ExecuteCommandAsync();                    //}                    #endregion                    AcrionResult.Code = 0;                    return AcrionResult;                }            }            else            {                if(existsCount > 0)                    AcrionResult.Msg += $" {existsCount}条数据已被指派,无法重复指派!";            }            return AcrionResult;        }        public List<Sys_Users> GetNewExistClient(int userid)        {            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";            var userArr =  _sqlSugar.SqlQueryable<Sys_Users>(sql).ToList();            var dic = new Dictionary<int, int[]>()            {                { 95, new int []{ 95 , 337 , 302, 350, 355, 357, 353 , 359 , 361, 368, 364, 366, 369} }            };            try            {                var sqSetting = _sqlSugar.Queryable<Sys_SetData>().First(x => x.Id == 1417);                if (sqSetting != null)                {                    Dictionary<int, int[]> result = JsonConvert.DeserializeObject<Dictionary<int, int[]>>(sqSetting.Remark);                    foreach (var item in result.Keys)                    {                        if (dic.Keys.Contains(item))                        {                            int[] dilatation = new int[dic[item].Length + result[item].Length];                            Array.Copy(dic[item], dilatation, dic[item].Length);                            Array.Copy(result[item], 0, dilatation, dic[item].Length, result[item].Length);                            dic[item] = dilatation;                        }                        else                        {                            dic.Add(item, result[item]);                        }                    }                }            }            catch (Exception)            {}            if (dic.Keys.Contains(userid))            {                return userArr.Where(x=> dic[userid].Contains(x.Id)).ToList();            }            return userArr.WhereIF(userid != 21 ,x=>x.Id == userid).ToList();        }        /// <summary>        /// 客户资料        /// excel download        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<List<NewClientDataExcelDownloadView>> NewClientDataExcelDownload(NewClientDataExcelDownloadDto dto)        {            var dt =  new List<NewClientDataExcelDownloadView>();            try            {                #region 交集                List<int> NewClientDataId1 = new List<int>();                List<int> NewClientDataId2 = new List<int>();                int state = 0;                #region 负责人                if (dto.OperationUserId != 21)                {                    if (string.IsNullOrWhiteSpace(dto.Userid))                    {                        dto.Userid = dto.OperationUserId.ToString();                    }                }                if (!string.IsNullOrWhiteSpace(dto.Userid))                {                    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);                    List<AscribedUser> ascribedUsers = await _sqlSugar.SqlQueryable<AscribedUser>(sql).ToListAsync();                    if (ascribedUsers.Count != 0)                    {                        foreach (var ascribedUser1 in ascribedUsers)                        {                            if (ascribedUser1.NewClientDataId != 0)                            {                                NewClientDataId1.Add(ascribedUser1.NewClientDataId);                            }                        }                    }                    else                    {                        dt = null;                    }                    state = -1;                }                #endregion                #region 业务归属                if (!string.IsNullOrWhiteSpace(dto.Business))                {                    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);                    List<AscribedDepartment> AscribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>(sql).ToListAsync();                    if (AscribedDepartment.Count != 0)                    {                        foreach (var item in AscribedDepartment)                        {                            if (item.NewClientDataId != 0)                            {                                NewClientDataId2.Add(item.NewClientDataId);                            }                        }                    }                    else                    {                        dt = null;                    }                    state = -1;                }                #endregion                List<int> intList = new List<int>();                if (NewClientDataId1.Count != 0 && NewClientDataId2.Count != 0)                {                    intList = NewClientDataId1.Intersect(NewClientDataId2).ToList();                }                else if (NewClientDataId1.Count != 0)                {                    intList = NewClientDataId1;                }                else if (NewClientDataId2.Count != 0)                {                    if (dto.OperationUserId == 21)                    {                        intList = NewClientDataId2;                    }                }                if (state == -1)                {                    if (intList.Count < 1) intList.Add(-1);                }                #endregion                #region 省域条件                var rangeSetDataList = new List<int>();                if (dto.Range != 0)                {                    string setDataSql = "select * from Sys_SetData where STid = 33 and isdel = 0  ";                    switch (dto.Range)                    {                        case 419:                            setDataSql += " and (Name like '%四%川%' or Name like '%成%都%')";                            break;                        case 421:                            setDataSql += " and (Name like '%贵%州%' or Name like '%贵%阳%')";                            break;                        case 420:                            setDataSql += " and (Name like '%云%南%' or Name like '%昆%明%')";                            break;                        case 423:                            setDataSql += " and (Name like '%重庆%')";                            break;                        case 422:                            setDataSql += " and (Name like '%西%藏%' or Name like '%拉%萨%')";                            break;                        case 578:                            setDataSql += " and (Name like '%青%海%' or Name like '%西%宁%')";                            break;                        case 605:                            setDataSql += " and (Name like '%陕%西%' or Name like '%西%安%')";                            break;                        case 606:                            setDataSql += " and (Name like '%宁%夏%' or Name like '%银%川%')";                            break;                        case 625:                            setDataSql += " and (Name like '%甘%肃%' or Name like '%兰%州%')";                            break;                        case 634:                            setDataSql += " and (Name like '%新%疆%' or Name like '%乌%鲁%木%齐%')";                            break;                    }                    rangeSetDataList = _sqlSugar.SqlQueryable<Sys_SetData>(setDataSql).Select(x => x.Id).ToList();                }                #endregion                var NewClientDataView = new List<NewClientDataExcelDownloadView>();                //var count = 0;                string contact = dto.Contact, location = dto.Location, clientDto = dto.Client;                var isSelectSearch = false;                var searchDataIds = new List<int>();                if (string.IsNullOrEmpty(contact) || string.IsNullOrEmpty(location) || string.IsNullOrEmpty(clientDto))                {                    isSelectSearch = true;                    var searchClientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()                        .Where(x => x.IsDel == 0)                        .Select(x => new Crm_NewClientData() { Id = x.Id, Client = x.Client, Location = x.Location, Contact = x.Contact })                        .ToListAsync();                    foreach (var item in searchClientDatas) EncryptionProcessor.DecryptProperties(item);                    if (dto.PortType == 1)                    {                        searchDataIds = searchClientDatas                            .WhereIF(!string.IsNullOrEmpty(contact), x => !string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(contact))     //联系人条件                            .WhereIF(!string.IsNullOrEmpty(location), x => !string.IsNullOrEmpty(x.Location) && x.Location.Contains(location)) //地区条件                            .WhereIF(!string.IsNullOrEmpty(clientDto), x => !string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto))   //单位条件                            .Select(x => x.Id)                            .ToList();                    }                    else if (dto.PortType == 2 || dto.PortType == 3)                    {                        searchDataIds = searchClientDatas                            .Where(x => (!string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(clientDto)) ||                                        (!string.IsNullOrEmpty(x.Location) && x.Location.Contains(clientDto)) ||                                        (!string.IsNullOrEmpty(x.Client) && x.Client.Contains(clientDto)))                            .Select(x => x.Id)                            .ToList();                    }                    if (searchDataIds.Count < 1) searchDataIds.Add(0);                }                var clientDatas = await _sqlSugar.Queryable<Crm_NewClientData>()                    .Where(x => x.IsDel == 0)                    .WhereIF(state == -1 && intList.Count > 0, x => intList.Contains(x.Id))                    .WhereIF(dto.Lvlid != 0, x => x.Lvlid == dto.Lvlid) //地市州条件                    .WhereIF(rangeSetDataList.Count > 0, x => rangeSetDataList.Contains(x.Lvlid)) //省域条件                    .WhereIF(dto.Category > 0, x => x.Category == dto.Category) //客户类别                    .WhereIF(isSelectSearch && searchDataIds.Count > 0, x => searchDataIds.Contains(x.Id)) //条件模糊查询                    .OrderByDescending(x => x.CreateTime)                    .ToListAsync();                NewClientDataView = _mapper.Map<List<NewClientDataExcelDownloadView>>(clientDatas);                if (!NewClientDataView.Any()) return dt;                var userDatas = await _sqlSugar.Queryable<Sys_Users>().ToListAsync();                var setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0).ToListAsync();                var ascribedUser = await _sqlSugar.SqlQueryable<AscribedUser>                  ("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();                var ascribedDepartment = await _sqlSugar.SqlQueryable<AscribedDepartment>                 ("select  d2.Id,d2.Name,d1.NewClientDataId  from Crm_ClientDataAndBusiness d1,Sys_SetData d2 where d1.SetDataId=d2.Id AND d1.ISDEL = 0").ToListAsync();                int index = 1;                foreach (var item in NewClientDataView)                {                    EncryptionProcessor.DecryptProperties(item); //解密                    item.RowNumber = index;                    item.CreateUserName = userDatas.Find(x => x.Id == item.CreateUserId)?.CnName ?? "-";                    item.CategoryStr = setDatas.Find(x => x.Id == item.Category)?.Name ?? "-";                    item.LvlidStr = setDatas.Find(x => x.Id == item.Lvlid)?.Name ?? "-";                    var currAscribedUser = ascribedUser.Where(x => x.NewClientDataId == item.Id).ToList();                    if (currAscribedUser.Any()) item.AscribedUserLable = string.Join("、", currAscribedUser.Select(x => x.CnName).ToList());                    var currAscribedDepartment = ascribedDepartment.Where(x => x.NewClientDataId == item.Id).ToList();                    if (currAscribedDepartment.Any()) item.AscribedDepartmentLable = string.Join("、", currAscribedDepartment.Select(x => x.Name).ToList());                    index++;                }                return NewClientDataView;            }            catch (Exception ex)            {                return dt;            }        }        /// <summary>        /// 客户资料操作记录        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<JsonView> NewClientDataRecord(NewClientDataRecordDto dto)        {            var jsonView = new JsonView();            string whereSql = string.Empty;            if (dto.UserId != 21) whereSql += string.Format(" AND tor.CreateUserId = '{0}'", dto.UserId);            else            {                if (!string.IsNullOrEmpty(dto.OpUserLabel))                {                    var userIdArray = dto.OpUserLabel.Split(',')                        .Select(userId =>                        {                            if (int.TryParse(userId, out int id)) return id;                            else return -1;                        })                        .ToArray();                    if (userIdArray.Any(x => x != -1)) whereSql += string.Format(" AND tor.CreateUserId IN ({0})", string.Join(",", userIdArray.Where(x => x != -1).ToList()));                }            }            if (!string.IsNullOrEmpty(dto.OpTypeLabel))            {                var enumArray = dto.OpTypeLabel.Split(',')                    .Select(status =>                    {                        if (Enum.TryParse(status, out OperationEnum result)) return result;                        else return default;                    })                    .ToList();                //移除默认值                if (enumArray.Contains(OperationEnum.NoOperation)) enumArray.Remove(OperationEnum.NoOperation);                if (enumArray.Any())                {                    if (enumArray.Contains(OperationEnum.List)) enumArray.Add(OperationEnum.NoOperation);                    if (enumArray.Any()) whereSql += string.Format(" AND tor.OperationItem IN ({0})", string.Join(",", enumArray.Select(status => ((int)status).ToString())));                }            }            bool beginDateBool = DateTime.TryParse(dto.BeginTime,out _),                 endDateBool = DateTime.TryParse(dto.EndTime,out _);            if (beginDateBool && endDateBool)            {                string beginLable = $"{dto.BeginTime} 00:00:00",                       endLable = $"{dto.EndTime} 23:59:59";                whereSql += string.Format(" AND tor.CreateTime BETWEEN '{0}' AND '{1}'", beginLable, endLable);            }            string sql = string.Format(@"SELECT  row_number() OVER (    ORDER BY      tor.CreateTime DESC  ) 'RowNum',  tor.Id,  tor.PortType,  tor.OperationItem,  tor.DataId,  ncd.Client,  tor.CreateUserId,  u.CnName 'CreateUserName',  tor.CreateTime,  tor.UpdatePreData,  tor.UpdateBefDataFROM  OA2023DB.dbo.Crm_TableOperationRecord tor  LEFT JOIN sys_users u On tor.CreateUserId = u.Id  LEFT JOIN Crm_NewClientData ncd On tor.DataId = ncd.IdWhere  TableName = 'Crm_NewClientData'  {0}", whereSql);            RefAsync<int> total = 0;            var datas = await _sqlSugar.SqlQueryable<NewClientDataRecordInfoView>(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total);            var viewData = datas.Select(x => new NewClientDataRecordView() { RowIndex = x.RowIndex, Label = x.Label, CreateTime = x.CreateTime }).ToList();            jsonView.Data = viewData;            jsonView.Code = 200;            jsonView.Count = total;            jsonView.Msg = "查询成功!";            return jsonView;        }    }}
 |