LEIYI 2 months ago
parent
commit
ce686bd1bb

+ 82 - 3
OASystem/OASystem.Api/Controllers/CRMController.cs

@@ -1,4 +1,6 @@
-using OASystem.Domain.AesEncryption;
+using NPOI.SS.Formula.Functions;
+using OASystem.API.OAMethodLib.AMapApi;
+using OASystem.Domain.AesEncryption;
 using OASystem.Domain.Dtos.CRM;
 using OASystem.Domain.Entities.Customer;
 using OASystem.Infrastructure.Repositories.CRM;
@@ -18,13 +20,21 @@ namespace OASystem.API.Controllers
         private readonly CustomerFamilyRepository _customerFamilyRep;
         private readonly CustomerSchoolRepository _customerSchoolRep;
         private readonly CustomerCompanyRepository _customerCompanyRep;
+        private readonly GeocodeService _geocodeService;
         /// <summary>
         /// 初始化
         /// </summary>
         /// <param name="clientCompanyRepository"></param>
         /// <param name="clientRepository"></param>
-        public CRMController(VisaDeleClientCompanyRepository clientCompanyRepository, VisaDeleClientRepository clientRepository,
-            CustomerCertRepository customerCertRep, CustomerFamilyRepository customerFamilyRep, CustomerSchoolRepository customerSchoolRep, CustomerCompanyRepository customerCompanyRep)
+        public CRMController(
+            VisaDeleClientCompanyRepository clientCompanyRepository, 
+            VisaDeleClientRepository clientRepository,
+            CustomerCertRepository customerCertRep,
+            CustomerFamilyRepository customerFamilyRep, 
+            CustomerSchoolRepository customerSchoolRep, 
+            CustomerCompanyRepository customerCompanyRep,
+            GeocodeService geocodeService
+            )
         {
             this._clientCompanyRepository = clientCompanyRepository;
             this._clientRepository = clientRepository;
@@ -32,6 +42,7 @@ namespace OASystem.API.Controllers
             this._customerFamilyRep = customerFamilyRep;
             this._customerSchoolRep = customerSchoolRep;
             _customerCompanyRep = customerCompanyRep;
+            _geocodeService = geocodeService;
         }
 
         /// <summary>
@@ -303,5 +314,73 @@ namespace OASystem.API.Controllers
             return Ok(JsonView(true, "删除成功!"));
         }
 
+
+        /// <summary>
+        /// 客户资料 地址经纬度查询
+        /// </summary>
+        /// <param name="province">省份</param>
+        /// <param name="city">城市</param>
+        /// <param name="area">区域</param>
+        /// <returns></returns>
+        [HttpPost]
+        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
+        public async Task<IActionResult> ClientCompanyNautica(string province,string city,string area)
+        {
+            if (string.IsNullOrEmpty(province) && string.IsNullOrEmpty(city) && string.IsNullOrEmpty(area))
+            {
+                return Ok(JsonView(false, "省份、城市、区域,其中一个必须有值!", Array.Empty<T>()));
+            }
+
+            var datas = await _customerCertRep._sqlSugar.Queryable<Crm_NewClientData>()
+                .Where(x => x.IsDel == 0 && !string.IsNullOrEmpty(x.Address))
+                .Select(x => new Crm_NewClientData() { Id = x.Id, Address = x.Address })
+                .ToListAsync();
+            foreach (var item in datas) EncryptionProcessor.DecryptProperties(item);
+
+            var seledtIds = datas
+                .WhereIF(!string.IsNullOrEmpty(province), x => x.Address.Contains(province))
+                .WhereIF(!string.IsNullOrEmpty(city), x => x.Address.Contains(city))
+                .WhereIF(!string.IsNullOrEmpty(area), x => x.Address.Contains(area))
+                .Select(x => x.Id)
+                .ToList();
+            if (!seledtIds.Any()) return Ok(JsonView(false, "暂无相关地址信息!", Array.Empty<T>()));
+
+            var clients = await _customerCertRep._sqlSugar.Queryable<Crm_NewClientData>()
+                .Where(x => seledtIds.Contains(x.Id))
+                .Select(x => new Crm_NewClientData() { Id = x.Id, Client = x.Client, Address = x.Address })
+                .ToListAsync();
+            foreach (var item in clients) EncryptionProcessor.DecryptProperties(item);
+
+            var requestData = clients.Select(x => x.Address).ToList();
+
+            var aMapResults = await _geocodeService.GetGeocodesAsync(requestData);
+
+            var res = new List<dynamic>();
+            foreach (var item in aMapResults)
+            {
+                var client = clients.Find(x => x.Address.Equals(item.Address))?.Client ?? "-";
+                if (item.Status.Equals("Success"))
+                {
+                    res.Add(new {
+                        client = client,
+                        address = item.Address,
+                        Longitude =item.Longitude,
+                        Latitude = item.Latitude,
+                    });
+                }
+                else
+                {
+                    res.Add(new
+                    {
+                        client = client,
+                        address = item.Address,
+                        Longitude = 0d,
+                        Latitude = 0d,
+                    });
+                }
+            }
+
+            return Ok(JsonView(res));
+        }
     }
 }

