using FluentFTP.Helpers; using MoreLinq; using NPOI.SS.Formula.Functions; using System.Data; using System.Linq; using System.Text.RegularExpressions; using YLErp.BLL; using YLErp.Commons; using YLErp.DBModels.Consts; using YLErp.DBModels.Enums; using YLErp.Helpers; using YLErp.Modules.EodModule; using YLErp.Modules.SuperviseReportModule.SAC.Common; using YLErp.Modules.SuperviseReportModule.SAC.Model; using static YLErp.DBModels.Consts.ConsReport; namespace YLErp.Modules.SuperviseReportModule.SAC.Service { //交易存续期管理 class ReportOptionTerminationService : ReportBaseService { public ReportOptionTerminationService(OptUserInfo optUser) : base(optUser) { } protected override string _excelDataSourcePath => "交易相关\\"; protected override string _excelDataSourceFileName => "import_OptionTermination_template.xlsx"; protected override DataFlagsEnum BusiDataType => DataFlagsEnum.A1007; private List? _validOperationType = null; public override List ValidOperationType { get { _validOperationType ??= new List() { OptFlagsEnum.A, OptFlagsEnum.D, OptFlagsEnum.U, }; return _validOperationType; } } protected override SuperviseReportTypeEnum ReportType => SuperviseReportTypeEnum.SAC_OptionTermination; readonly List noteList = new(); private readonly List _cacheCodeList = new(); protected override BodyModel GenerateBody(out bool noData, out List fileList) { fileList = new List(); var model = new BodyModel(); var dataList = new List(); //if (_reqInfo.DataSource.HasFlag(SAC_ReportDataSourceEnum.Template)) //{ dataList = GetOptionTerminationModel(ref fileList); //} var subsystemDataList = loadSubsystemDataSource(fileList, AddSubsystemNote); if (subsystemDataList != null && subsystemDataList.Count > 0) { dataList.AddRange(subsystemDataList); } noData = dataList.Count == 0; model.OptionTermination = dataList; return model; } public bool AddSubsystemNote(OptionTerminationModel model, List fileList, string tag) { var isExtensionTime = model.DurationOperationType == ConsReport.OperationTypeMap["展期"]; var date = DateTime.MinValue; if (isExtensionTime) { DateTime.TryParse(model.RenewalDate, out date); } else { DateTime.TryParse(model.ExpirationDate, out date); } var extensionTimeInfo = model.DurationOperationType == ConsReport.OperationTypeMap["展期"] ? "-" : ""; var notes = base.GetReportNotes(ReportType, $"_{model.ConfirmationNo.Replace("_", "-")}_{_operationType}", true);//添加了operationType,要不A和D会查到同一条记录,在D时候,就会和A相同的数据 //永远查找现有成功报送了结的新增记录,而不是修改; var note = notes.LastOrDefault(O => O.IsValid && O.InfoTag.Contains(formatInfoTag(model, extensionTimeInfo: extensionTimeInfo)) && O.InfoCache.Contains(date.ToString("yyyy-MM-dd"))); if (note == null) { if (isExtensionTime) { var oldDateStr = ""; var oldData = base.GetReportNotes(SuperviseReportTypeEnum.SAC_OptionConfirmation, $"A1004_{model.ConfirmationNo.Replace("_", "-")}_成交_A").FirstOrDefault(); oldDateStr = Regex.Match(oldData?.InfoCache ?? "", "(?<=DueDate\":\")[^\"]+(?=\")").Value; if (DateTime.TryParse(oldDateStr, out var oldDate)) { oldDateStr = $",\"OldMaturityDate\":\"{oldDate.ToString("yyyy-MM-dd")}\""; } note = new SACReportNotes() { InfoCache = $"{{\"Tag\":\"{model.ConfirmationNo}\"{oldDateStr},\"NewMaturityDate\":\"{date.ToString("yyyy-MM-dd")}\",\"Source\":\"Subsystem\",\"SubFileTag\":\"{tag}\",\"ExceID\":\"{model.ExceID}\"}}", IsValid = true, }; } else { note = new SACReportNotes() { InfoCache = $"{{\"Tag\":\"{model.ConfirmationNo}\",\"ValueDate\":\"{date.ToString("yyyy-MM-dd")}\",\"Source\":\"Subsystem\",\"SubFileTag\":\"{tag}\",\"ExceID\":\"{model.ExceID}\"}}", IsValid = true, }; } } else//多次U的时候,每次用最新的tag来赋值SubFileTag { switch (model.OperationType) { case OptFlagsEnum.A: return false;//新增数据已报送,跳过 case OptFlagsEnum.U: //多次U的时候,每次用最新的tag来赋值SubFileTag if (isExtensionTime) { var oldDateStr = ""; var oldData = base.GetReportNotes(SuperviseReportTypeEnum.SAC_OptionConfirmation, $"A1004_{model.ConfirmationNo.Replace("_", "-")}_成交_A").FirstOrDefault(); oldDateStr = Regex.Match(oldData?.InfoCache ?? "", "(?<=DueDate\":\")[^\"]+(?=\")").Value; if (DateTime.TryParse(oldDateStr, out var oldDate)) { oldDateStr = $",\"OldMaturityDate\":\"{oldDate.ToString("yyyy-MM-dd")}\""; } note.InfoCache = $"{{\"Tag\":\"{model.ConfirmationNo}\"{oldDateStr},\"NewMaturityDate\":\"{date.ToString("yyyy-MM-dd")}\",\"Source\":\"Subsystem\",\"SubFileTag\":\"{tag}\",\"ExceID\":\"{model.ExceID}\"}}"; } else { note.InfoCache = $"{{\"Tag\":\"{model.ConfirmationNo}\",\"ValueDate\":\"{date.ToString("yyyy-MM-dd")}\",\"Source\":\"Subsystem\",\"SubFileTag\":\"{tag}\",\"ExceID\":\"{model.ExceID}\"}}"; } note.IsValid = true; break; case OptFlagsEnum.D:// note.IsValid = false; break; case OptFlagsEnum.NONE: default: throw new ServiceException("未知操作类型"); } } model.ExceID = base.formatExceID(); note.id = 0; note.ExceId = model.ExceID; note.CreateTime = DateTime.Now; note.FileTag = FileTag; note.ReportType = ReportType; note.ReportDate = _reqInfo.ReportDate; note.InfoTag = formatInfoTag(model, true); note.OptTime = note.CreateTime; note.RetCode = ""; note.RetMsg = ""; note.ReportResponse = false; note.BizId = ""; note.changeStatus = false; noteList.Add(note); return true; } /// /// 格式化报送标签,用于关联报表和业务信息 /// /// /// /// /// private string formatInfoTag(OptionTerminationModel model, bool suffixType = false, string extensionTimeInfo = "") { var operationTag = ""; if (model.DurationOperationType == ConsReport.OperationTypeMap["敲入"] || model.DurationOperationType == ConsReport.OperationTypeMap["敲出"]) { operationTag = $"_{model.DurationOperationType}"; } string result = $"{formatInfoTagStr(model)}{operationTag}_{model.DurationEventNO}_"; if (suffixType) { result = $"{result}{_operationType}"; } return result; } private string formatInfoTagStr(OptionTerminationModel model, string extensionTimeInfo = "") { string result = $"{BusiDataType}_{model.ConfirmationNo.Replace("_", "-")}_{(string.IsNullOrWhiteSpace(extensionTimeInfo) ? "了结" : ($"_{extensionTimeInfo}_展期"))}"; return result; } protected override string _changeCodeOfInfoTag(string infoTag, string newCode, out string originalCode) { var arr = infoTag.Split('_'); if (arr.Length != 5 && arr.Length != 6) { throw new ServiceException($"InfoTag信息不匹配:{infoTag}"); } originalCode = arr[1]; arr[1] = newCode.Replace("_", "-"); return string.Join("_", arr); } /// /// 从Excel获取结算信息 /// /// private List GetOptionTerminationModel(ref List fileList) { var result = new List(); string path = ""; if (_excelDataSource != null && _excelDataSource.Tables.Contains("期权交易存续期明细")) { string sourcePath = Path.Combine(_excelDataSourceRootPath, "附件"); var dt = _excelDataSource.Tables["期权交易存续期明细"]; for (var i = 1; i < dt.Rows.Count; i++) { if (string.IsNullOrWhiteSpace(dt.Rows[i][0]?.ToString())) { //第一列空白说明数据结束了; break; } var optType = OptFlagsEnum.NONE; switch (dt.Rows[i][2]?.ToString()) { case "0": case "A": case "首次": optType = OptFlagsEnum.A; break; case "1": case "U": case "变更": optType = OptFlagsEnum.U; break; case "2": case "D": case "废止": optType = OptFlagsEnum.D; break; } if (optType != _operationType) { continue; } DateTime.TryParse(GetDataSetValue(dt, i, 4), out DateTime expirationDate); var model = new OptionTerminationModel { DurationEventNO = GetDataSetValue(dt, i, 0), ConfirmationNo = GetDataSetValue(dt, i, 1), OperationType = optType, DurationOperationType = ConsReport.OperationTypeMap[GetDataSetValue(dt, i, 3)], ExpirationDate = expirationDate == DateTime.MinValue ? null : expirationDate.ToString("yyyy-MM-dd"), RenewalDate = GetDataSetValue(dt, i, 5), }; model.DefaultingParty = ConsReport.FillPartyMap[GetDataSetValue(dt, i, 6)]; model.DefaultEvent = GetDataSetValue(dt, i, 7); model.TerminationAmount = GetDataSetValue(dt, i, 8); model.Balance = GetDataSetValueToDoubleOrNull(dt, i, 9)?.ToString("0.00"); model.AmountPaidThisTime = GetDataSetValue(dt, i, 10); model.ClosedTransactionsRealRateReturn = GetDataSetValue(dt, i, 11); // model.TerminationAmount = GetDataSetValueToDouble(dt, i, 8).ToString("0.00"); // model.Balance = GetDataSetValueToDouble(dt, i, 9).ToString("0.00"); // model.AmountPaidThisTime = GetDataSetValueToDouble(dt, i, 10).ToString("0.00"); // model.ClosedTransactionsRealRateReturn = GetDataSetValueToDouble(dt, i, 11).ToString("0.00"); model.OptionDurationManagementAtt = GetDataSetValue(dt, i, 12); var eventStatus = ""; switch (model.DurationOperationType) { case "05": eventStatus = "01"; break; case "06": eventStatus = "02"; break; } model.BarrierEventStatus = eventStatus; model.Blank1 = GetDataSetValue(dt, i, 14); model.Blank2 = GetDataSetValue(dt, i, 15); DateTime.TryParse(model.ExpirationDate, out DateTime date); var cacheValue = $"{model.ConfirmationNo}_{model.DurationEventNO}_"; if (ReportStatus.CheckCacheInfo(CacheKey, cacheValue)) { continue; } List notes = base.GetReportNotes(ReportType, formatInfoTag(model)); var note = notes.LastOrDefault(O => O.InfoCache.Contains(date.ToString("yyyy-MM-dd"))); if (note == null && _operationType == OptFlagsEnum.A) { note = new SACReportNotes() { IsValid = true, }; } else { if (note == null) { continue; } switch (_operationType) { case OptFlagsEnum.A: continue;//新增数据已报送,跳过 case OptFlagsEnum.U: note.IsValid = true; break; case OptFlagsEnum.D: note.IsValid = false; break; case OptFlagsEnum.NONE: default: throw new ServiceException("未知操作类型"); } } if (model.OperationType != OptFlagsEnum.A) { model.BizID = note.BizId;//确认书编号; } path = Path.Combine(sourcePath, model.OptionDurationManagementAtt); if (!string.IsNullOrWhiteSpace(model.OptionDurationManagementAtt)) { if (!ReportStatus.CheckFileLength(path)) { break; } fileList.Add(path); } model.ExceID = base.formatExceID(); result.Add(model); ReportStatus.AddCacheInfo(CacheKey, cacheValue); note.InfoCache = $"{{\"Tag\":\"{model.ConfirmationNo}\",\"ValueDate\":\"{date.ToString("yyyy-MM-dd")}\",\"DurationEventNO\":\"{model.DurationEventNO}\"}}"; note.id = 0; note.ExceId = model.ExceID; note.CreateTime = DateTime.Now; note.FileTag = FileTag; note.ReportType = ReportType; note.ReportDate = _reqInfo.ReportDate; note.InfoTag = formatInfoTag(model, true); note.OptTime = note.CreateTime; note.RetCode = ""; note.RetMsg = ""; note.ReportResponse = false; note.BizId = ""; note.DataId = ""; note.changeStatus = false; noteList.Add(note); } } return result; } protected override List CheckBodyValue(BodyModel model, out bool checkStatus) { var result = new List(); if (model?.OptionTermination != null) { var helper = new Common.CheckHelper(); for (var i = 0; i < model.OptionTermination.Count; i++) { var listRoot = new List(); var item = model.OptionTermination[i]; helper.ExecuteCheck(item, (name, value, msg) => { listRoot.Add(new SacInfo(name, value, msg)); }); if (listRoot.Count > 0) { var errMsg = new SacInfo("OptionTermination", i) { FieldValue = item.ConfirmationNo, SubMaps = new List(listRoot) }; result.Add(errMsg); } } } checkStatus = result.Count > 0; return result; } public override bool BeforeOfGenerated(out string errMsg) { errMsg = ""; foreach (var file in xmlAttachmentList) { try { File.Delete(file); } catch (Exception e) { LogFactory.GetLogger().Error(e); }; } for (var i = 0; i < noteList.Count; i++) { base.SaveReportNotes(noteList[i]); } return true; } } }