using BaseOUDAL; using Microsoft.Extensions.DependencyInjection; using Org.BouncyCastle.Crypto.Tls; using Qdp.Foundation.Utilities; using System.Data; using YieldChain.Commons; using YLErp.Abstract; using YLErp.Commons; using YLErp.Model; using YLErp.Models.Tag; using YLErp.Modules.ClientModule.Dto; using YLErp.Modules.TagModule; namespace YLErp.Modules.ClientModule { /// /// 客户黑名单服务 /// public class ClientBlackService : ClientBaseService { private IKafkaProduce _kafkaProduce; public ClientBlackService(OptUserInfo userInfo) : base(userInfo) { _kafkaProduce = YLServiceLocator.ServiceProvider.GetService(); } /// /// 查询黑名单列表 /// public SearchListResult SearchList(ClientBlackReq req) { var predicate = PredicateBuilder.True(); if (req.ids != null && req.ids.Any()) { predicate = PredicateBuilder.Create(n => req.ids.Contains(n.id)); } else { if (!string.IsNullOrEmpty(req.Name)) { predicate = predicate.And(d => d.Name.Contains(req.Name)); } } var query = DbContext.client_black.AsNoTracking().Where(predicate); if (string.IsNullOrEmpty(req.sidx)) { req.sidx = "id"; req.sord = "asc"; } var retListResult = query.ToSearchList(req); if (retListResult != null && retListResult.rows != null && retListResult.rows.Any()) { var names = retListResult.rows.Select(p => p.Name).Distinct().ToList(); var clients = DbContext.client.AsNoTracking().Where(p => names.Contains(p.Name)).Select(p => new ClientSimpleDto { id = p.id, Name = p.Name }).ToList(); if (clients != null && clients.Count > 0) { Dictionary> clientTagList = null; if (clients != null && clients.Any()) { using (var tagService = new TagService(OptUser)) { clientTagList = tagService.GetTagByClientIds(clients.Select(p => p.id).Distinct().ToList()); } } if (clientTagList == null) { clientTagList = new Dictionary>(); } clients.ForEach(p => { var retInfo = retListResult.rows.FirstOrDefault(d => d.Name.Equals(p.Name)); if (retInfo != null) { //拼装标签值 if (clientTagList.ContainsKey(p.id)) { retInfo.Tags = clientTagList[p.id]; retInfo.OutputTags = TagService.GetOutputTagsStr(retInfo.Tags); } } }); } } return retListResult; } /// /// 客户黑名单导入 /// public void ImportxlsxClientBlack(Stream stream, bool checkStatus) { //当前编码支持ansi和utf with bom var ds = Office.ExcelHelper.ReadExcelAsDataSet(stream); if (ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1) { throw new ServiceException("读取导入数据失败:数据为空") { Tag = "111" }; } var table = ds.Tables[0]; if (table.Rows.Count < 1) { throw new ServiceException("导入数据不能为空!"); } var list = new List(); foreach (DataRow row in table.Rows) { if (row.IsNull("客户名称")) { throw new ServiceException("导入客户名称不能为空!"); } var importModel = new client_black { Name = row["客户名称"].ToString(), Remarks = row.IsNull("备注") ? "" : row["备注"].ToString() }; if (table.Columns.Contains("标签值") && !string.IsNullOrEmpty(row["标签值"].ToString())) { var tagStrArr = row["标签值"].ToString().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); if (tagStrArr != null && tagStrArr.Length > 0) { importModel.Tags = tagStrArr.Select(p => new YLErp.Models.Tag.TagDto { Name = p }).ToList(); } } if (list.Where(x => x.Name == importModel.Name).Count() > 0) throw new ServiceException($"第{row.Table.Rows.IndexOf(row) + 2}行客户名称:'{importModel.Name}'重复!"); else list.Add(importModel); } var importHasTagClientNames = list.Where(p => p.Tags != null && p.Tags.Count > 0).Select(p => p.Name).Distinct().ToList(); if (importHasTagClientNames != null && importHasTagClientNames.Count > 0) { var dbClientNames = DbContext.client.AsNoTracking().Where(p => importHasTagClientNames.Contains(p.Name)).Select(p => p.Name).Distinct().ToList(); if (dbClientNames != null && dbClientNames.Count > 0) { dbClientNames.ForEach(p => { importHasTagClientNames.Remove(p); }); } if (importHasTagClientNames.Count > 0) { throw new ServiceException(String.Join(",", importHasTagClientNames) + "不存在开户记录,无法设置标签值,请清除表格中对应客户的标签值再继续导入"); } } var importHasLongTagClientNames = list.Where(p => p.Tags != null && p.Tags.Any(d => d.Name.Length > 30)).Select(p => p.Name).Distinct().ToList(); if (importHasLongTagClientNames != null && importHasLongTagClientNames.Count > 0) { throw new ServiceException(String.Join(",", importHasLongTagClientNames) + "存在过长的标签值(每个标签值限制30个字符,多个以英文分号隔开),请调整完成后再导入"); } AddClientBlack(list, checkStatus); } public void AddClientBlack(IEnumerable list, bool checkStatus) { var errMsgList = new List(); var nameList = list.Select(O => O.Name); var dbList = DbContext.client_black.Where(O => nameList.Contains(O.Name)); if (checkStatus) { foreach (var item in dbList) { var obj = list.First(O => O.Name.Equals(item.Name, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrWhiteSpace(item.Remarks) && item.Remarks != obj.Remarks) { errMsgList.Add($"{item.Name}"); continue; } } if (errMsgList.Count > 0) { var msg = ""; if (errMsgList.Count <= 5) { msg = $"客户:{string.Join(",", errMsgList)},备注已存在,是否替换?"; } else { msg = $"{string.Join(",", errMsgList.Take(5))} 等{errMsgList.Count}个客户,备注已存在,是否替换?"; } throw new ServiceException(msg); } } // 在外部定义列表来保存需要通知的客户对 var clientsToNotify = new List<(Client oldClient, Client newClient)>(); foreach (var item in list) { if (string.IsNullOrWhiteSpace(item.Name)) { throw new ServiceException("导入客户名称不能为空!"); } item.Name = item.Name?.ToString() ?? ""; item.Remarks = item.Remarks?.ToString() ?? ""; item.OptId = UserId; item.OptName = UserName; item.OptDate = DateTime.Now; var clientexistence = DbContext.client.FirstOrDefault(c => c.Name == item.Name); if (clientexistence != null) { var dt = DateTime.Now; if (clientexistence.ProcessStatus == "已开户") { var oldClient= clientexistence.Clone(); clientexistence.ProcessOrderId = -4; clientexistence.ProcessStatus = "已休眠"; clientexistence.OptId = UserId; clientexistence.OptName = UserName; clientexistence.OptDate = dt; DbContext.ClientAuditLog.Add(new ClientAuditLog { ClientId = clientexistence.id, OptType = "休眠", Changes = string.Empty, DataType = "00", OptId = UserId, OptName = UserName, OptDate = dt }); // 如果原有状态是已开户,添加到通知列表 if (oldClient != null) { clientsToNotify.Add((oldClient, clientexistence)); } } ///日志记录 DbContext.ClientAuditLog.Add(new ClientAuditLog { ClientId = clientexistence.id, OptType = "加入黑名单", Changes = string.Empty, DataType = "00", OptId = UserId, OptName = UserName, OptDate = dt }); } } if (dbList.Any()) { DbContext.client_black.RemoveRange(dbList); DbContext.SaveChanges(); } DbContext.client_black.AddRange(list); DbContext.SaveChanges(); // 发送Kafka消息 foreach (var (oldClient, newClient) in clientsToNotify) { new ClientKafkaService(_kafkaProduce).Send(newClient, oldClient); } var importHasTagClientNames = list.Where(p => p.Tags != null && p.Tags.Count > 0).Select(p => p.Name).Distinct().ToList(); if (importHasTagClientNames != null && importHasTagClientNames.Count > 0) { var dbClients = DbContext.client.AsNoTracking().Where(p => importHasTagClientNames.Contains(p.Name)).Select(p => new ClientSimpleDto { id = p.id, Name = p.Name }).ToList(); if (dbClients != null && dbClients.Count > 0) { var tagService = new TagService(OptUser); dbClients.ForEach(p => { var importInfo = list.FirstOrDefault(d => d.Name.Equals(p.Name)); if (importInfo != null) { tagService.SetClientTagForClientImport(new TagModule.Dto.SetClientTagForClientEditRequest { ClientId = p.id, Tags = importInfo.Tags }); } }); } } } /// /// 黑名单导出 /// public byte[] ExportClientBlack(ClientBlackReq req) { if (req.ids == null || !req.ids.Any()) { req.ids = null; req.rows = 10000; } else { req.Name = null; } var slist = SearchList(req); var dc = new List { new ExcelHelper.DataColumnModel("客户名称", "Name"), new ExcelHelper.DataColumnModel("备注", "Remarks",typeof(string)) }; new ExcelHelper().ListToExcel(dc.ToArray(), slist.rows.ToList(), "黑名单导出", true, out var buffer); return buffer; } } }