+ 6 - 1
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -7738,7 +7738,8 @@ FROM
             if (info != null) parentId = info.Id;
             else
             {
-                int addId = await _sqlSugar.Insertable(new Grp_EnterExitCost() { DiId = diId, CreateUserId = currUserId }).ExecuteReturnIdentityAsync();
+                var currencys = await EnterExitCostMobileGetCurrencyInit();
+                int addId = await _sqlSugar.Insertable(new Grp_EnterExitCost() { DiId = diId, CreateUserId = currUserId, CurrencyRemark = JsonConvert.SerializeObject(currencys) }).ExecuteReturnIdentityAsync();
                 if (addId < 1) throw new CustomException("出入境费用添加失败!");
                 parentId = addId;
             }
@@ -7879,6 +7880,7 @@ FROM
             if (id <= 0) //add 
             {
                 checkboxInfo.CreateUserId = dto.CurrUserId;
+                checkboxInfo.CurrencyRemark = JsonConvert.SerializeObject(await EnterExitCostMobileGetCurrencyInit());
                 var add = await _sqlSugar.Insertable(checkboxInfo).ExecuteCommandAsync();
 
                 if (add < 1) return Ok(JsonView(false));
@@ -7938,6 +7940,7 @@ FROM
             if (id <= 0) //add 
             {
                 checkboxInfo.CreateUserId = dto.CurrUserId;
+                checkboxInfo.CurrencyRemark = JsonConvert.SerializeObject(await EnterExitCostMobileGetCurrencyInit());
                 var add = await _sqlSugar.Insertable(checkboxInfo).ExecuteCommandAsync();
 
                 if (add < 1) return Ok(JsonView(false));
@@ -7977,6 +7980,7 @@ FROM
             if (id <= 0) //add 
             {
                 info.CreateUserId = dto.CurrUserId;
+                info.CurrencyRemark = JsonConvert.SerializeObject(await EnterExitCostMobileGetCurrencyInit());
                 var add = await _sqlSugar.Insertable(info).ExecuteReturnIdentityAsync();
 
                 if (add < 1) return Ok(JsonView(false));
@@ -8038,6 +8042,7 @@ FROM
             if (id <= 0) //add 
             {
                 info.CreateUserId = dto.CurrUserId;
+                info.CurrencyRemark = JsonConvert.SerializeObject(await EnterExitCostMobileGetCurrencyInit()); 
                 var addId = await _sqlSugar.Insertable(info).ExecuteReturnIdentityAsync();
 
                 if (addId <= 0) return Ok(JsonView(false));

+ 54 - 2
OASystem/OASystem.Api/Controllers/MarketCustomerResourcesController.cs

@@ -1,10 +1,12 @@
 using Aspose.Cells;
+using Microsoft.AspNetCore.Mvc.RazorPages;
 using OASystem.API.OAMethodLib;
 using OASystem.Domain.AesEncryption;
 using OASystem.Domain.Dtos.CRM;
 using OASystem.Domain.Entities.Customer;
 using OASystem.Infrastructure.Repositories.CRM;
 using System.Collections;
+using System.Data;
 using System.Diagnostics;
 using System.Linq;
 
@@ -457,7 +459,6 @@ namespace OASystem.API.Controllers
 
 
         [HttpPost]
-        
         public IActionResult QueryClientType(QueryClientTypeDto Dto)
         {
             var jw = JsonView(true,"获取成功!");
@@ -523,7 +524,6 @@ namespace OASystem.API.Controllers
         }
 
         [HttpPost]
-
         public IActionResult QueryClientTypeSecond(QueryClientTypeDto Dto)
         {
             var jw = JsonView(true, "获取成功!");
@@ -562,6 +562,58 @@ namespace OASystem.API.Controllers
             return Ok(jw);
         }
 
+        /// <summary>
+        /// 客户资料数据 excel 下载
+        /// </summary>
+        /// <param name="dto"></param>
+        /// <returns></returns>
+        [HttpPost]
+        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
+        public async Task<IActionResult> NewClientDataExcelDownload(NewClientDataExcelDownloadDto dto)
+        {
+            #region 参数验证
+            if (dto.OperationUserId < 0) return Ok(JsonView(false, "请传入有效的OperationUserId参数!"));
+
+            if (dto.PortType < 0)  return Ok(JsonView(false, "请传入有效的PortType参数!"));
+            if (dto.PageId < 0) return Ok(JsonView(false, "请传入有效的PageId参数!"));
+            #endregion
+
+            #region 页面操作权限验证
+            var pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.OperationUserId, dto.PageId);
+
+            if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权!"));
+            #endregion
+
+            DataTable dt = await _clientDataRepository.NewClientDataExcelDownload(dto);
+            dt.TableName = $"NCDDT";
+            if (dt != null)
+            {
+                string tempPath = (AppSettingsHelper.Get("ExcelBasePath") + "Template/团组费用统计模板.xls");
+                var designer = new WorkbookDesigner();
+                designer.Workbook = new Workbook(tempPath);
+                designer.SetDataSource(dt);
+                designer.Process();
+
+                //文件名
+                string fileName = $"公司客户资料{DateTime.Now.ToString("yyyyMMddHHmmss")}.xls";
+                designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + "NewClientDataExcelDownload/" + fileName);
+                string url = AppSettingsHelper.Get("ExcelBaseUrl") + "Office/Excel/NewClientDataExcelDownload/" + fileName;
+
+                #region 客户资料表操作记录
+                await GeneralMethod.NewClientOperationRecord(dto.PortType, OperationEnum.Download, dto.OperationUserId, 0, "excel导出");
+                #endregion
+
+                return Ok(JsonView(true, "成功", url));
+            }
+            else
+            {
+                return Ok(JsonView(false));
+                }
+           
+        }
+
+
+
         #region 修改数据
         //[HttpPost]
         //public IActionResult SynchronizationData()

+ 100 - 0
OASystem/OASystem.Api/OAMethodLib/AMapApi/GeocodeService.cs

@@ -0,0 +1,100 @@
+using Microsoft.AspNetCore.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+namespace OASystem.API.OAMethodLib.AMapApi
+{
+    /// <summary>
+    /// 高德地图API Service
+    /// </summary>
+    public class GeocodeService
+    {
+        private readonly string _apiKey = "2f5a9ef15f598df3170811f50787166a"; // 高德API Key
+        private readonly HttpClient _httpClient;
+
+        /// <summary>
+        /// 初始化
+        /// </summary>
+        /// <param name="httpClient"></param>
+        public GeocodeService(HttpClient httpClient)
+        {
+            _httpClient = httpClient;
+        }
+
+        /// <summary>
+        /// 获取单个地址的经纬度
+        /// </summary>
+        /// <param name="address"></param>
+        /// <returns></returns>
+        public async Task<GeocodeResult> GetGeocodeAsync(string address)
+        {
+            if (string.IsNullOrEmpty(address)) return new GeocodeResult { Address = address, Status = "Failed", Info = "地址为空!" };
+
+            string url = $"https://restapi.amap.com/v3/geocode/geo?key={_apiKey}&address={Uri.EscapeDataString(address)}";
+            var response = await _httpClient.GetFromJsonAsync<JsonElement>(url);
+
+            if (response.GetProperty("status").GetString() == "1" && response.GetProperty("geocodes").GetArrayLength() > 0)
+            {
+                var location = response.GetProperty("geocodes")[0].GetProperty("location").GetString();
+                var coordinates = location.Split(',');
+
+                return new GeocodeResult
+                {
+                    Address = address,
+                    Longitude = double.Parse(coordinates[0]),
+                    Latitude = double.Parse(coordinates[1]),
+                    Status = "Success",
+                    Info = "OK"
+                };
+            }
+            else
+            {
+                return new GeocodeResult
+                {
+                    Address = address,
+                    Status = "Failed",
+                    Info = response.GetProperty("info").GetString()
+                };
+            }
+        }
+
+        /// <summary>
+        /// 批量获取多个地址的经纬度
+        /// </summary>
+        /// <param name="addresses"></param>
+        /// <param name="qpsLimit"></param>
+        /// <returns></returns>
+        public async Task<List<GeocodeResult>> GetGeocodesAsync(IEnumerable<string> addresses, int qpsLimit = 3)
+        {
+            var results = new List<GeocodeResult>();
+            for (int i = 0; i < addresses.Count(); i += qpsLimit)
+            {
+                // 每次处理 qpsLimit 个地址
+                var batch = addresses.Skip(i).Take(qpsLimit);
+
+                // 创建并启动任务
+                var tasks = batch.Select(GetGeocodeAsync).ToList();
+                var batchResults = await Task.WhenAll(tasks);
+
+                // 收集结果
+                results.AddRange(batchResults);
+
+                // 如果还有剩余请求,延迟一秒
+                if (i + qpsLimit < addresses.Count())
+                {
+                    await Task.Delay(1000);
+                }
+            }
+
+            return results;
+        }
+
+        public class GeocodeResult
+        {
+            public string Address { get; set; }
+            public double Latitude { get; set; }
+            public double Longitude { get; set; }
+            public string Status { get; set; }
+            public string Info { get; set; }
+        }
+    }
+}

+ 5 - 0
OASystem/OASystem.Api/Program.cs

@@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core;
 using Microsoft.Extensions.DependencyInjection.Extensions;
 using OASystem.API.Middlewares;
 using OASystem.API.OAMethodLib;
+using OASystem.API.OAMethodLib.AMapApi;
 using OASystem.API.OAMethodLib.APNs;
 using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.API.OAMethodLib.JuHeAPI;
@@ -330,6 +331,10 @@ builder.Services.AddHttpClient("PublicQiYeWeChatApi", c => c.BaseAddress = new U
 //builder.Services.AddHttpClient("PublicYouDaoApi", c => c.BaseAddress = new Uri("https://openapi.youdao.com"));
 #endregion
 
+#region ¸ßµÂµØͼAPI ·þÎñ
+builder.Services.AddHttpClient<GeocodeService>();
+#endregion
+
 #region Quartz
 
 builder.Services.AddSingleton<ISchedulerFactory, StdSchedulerFactory>();

+ 1 - 0
OASystem/OASystem.Domain/AutoMappers/_baseMappingProfile.cs

@@ -283,6 +283,7 @@ namespace OASystem.Domain.AutoMappers
             #region 新客户资料
             CreateMap<NewClientOpDto, Crm_NewClientData>();
             CreateMap<Crm_NewClientData, NewClientDataView>();
+            CreateMap<Crm_NewClientData, NewClientDataExcelDownloadView>();
             #endregion
             #endregion
 

+ 6 - 0
OASystem/OASystem.Domain/Dtos/CRM/NewClientDataQueryDto.cs

@@ -58,6 +58,12 @@ namespace OASystem.Domain.Dtos.CRM
         public int Category { get; set; }
 
     }
+
+    public class NewClientDataExcelDownloadDto : NewClientDataQueryDto
+    {
+        public int PageId { get; set; }
+    }
+
     public class NewClientOpDto:PortDtoBase
     {
         /// <summary>

+ 2 - 2
OASystem/OASystem.Domain/Entities/Customer/Crm_NewClientData.cs

@@ -23,7 +23,7 @@ namespace OASystem.Domain.Entities.Customer
         private string contact;
         private int gender;
         private string passport;
-        private DateTime? passportDate;
+        private DateTime passportDate;
         private string job;
         private string telephone;
         private string phone;
@@ -94,7 +94,7 @@ namespace OASystem.Domain.Entities.Customer
         /// 护照日期
         /// </summary>
         [SugarColumn(IsNullable = true, ColumnDataType = "DateTime")]
-        public DateTime? PassportDate { get => passportDate; set => passportDate = value; }
+        public DateTime PassportDate { get => passportDate; set => passportDate = value; }
 
         /// <summary>
         /// 职位

+ 32 - 0
OASystem/OASystem.Domain/ViewModels/CRM/NewClientDataView.cs

@@ -245,6 +245,38 @@ namespace OASystem.Domain.ViewModels.CRM
         public int NewClientDataId { get; set; }
     }
 
+
+    public class NewClientDataExcelDownloadView : Crm_NewClientData
+    {
+        /// <summary>
+        /// 编号
+        /// </summary>
+        public int RowNumber { get; set; }
+
+        /// <summary>
+        /// 客户分类
+        /// </summary>
+        public string CategoryStr { get; set; }
+
+        /// <summary>
+        /// 地市州Id
+        /// </summary>
+        public string LvlidStr { get; set; }
+
+        public string CreateUserName { get; set; }
+
+        public string SexLable
+        {
+            get
+            {
+                return Gender == 0 ? "女" : Gender == 1 ? "男" : "未设置";
+            }
+        }
+
+        public string AscribedUserLable { get; set; } = "";
+        public string AscribedDepartmentLable { get; set; } = "";
+    }
+
     public class CRMWeekStatisticsView
     {
         public string UserName { get; set; }

+ 220 - 41
OASystem/OASystem.Infrastructure/Repositories/CRM/NewClientDataRepository.cs

@@ -16,6 +16,7 @@ using OASystem.Domain.Enums;
 using OASystem.Domain.ViewModels.CRM;
 using OASystem.Domain.ViewModels.JuHeExchangeRate;
 using OASystem.Domain.ViewModels.QiYeWeChat;
+using OASystem.Infrastructure.Tools;
 using SqlSugar;
 using System;
 using System.Collections;
@@ -353,7 +354,6 @@ namespace OASystem.Infrastructure.Repositories.CRM
                 }
                 #endregion
 
-
                 var NewClientDataView = new List<NewClientDataView>();
                 var count = 0;
                 string contact = dto.Contact, location = dto.Location, clientDto = dto.Client;
@@ -1399,57 +1399,236 @@ namespace OASystem.Infrastructure.Repositories.CRM
             return userArr;
         }
 
+
+
         /// <summary>
-        /// 公司客户名单 缓存
+        /// 客户资料
+        /// excel download
         /// </summary>
-        /// <param name="opType">操作类型 1 获取全部 2 单条详情 3 添加 4 修改 5 删除</param>
-        /// <param name="data"></param>
+        /// <param name="dto"></param>
         /// <returns></returns>
-        public async Task<List<Crm_NewClientData>> NewClientDataRedis(int opType, Crm_NewClientData data = null) 
+        public async Task<DataTable> NewClientDataExcelDownload(NewClientDataExcelDownloadDto dto)
         {
-            var datas = new List<Crm_NewClientData>();
-            var opTypes = new List<int>() { 1, 2, 3, 4 };
-            if (!opTypes.Any(x => x == opType)) return datas;
-
-            var keyName = $"newClientDataStr";
-            var newClientJson = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync<string>(keyName);//string 取
-            if (!string.IsNullOrEmpty(newClientJson)) datas = JsonConvert.DeserializeObject<List<Crm_NewClientData>>(newClientJson);
-            if (opType == 1) //查询全部
+            var dt = new DataTable();
+
+            try
             {
-                if (datas != null && datas.Count > 0) return datas;
+                #region 交集
+                List<int> NewClientDataId1 = new List<int>();
+                List<int> NewClientDataId2 = new List<int>();
+                int state = 0;
 
-                datas = await _sqlSugar.Queryable<Crm_NewClientData>().Where(x => x.IsDel == 0).ToListAsync();
-                foreach (var item in datas) EncryptionProcessor.DecryptProperties(item);
+                #region 负责人
+                if (dto.OperationUserId != 21)
+                {
+                    if (string.IsNullOrWhiteSpace(dto.Userid))
+                    {
+                        dto.Userid = dto.OperationUserId.ToString();
+                    }
+                }
 
-            }
-            else if (opType == 2) //单条数据
-            {
-                if (datas != null && datas.Count > 0) return datas.Where(x => x.Id == data.Id).ToList();
+                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>().Where(x => x.IsDel == 0).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++;
+                }
+
+                dt = CommonFun.ToDataTableArray(NewClientDataView);
+                return dt;
 
-                datas = await _sqlSugar.Queryable<Crm_NewClientData>().Where(x => x.IsDel == 0).ToListAsync();
-                foreach (var item in datas) EncryptionProcessor.DecryptProperties(item);
-                await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync(keyName, JsonConvert.SerializeObject(datas));//string 存
-                return datas.Where(x => x.Id == data.Id).ToList();
-            }
-            else if (opType == 3) //添加
-            {
-                datas.Add(data);
-            }
-            else if (opType == 4) //修改
-            {
-                var updData = datas.Where(x => x.Id != data.Id).FirstOrDefault();
-                if (updData != null) datas.Remove(updData);
-                datas.Add(data);
             }
-            else if (opType == 5) //删除
+            catch (Exception ex)
             {
-                var delData = datas.Where(x => x.Id == data.Id).FirstOrDefault();
-                if (delData != null) datas.Remove(delData);
+                return dt;
             }
-
-            await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync(keyName, JsonConvert.SerializeObject(datas));//string 存
-
-            return datas;
         }
     }
 }