/****************************************************************************** * 文件名称: DirectoryDownloadOptimizedService.cs * 文件说明: 医保目录下载优化服务(不改动原下载/导入代码) * 当前版本: V1.0 * 创建日期: 2026-08-13 * * 说明: * 为解决 BasicData 页面大数据量目录下载卡死问题,新增本服务类。 * 本类独立实现后台下载、流式读取、批量导入、进度刷新节流、循环下载退出控制, * 不修改 DirectoryDownloadService、DataImoport、ProgressWrapper 等原有文件。 * 仅在 DataDownload.cs 的调用入口将旧调用替换为本类调用。 ******************************************************************************/ using Newtonsoft.Json.Linq; using PTMedicalInsurance.Business; using PTMedicalInsurance.Common; using PTMedicalInsurance.Helper; using PTMedicalInsurance.Variables; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Drawing; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Windows.Forms; namespace PTMedicalInsurance.Forms.BasicDatas.services { /// /// 医保目录下载优化服务 /// public class DirectoryDownloadOptimizedService { private readonly CenterBusiness _cBus = new CenterBusiness(); private readonly ComputerInfo _comp = new ComputerInfo(); private static readonly Dictionary TradeMap = new Dictionary { { DirectoryTypeEnum.Drug, TradeEnum.CMDirectory }, { DirectoryTypeEnum.MedicalService, TradeEnum.MedicalServiceDirectory }, { DirectoryTypeEnum.Consumables, TradeEnum.MaterialDirectory }, { DirectoryTypeEnum.DiseaseDiagnosis, TradeEnum.DiseaseDiagDirectory }, { DirectoryTypeEnum.Surgery, TradeEnum.OperationDirectory }, { DirectoryTypeEnum.OutpatientChronicDiseases, TradeEnum.OPSDiseaseDirectory }, { DirectoryTypeEnum.Drgs, TradeEnum.DRGDiseaseDirectory }, { DirectoryTypeEnum.DaySurgery, TradeEnum.DayOperationDiseaseDirectory }, { DirectoryTypeEnum.Dictionary, TradeEnum.DictionaryDownload }, { DirectoryTypeEnum.ChineseHerbalPieces, TradeEnum.CMPiecesDirectory }, { DirectoryTypeEnum.HospMadeMedicines, TradeEnum.MedOrgSelfDrug }, { DirectoryTypeEnum.TumorMorphology, TradeEnum.TumorDirectory }, { DirectoryTypeEnum.TcmDisease, TradeEnum.CMDiseaseDirectory }, { DirectoryTypeEnum.TcmSyndrome, TradeEnum.CMSyndromeDirectory } }; private const int DefaultBatchSize = 500; private const string BatchSizeConfigKey = "DirectoryDownloadBatchSize"; private const int DefaultTimeout = 1800000; // 30 分钟 private const string TimeoutConfigKey = "DirectoryDownloadTimeout"; private const int DefaultMaxLoopIterations = 20; private const string MaxLoopIterationsConfigKey = "DirectoryDownloadMaxLoopIterations"; private const string ApplyDataCode = "09010035"; #region 公共接口 /// /// 单次下载并导入 /// /// 起始版本号 /// 目录类型 /// 父窗体 /// 错误信息 /// 0 成功,-1 失败 public int SingleDownload(string version, DirectoryTypeEnum category, Form ownerForm, out string errorMessage) { errorMessage = string.Empty; var context = new OptimizedDownloadContext { Version = version, Category = category, BatchSize = GetBatchSize() }; Global.writeLog($"[DirectoryDownloadOptimizedService] SingleDownload 配置:BatchSize={context.BatchSize}, Timeout={GetTimeout()}, MaxLoopIterations={GetMaxLoopIterations()}"); var result = new DownloadResult(); // 单次下载:先查询文件名,若本地 txt 已存在则询问是否重新下载 string filename = QueryDirectoryFilename(category, version, out errorMessage); if (filename == null) { return -1; } string txtFileDir = System.Environment.CurrentDirectory + "\\Download"; string txtFilePath = txtFileDir + "\\" + filename.Substring(0, filename.Length - 4); bool needDownload = true; if (File.Exists(txtFilePath)) { DialogResult dr = DialogResult.Yes; if (ownerForm != null && !ownerForm.IsDisposed) { ownerForm.Invoke(new Action(() => { dr = MessageBox.Show("该目录文件已存在,是否重新下载并导入?\r\n选择【否】将直接导入本地已有文件。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); })); } needDownload = (dr == DialogResult.Yes); } if (!needDownload) { // 直接用本地已有文件导入 using (var dialog = new OptimizedDownloadProgressDialog("正在导入目录...")) { dialog.OwnerForm = ownerForm; dialog.DoWorkAction = (worker, dlg) => { string tempError; result.Result = ImportDataFromTxt(context, txtFilePath, worker, dlg, out tempError); result.ErrorMessage = tempError; }; dialog.Run(); } } else { using (var dialog = new OptimizedDownloadProgressDialog("正在下载目录...")) { dialog.OwnerForm = ownerForm; dialog.DoWorkAction = (worker, dlg) => { string tempError; result.Result = DoSingleDownload(context, worker, dlg, out tempError); result.ErrorMessage = tempError; }; dialog.Run(); } } errorMessage = result.ErrorMessage; return result.Result; } /// /// 循环下载并导入,直到版本号不再变化或达到最大迭代次数 /// /// 起始版本号 /// 目录类型 /// 父窗体 /// 错误信息 /// 0 成功,-1 失败 public int LoopDownload(string version, DirectoryTypeEnum category, Form ownerForm, out string errorMessage) { errorMessage = string.Empty; var context = new OptimizedDownloadContext { Version = version, Category = category, BatchSize = GetBatchSize() }; Global.writeLog($"[DirectoryDownloadOptimizedService] LoopDownload 配置:BatchSize={context.BatchSize}, Timeout={GetTimeout()}, MaxLoopIterations={GetMaxLoopIterations()}"); var result = new DownloadResult(); using (var dialog = new OptimizedDownloadProgressDialog("正在循环下载目录...")) { dialog.OwnerForm = ownerForm; dialog.DoWorkAction = (worker, dlg) => { int maxLoopIterations = GetMaxLoopIterations(); bool reachedLatestVersion = false; for (int i = 0; i < maxLoopIterations; i++) { if (worker.CancellationPending) { result.ErrorMessage = "操作取消!"; result.Result = -1; return; } string previousVersion = context.Version; string tempError; result.Result = DoSingleDownload(context, worker, dlg, out tempError); result.ErrorMessage = tempError; if (result.Result != 0) { Global.writeLog("LoopDownload err:" + result.ErrorMessage); return; } // 版本号未变化,说明已到达最新版本 if (context.Version == previousVersion) { reachedLatestVersion = true; break; } } if (!reachedLatestVersion) { string warnMsg = $"循环下载已达到最大次数 {maxLoopIterations},可能还有未下载完的版本。当前版本:{context.Version}。如需继续,请增大 app.config 中的 DirectoryDownloadMaxLoopIterations。"; result.ErrorMessage = warnMsg; Global.writeLog(warnMsg); } }; dialog.Run(); } errorMessage = result.ErrorMessage; return result.Result; } #endregion #region 内部下载与导入逻辑 /// /// 执行一次下载并导入 /// private int DoSingleDownload(OptimizedDownloadContext context, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err) { err = string.Empty; if (context.Category == DirectoryTypeEnum.None) { err = "未选择有效大类!"; return -1; } if (!TradeMap.TryGetValue(context.Category, out var trade)) { err = "未找到对应的目录类型"; return -1; } if (worker.CancellationPending) { err = "操作取消!"; return -1; } // 1. 下载并解压目录文件 Global.writeLog("OptimizedDownload1"); JObject joRtn = DownloadDirectoryWithProgress(trade.GetCode(), context.Version, worker, dialog, out err); if (joRtn == null || JsonHelper.parseIrisRtnValue(joRtn, out err) != 0) { return -1; } Global.writeLog("OptimizedDownload2"); string txtPath = joRtn["filePath"]?.ToString(); if (string.IsNullOrEmpty(txtPath)) { err = "文件路径为空"; return -1; } if (worker.CancellationPending) { err = "操作取消!"; return -1; } // 2. 流式导入 return ImportDataFromTxt(context, txtPath, worker, dialog, out err); } /// /// 查询目录文件名(用于单次下载前判断本地是否已存在) /// /// 文件名(含 .zip 后缀);失败返回 null private string QueryDirectoryFilename(DirectoryTypeEnum category, string version, out string err) { err = string.Empty; if (category == DirectoryTypeEnum.None) { err = "未选择有效大类!"; return null; } if (!TradeMap.TryGetValue(category, out var trade)) { err = "未找到对应的目录类型"; return null; } JObject joCenterRtn = _cBus.DownDirecotry(trade.GetCode(), version); if (JsonHelper.parseCenterRtnValue(joCenterRtn, out err) != 0) { return null; } string filename = JsonHelper.getDestValue(joCenterRtn, "output.filename"); if (string.IsNullOrEmpty(filename)) { err = "中心返回的文件名为空"; return null; } return filename; } /// /// 从 txt 文件流式读取并导入 IRIS /// private int ImportDataFromTxt(OptimizedDownloadContext context, string txtPath, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err) { err = string.Empty; int errorCount = 0; string errorMsg = string.Empty; int currentRow = 0; try { // 2.1 先统计行数 int rows = 0; using (var counter = new StreamReader(txtPath, Encoding.UTF8)) { while (counter.ReadLine() != null) { rows++; } } if (rows == 0) { err = "txt 文件为空"; return -1; } // 2.2 设置进度条最大值 dialog.SetMaximum(rows); dialog.SetHeaderText(ProgressBarStyle.Continuous, $"本次下载总条数【{rows}】,起始版本名称【{context.Version}】", 50); int direcType = (int)context.Category; int requiredLength = GetRequiredColumnCount(direcType); int progressInterval = Math.Max(1, rows / 100); // 约 1% currentRow = 0; int processedCount = 0; int skipCount = 0; dynamic jaParams = new JArray(); string currentVersionName = context.Version; DateTime lastStatusUpdateTime = DateTime.MinValue; // 2.3 逐行处理(支持字段内换行:前列不足时与下一行合并) using (var reader = new StreamReader(txtPath, Encoding.UTF8)) { string pendingLine = null; string lineTmp; while ((lineTmp = reader.ReadLine()) != null) { currentRow++; if (worker.CancellationPending) { err = "操作取消!"; return -1; } // 跳过空行 if (string.IsNullOrWhiteSpace(lineTmp)) { continue; } // 尝试与之前挂起的行合并(字段内换行) if (pendingLine != null) { lineTmp = pendingLine + "\r\n" + lineTmp; pendingLine = null; } string[] arr = lineTmp.Split('\t'); if (arr.Length < requiredLength) { // 列数不足,可能是字段内换行,挂起等下一行 pendingLine = lineTmp; continue; } JObject joParam = BuildDirectoryJson(arr, direcType, currentRow); if (joParam == null) { skipCount++; continue; } processedCount++; // 只在进度节点取版本号,避免每行字符串解析 if (currentRow % progressInterval == 0 || currentRow == rows) { currentVersionName = JsonHelper.getDestValue(joParam, "VersionName"); } // 每 1 秒更新一次标题和进度条,让用户知道还在运行 if ((DateTime.Now - lastStatusUpdateTime).TotalMilliseconds > 1000) { dialog.SetHeaderText(ProgressBarStyle.Continuous, $"本次下载总条数【{rows}】,正在导入第 {currentRow} 行,起始版本名称【{context.Version}】,当前版本名称【{currentVersionName}】", 50); dialog.ReportProgress(currentRow); lastStatusUpdateTime = DateTime.Now; } jaParams.Add(joParam); // 每 batchSize 条提交一次(按实际有效记录数) if (processedCount % context.BatchSize == 0 || currentRow == rows) { if (jaParams.Count > 0) { JObject joRtn = ApplyDataToIris(ApplyDataCode, jaParams); if (joRtn["errorCode"]?.ToString() != "0") { errorCount++; errorMsg += "\r\n" + joRtn["errorMessage"]; } jaParams = new JArray(); } // 在批次提交节点更新进度和标题 if (currentRow % progressInterval == 0 || currentRow == rows) { dialog.ReportProgress(currentRow); dialog.SetHeaderText(ProgressBarStyle.Continuous, $"本次下载总条数【{rows}】,起始版本名称【{context.Version}】,当前版本名称【{currentVersionName}】", 50); } } } // 文件末尾可能还有未合并完的行 if (pendingLine != null) { string[] arr = pendingLine.Split('\t'); JObject joParam = BuildDirectoryJson(arr, direcType, currentRow); if (joParam != null) { processedCount++; jaParams.Add(joParam); } } } // 提交剩余未提交的数据 if (jaParams.Count > 0) { JObject joRtn = ApplyDataToIris(ApplyDataCode, jaParams); if (joRtn["errorCode"]?.ToString() != "0") { errorCount++; errorMsg += "\r\n" + joRtn["errorMessage"]; } jaParams = new JArray(); dialog.ReportProgress(rows); } // 更新上下文版本号,供循环下载判断终止 context.Version = currentVersionName; if (processedCount == 0) { err = $"未导入任何有效数据:txt 共 {rows} 行,跳过 {skipCount} 行(列数不足或格式错误)。请检查下载文件是否完整。"; return -1; } if (errorCount > 0) { err = $"导入完成,成功 {processedCount} 条,IRIS 报错 {errorCount} 次,跳过 {skipCount} 行。详情:{errorMsg}"; return 0 - errorCount; } if (skipCount > 0) { err = $"导入完成,成功 {processedCount} 条,跳过 {skipCount} 行(列数不足)。请查看日志确认是否有数据丢失。"; // 跳过不严重的行,仍然返回 0,但给出提示 } return 0; } catch (Exception ex) { err = $"ImportDataFromTxt 异常:{ex.Message}(目录类型 {context.Category},当前处理到第 {currentRow} 行,批次大小 {context.BatchSize})"; Global.writeLog(err + "\r\n" + ex.StackTrace); return -1; } } #endregion #region 配置与工具 /// /// 从当前 DLL 对应的 .config 文件中读取配置值 /// private string GetAppSetting(string key) { try { string assemblyPath = Assembly.GetExecutingAssembly().Location; Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyPath); if (config.AppSettings.Settings[key] != null) { return config.AppSettings.Settings[key].Value; } } catch { // 忽略异常,回退到默认的 AppSettings } return ConfigurationManager.AppSettings[key]; } /// /// 从 app.config 读取批量大小,默认 100 /// private int GetBatchSize() { int size = DefaultBatchSize; try { string cfg = GetAppSetting(BatchSizeConfigKey); if (!string.IsNullOrEmpty(cfg) && int.TryParse(cfg, out int parsed) && parsed > 0) { size = parsed; } } catch { // 忽略配置读取异常,使用默认值 } return size; } /// /// 从 app.config 读取下载超时时间(毫秒),默认 30 分钟 /// private int GetTimeout() { int timeout = DefaultTimeout; try { string cfg = GetAppSetting(TimeoutConfigKey); if (!string.IsNullOrEmpty(cfg) && int.TryParse(cfg, out int parsed) && parsed > 0) { timeout = parsed; } } catch { // 忽略配置读取异常,使用默认值 } return timeout; } /// /// 从 app.config 读取循环下载最大迭代次数,默认 20 /// private int GetMaxLoopIterations() { int iterations = DefaultMaxLoopIterations; try { string cfg = GetAppSetting(MaxLoopIterationsConfigKey); if (!string.IsNullOrEmpty(cfg) && int.TryParse(cfg, out int parsed) && parsed > 0) { iterations = parsed; } } catch { // 忽略配置读取异常,使用默认值 } return iterations; } /// /// 提交数据到 IRIS /// private JObject ApplyDataToIris(string code, JArray jaParam) { try { JObject joIn = new JObject(); joIn.Add(new JProperty("params", jaParam)); joIn.Add("code", code); joIn.Add("updateUserID", Global.user.ID); InvokeHelper invoker = new InvokeHelper(); return invoker.invokeInsuService(joIn.ToString(), "applyDataToIris"); } catch (Exception ex) { return JsonHelper.setExceptionJson(-1, "applyDataToIris", ex.Message); } } /// /// 带进度显示的目录下载并解压(不修改 HisMainBusiness.DownloadDirectory) /// private JObject DownloadDirectoryWithProgress(string funNO, string version, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err) { err = string.Empty; try { // 1. 查询目录文件号 dialog.SetHeaderText(ProgressBarStyle.Marquee, $"正在获取文件信息,版本【{version}】...", 50); JObject joCenterRtn = _cBus.DownDirecotry(funNO, version); if (JsonHelper.parseCenterRtnValue(joCenterRtn, out err) != 0) { return JsonHelper.setExceptionJson(-100, "下载异常", err); } string filename = JsonHelper.getDestValue(joCenterRtn, "output.filename"); string fileQuryNo = JsonHelper.getDestValue(joCenterRtn, "output.file_qury_no"); if (string.IsNullOrEmpty(filename) || string.IsNullOrEmpty(fileQuryNo)) { err = "中心返回的文件信息不完整"; return JsonHelper.setExceptionJson(-100, "下载异常", err); } if (worker.CancellationPending) { err = "操作取消!"; return JsonHelper.setExceptionJson(-100, "下载取消", err); } // 2. 下载文件(带进度) JObject jo9102Rtn = DownloadCenterFileWithProgress(filename, fileQuryNo, worker, dialog, out err); if (jo9102Rtn == null || jo9102Rtn["errorCode"]?.ToString() != "0") { return JsonHelper.setExceptionJson(-100, "保存文件异常", err); } string zipFilePath = jo9102Rtn["filePath"]?.ToString(); if (string.IsNullOrEmpty(zipFilePath) || !File.Exists(zipFilePath)) { err = "下载后的zip文件不存在"; return JsonHelper.setExceptionJson(-100, "保存文件异常", err); } // 3. 解压 string txtFileDir = System.Environment.CurrentDirectory + "\\Download"; string txtFilePath = txtFileDir + "\\" + filename.Substring(0, filename.Length - 4); if (!Directory.Exists(txtFileDir)) { Directory.CreateDirectory(txtFileDir); } if (File.Exists(txtFilePath)) { // 在后台线程中不能弹窗,先返回特殊错误码让上层处理 // 但为了保持与原 HisMainBusiness.DownloadDirectory 相同的覆盖逻辑, // 这里默认直接覆盖(医保目录更新时通常需要最新版) File.Delete(txtFilePath); } if (tools.ExtractFile(zipFilePath, txtFileDir, out err) != 0) { return JsonHelper.setExceptionJson(-100, "提取文件", err); } JObject joRtn = (JObject)jo9102Rtn.DeepClone(); joRtn["filePath"] = txtFilePath; return joRtn; } catch (Exception ex) { err = $"DownloadDirectoryWithProgress 异常:{ex.Message}"; Global.writeLog(err); return JsonHelper.setExceptionJson(-100, "下载中心目录", err); } } /// /// 带进度显示的中心文件下载(9102) /// private JObject DownloadCenterFileWithProgress(string filename, string fileQuryNo, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err) { err = string.Empty; string filePath = Global.curEvt.path + "\\Download\\" + filename; try { if (!Directory.Exists(Global.curEvt.path + "\\Download")) { Directory.CreateDirectory(Global.curEvt.path + "\\Download"); } if (File.Exists(filePath)) { File.Delete(filePath); } // 构造 9102 入参 dynamic jo9102InParam = new JObject(); dynamic jofsDownloadIn = new JObject(); jofsDownloadIn.filename = filename; jofsDownloadIn.file_qury_no = fileQuryNo; jofsDownloadIn.fixmedins_code = Global.inf.hospitalNO; jo9102InParam.fsDownloadIn = jofsDownloadIn; string requestData = JsonHelper.setCenterInpar("9102", jo9102InParam.ToString()); Global.curEvt.URL = _comp.getFunNoInsuURL("9102"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL); request.Method = "POST"; request.ContentType = "application/json"; request.Headers.Add("apikey", "fa8kQMIF6LB0D7c6UGQoZc6TCcZO2G6O"); request.Accept = "text/html, application/xhtml+xml, */*"; int timeout = GetTimeout(); request.Timeout = timeout; request.ReadWriteTimeout = timeout; byte[] payload = Encoding.UTF8.GetBytes(requestData); request.ContentLength = payload.Length; using (Stream writer = request.GetRequestStream()) { writer.Write(payload, 0, payload.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) using (Stream responseStream = response.GetResponseStream()) using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { long totalLength = response.ContentLength; byte[] buffer = new byte[8192]; int bytesRead; long downloaded = 0; DateTime lastReportTime = DateTime.MinValue; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { if (worker.CancellationPending) { err = "操作取消!"; fs.Close(); SafeDelete(filePath); return JsonHelper.setExceptionJson(-100, "下载取消", err); } fs.Write(buffer, 0, bytesRead); downloaded += bytesRead; // 每 300ms 或每 1MB 刷新一次标题,避免消息队列阻塞 if ((DateTime.Now - lastReportTime).TotalMilliseconds > 300) { string progressText = FormatFileSize(downloaded); if (totalLength > 0) { int percent = (int)((downloaded * 100) / totalLength); progressText = $"已下载 {progressText} / {FormatFileSize(totalLength)} ({percent}%)"; dialog.SetHeaderText(ProgressBarStyle.Marquee, $"正在下载文件【{filename}】,{progressText}", 50); } else { dialog.SetHeaderText(ProgressBarStyle.Marquee, $"正在下载文件【{filename}】,{progressText}", 50); } lastReportTime = DateTime.Now; } } } dynamic joReturn = new JObject(); joReturn.errorCode = 0; joReturn.errorMessage = ""; joReturn.filePath = filePath; return joReturn; } catch (Exception ex) { err = ex.Message; SafeDelete(filePath); Global.writeLog("DownloadCenterFileWithProgress 异常:" + ex.Message); dynamic joReturn = new JObject(); joReturn.errorCode = -100; joReturn.errorMessage = err; joReturn.filePath = filePath; return joReturn; } } private void SafeDelete(string path) { try { if (File.Exists(path)) { File.Delete(path); } } catch { // 忽略清理异常 } } private string FormatFileSize(long bytes) { if (bytes < 1024) return $"{bytes} B"; if (bytes < 1024 * 1024) return $"{bytes / 1024.0:F2} KB"; if (bytes < 1024 * 1024 * 1024) return $"{bytes / (1024.0 * 1024.0):F2} MB"; return $"{bytes / (1024.0 * 1024.0 * 1024.0):F2} GB"; } private string ConvertArrayNull(string arrayValue) { return arrayValue == "null" ? string.Empty : arrayValue; } #endregion #region 目录 JSON 组装(从 DataImoport.cs 复刻,保持原逻辑不变) private JObject BuildDirectoryJson(string[] arr, int direcType, int rowNumber) { int requiredLength = GetRequiredColumnCount(direcType); if (requiredLength > 0 && arr.Length < requiredLength) { // 列数不足时填充空字符串,而不是跳过(医保目录中末尾空字段常见) int originalLength = arr.Length; Array.Resize(ref arr, requiredLength); for (int i = originalLength; i < requiredLength; i++) { arr[i] = string.Empty; } } switch (direcType) { case 1: return GetDrugsJsonByTxt(arr); case 2: return GetMedicalServiceJsonByTxt(arr); case 3: return GetMaterialJsonByTxt(arr); case 4: return GetDiagnoseJsonByTxt(arr); case 5: return GetOperationJsonByTxt(arr); case 6: return GetChronicDiseaseJsonByTxt(arr); case 7: return GetDRGsJsonByTxt(arr); case 8: return GetDaySurgeryJsonByTxt(arr); case 10: return GetChineseDrugJsonByTxt(arr); case 11: return GetHosPreparationJsonByTxt(arr); default: return new JObject(); } } /// /// 获取各目录类型所需的最小列数(根据 BuildDirectoryJson 中最大字段索引 +1) /// private int GetRequiredColumnCount(int direcType) { switch (direcType) { case 1: return 92; // 药品:最大 arr[91] case 2: return 16; // 诊疗:最大 arr[15] case 3: return 71; // 材料:最大 arr[70] case 4: return 24; // 诊断:最大 arr[23] case 5: return 24; // 手术:最大 arr[23] case 6: return 16; // 慢性病:最大 arr[15] case 7: return 13; // DRGs:最大 arr[12] case 8: return 11; // 日间手术:最大 arr[10] case 10: return 11; // 中药饮片:最大 arr[10] case 11: return 78; // 医疗机构制剂:最大 arr[77] default: return 0; } } private JObject GetDrugsJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[0]; jsonTemp.Name = arr[7]; jsonTemp.HisType = "1"; jsonTemp.HisTypeName = "药品"; jsonTemp.LocateCode = ""; jsonTemp.LocateName = ""; jsonTemp.DosageFormCode = arr[9]; jsonTemp.DosageFormName = arr[10]; jsonTemp.CategoryCode = arr[11]; jsonTemp.CategoryName = arr[12]; jsonTemp.Specification = arr[13]; jsonTemp.SpecificationCode = arr[14]; jsonTemp.UnitOfPackag = arr[42]; jsonTemp.UnitOfValuation = arr[48]; jsonTemp.StartDate = ConvertArrayNull(arr[36]); jsonTemp.EndDate = ConvertArrayNull(arr[37]); jsonTemp.PinyinSearchCode = arr[50]; jsonTemp.Instructions = arr[35]; jsonTemp.ExceptContent = ""; jsonTemp.Connotation = ""; jsonTemp.ValidFlag = ConvertArrayNull(arr[78]); jsonTemp.Note = arr[77]; jsonTemp.VersionNO = arr[82]; jsonTemp.VersionName = arr[83]; jsonTemp.UseFlag = ConvertArrayNull(arr[78]); jsonTemp.DrugSafetyStandardCode = arr[8]; jsonTemp.ApprovalNO = arr[61]; jsonTemp.SpecialFlag = ConvertArrayNull(arr[55]); //特殊药品标志 jsonTemp.LimitFlag = ConvertArrayNull(arr[57]); //限制标志 jsonTemp.LimitRange = arr[56]; jsonTemp.UniqueRecordNO = arr[79]; jsonTemp.Manufacturers = arr[53]; jsonTemp.Company = arr[85]; jsonTemp.ChargeItemLevelName = arr[91]; //jsonTemp.CeilingPrice = arr[91]; // 最高限价 jsonTemp.PackagingMaterial = arr[29]; // 包装材质 jsonTemp.MinPackagingQuantity = arr[41]; // 最小包装数量 jsonTemp.MinDosageUnit = arr[43]; // 最小制剂单位 jsonTemp.MinPackagingUnit = arr[42]; // 最小包装单位 SetChargeItemLevel(jsonTemp); return jsonTemp; } private JObject GetMedicalServiceJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[0]; jsonTemp.Name = arr[9]; jsonTemp.HisType = "2"; jsonTemp.HisTypeName = "诊疗"; jsonTemp.LocateCode = ""; jsonTemp.LocateName = ""; jsonTemp.DosageFormCode = arr[9]; jsonTemp.DosageFormName = arr[10]; jsonTemp.CategoryCode = arr[8]; jsonTemp.CategoryName = arr[12]; jsonTemp.Specification = ""; jsonTemp.SpecificationCode = ""; jsonTemp.UnitOfPackag = arr[1]; jsonTemp.UnitOfValuation = arr[2]; jsonTemp.Instructions = arr[3]; jsonTemp.ExceptContent = arr[4]; jsonTemp.Connotation = arr[5]; jsonTemp.ValidFlag = arr[6]; jsonTemp.Note = ""; jsonTemp.VersionNO = arr[14]; jsonTemp.VersionName = arr[15]; jsonTemp.UseFlag = arr[6]; jsonTemp.DrugSafetyStandardCode = ""; jsonTemp.ApprovalNO = ""; jsonTemp.SpecialFlag = ""; jsonTemp.LimitFlag = ""; jsonTemp.LimitRange = ""; jsonTemp.UniqueRecordNO = arr[13]; jsonTemp.ChargeItemLevel = arr[0]; if (jsonTemp.ChargeItemLevel == "1") { jsonTemp.ChargeItemLevelName = "甲"; jsonTemp.SelfPercent = "0"; } else if (jsonTemp.ChargeItemLevel == "2") { jsonTemp.ChargeItemLevelName = "乙"; jsonTemp.SelfPercent = "0"; } else if (jsonTemp.ChargeItemLevel == "3") { jsonTemp.ChargeItemLevelName = "丙"; jsonTemp.SelfPercent = "100"; } else { jsonTemp.ChargeItemLevel = "4"; jsonTemp.SelfPercent = "100"; jsonTemp.ChargeItemLevelName = "未知"; } return jsonTemp; } private JObject GetMaterialJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[0]; jsonTemp.Name = arr[1]; jsonTemp.HisType = "3"; jsonTemp.HisTypeName = "材料"; jsonTemp.LocateCode = ""; jsonTemp.LocateName = ""; jsonTemp.DosageFormCode = ""; jsonTemp.DosageFormName = ""; jsonTemp.CategoryCode = ""; jsonTemp.CategoryName = ""; jsonTemp.Specification = arr[7]; jsonTemp.SpecificationCode = arr[6]; jsonTemp.UnitOfPackag = arr[15]; jsonTemp.UnitOfValuation = ConvertArrayNull(arr[35]); jsonTemp.StartDate = ConvertArrayNull(arr[46]); jsonTemp.EndDate = ConvertArrayNull(arr[47]); jsonTemp.Instructions = arr[27]; jsonTemp.ExceptContent = arr[63]; jsonTemp.Connotation = ""; jsonTemp.ValidFlag = arr[67]; jsonTemp.Note = arr[7]; jsonTemp.VersionNO = arr[69]; jsonTemp.VersionName = arr[70]; jsonTemp.UseFlag = arr[67]; jsonTemp.DrugSafetyStandardCode = ""; jsonTemp.ApprovalNO = arr[50]; jsonTemp.SpecialFlag = ""; jsonTemp.LimitFlag = ConvertArrayNull(arr[33]); jsonTemp.LimitRange = arr[34]; jsonTemp.UniqueRecordNO = arr[68]; jsonTemp.Manufacturers = arr[59]; jsonTemp.ChargeItemLevelName = arr[37]; SetChargeItemLevel(jsonTemp); return jsonTemp; } private JObject GetDiagnoseJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[10]; jsonTemp.Name = arr[11]; jsonTemp.HisType = "4"; jsonTemp.HisTypeName = "诊断"; jsonTemp.LocateCode = ""; jsonTemp.LocateName = ""; jsonTemp.DosageFormCode = ""; jsonTemp.DosageFormName = ""; jsonTemp.CategoryCode = ""; jsonTemp.CategoryName = ""; jsonTemp.Specification = ""; jsonTemp.SpecificationCode = ""; jsonTemp.UnitOfPackag = ""; jsonTemp.UnitOfValuation = ""; jsonTemp.StartDate = ""; jsonTemp.EndDate = ""; jsonTemp.Instructions = ""; jsonTemp.ExceptContent = ""; jsonTemp.Connotation = ""; jsonTemp.ValidFlag = arr[18]; jsonTemp.Note = arr[17]; jsonTemp.VersionNO = arr[22]; jsonTemp.VersionName = arr[23]; jsonTemp.UseFlag = arr[18]; jsonTemp.DrugSafetyStandardCode = ""; jsonTemp.ApprovalNO = ""; jsonTemp.SpecialFlag = ""; jsonTemp.LimitFlag = ""; jsonTemp.LimitRange = ""; jsonTemp.UniqueRecordNO = arr[19]; jsonTemp.Manufacturers = ""; return jsonTemp; } private JObject GetChronicDiseaseJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[0]; jsonTemp.Name = arr[1]; jsonTemp.HisType = "6"; jsonTemp.HisTypeName = "慢性病"; jsonTemp.LocateCode = ""; jsonTemp.LocateName = ""; jsonTemp.DosageFormCode = ""; jsonTemp.DosageFormName = ""; jsonTemp.CategoryCode = arr[14]; jsonTemp.CategoryName = arr[15]; jsonTemp.Specification = ""; jsonTemp.SpecificationCode = ""; jsonTemp.UnitOfPackag = ""; jsonTemp.UnitOfValuation = ""; jsonTemp.StartDate = ""; jsonTemp.EndDate = ""; jsonTemp.Instructions = ""; jsonTemp.ExceptContent = ""; jsonTemp.Connotation = arr[10]; jsonTemp.ValidFlag = arr[5]; jsonTemp.Note = arr[4]; jsonTemp.VersionNO = arr[9]; jsonTemp.VersionName = arr[11]; jsonTemp.UseFlag = arr[5]; jsonTemp.DrugSafetyStandardCode = ""; jsonTemp.ApprovalNO = ""; jsonTemp.SpecialFlag = ""; jsonTemp.LimitFlag = ""; jsonTemp.LimitRange = ""; jsonTemp.UniqueRecordNO = arr[6]; jsonTemp.Manufacturers = ""; return jsonTemp; } private JObject GetOperationJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[10]; jsonTemp.Name = arr[11]; jsonTemp.HisType = "5"; jsonTemp.HisTypeName = "手术"; jsonTemp.ValidFlag = arr[18]; jsonTemp.Note = arr[17]; jsonTemp.VersionNO = arr[22]; jsonTemp.VersionName = arr[23]; jsonTemp.UseFlag = arr[18]; jsonTemp.UniqueRecordNO = arr[19]; return jsonTemp; } private JObject GetDRGsJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[1]; jsonTemp.Name = arr[2]; jsonTemp.HisType = "7"; jsonTemp.HisTypeName = "DRGs"; jsonTemp.Connotation = arr[10]; jsonTemp.Instructions = arr[3]; jsonTemp.ExceptContent = arr[4]; jsonTemp.ValidFlag = arr[5]; jsonTemp.Note = arr[11]; jsonTemp.VersionNO = arr[9]; jsonTemp.VersionName = arr[12]; jsonTemp.UseFlag = arr[5]; jsonTemp.UniqueRecordNO = arr[6]; return jsonTemp; } private JObject GetDaySurgeryJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[1]; jsonTemp.Name = arr[2]; jsonTemp.HisType = "8"; jsonTemp.HisTypeName = "日间手术"; jsonTemp.Connotation = arr[8]; jsonTemp.ValidFlag = arr[3]; jsonTemp.Note = arr[9]; jsonTemp.VersionNO = arr[7]; jsonTemp.VersionName = arr[10]; jsonTemp.UseFlag = arr[3]; jsonTemp.UniqueRecordNO = arr[4]; return jsonTemp; } private JObject GetChineseDrugJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[0]; jsonTemp.Name = arr[1]; jsonTemp.HisType = "10"; jsonTemp.HisTypeName = "中药饮片"; jsonTemp.Connotation = arr[8]; jsonTemp.ValidFlag = arr[3]; jsonTemp.Note = arr[9]; jsonTemp.VersionNO = arr[7]; jsonTemp.VersionName = arr[10]; jsonTemp.UseFlag = arr[3]; jsonTemp.UniqueRecordNO = arr[4]; return jsonTemp; } private JObject GetHosPreparationJsonByTxt(string[] arr) { dynamic jsonTemp = new JObject(); jsonTemp.ID = ""; jsonTemp.updateUserID = Global.user.ID; jsonTemp.HospitalDr = Global.inf.hospitalDr; jsonTemp.InterfaceDr = Global.inf.interfaceDr; jsonTemp.Code = arr[0]; jsonTemp.Name = arr[1]; jsonTemp.HisType = "11"; jsonTemp.HisTypeName = "医疗机构制剂"; jsonTemp.Connotation = arr[8]; jsonTemp.ValidFlag = arr[64]; jsonTemp.Note = arr[9]; jsonTemp.VersionNO = arr[70]; jsonTemp.VersionName = arr[71]; jsonTemp.UseFlag = arr[64]; jsonTemp.UniqueRecordNO = arr[46]; jsonTemp.Instructions = arr[77]; jsonTemp.NationalCode = arr[57]; jsonTemp.NationalName = arr[58]; return jsonTemp; } private void SetChargeItemLevel(dynamic jsonTemp) { string levelName = jsonTemp.ChargeItemLevelName; if (levelName == "甲") { jsonTemp.ChargeItemLevel = "01"; jsonTemp.SelfPercent = "0"; } else if (levelName == "乙") { jsonTemp.ChargeItemLevel = "02"; jsonTemp.SelfPercent = "0"; } else if (levelName == "丙") { jsonTemp.ChargeItemLevel = "03"; jsonTemp.SelfPercent = "100"; } else { jsonTemp.ChargeItemLevel = "04"; jsonTemp.SelfPercent = "100"; jsonTemp.ChargeItemLevelName = "未知"; } } #endregion } /// /// 下载上下文 /// internal class OptimizedDownloadContext { public string Version { get; set; } public DirectoryTypeEnum Category { get; set; } public int BatchSize { get; set; } = 100; } /// /// 下载结果 /// internal class DownloadResult { public int Result { get; set; } public string ErrorMessage { get; set; } } /// /// 优化的进度对话框(基于 BackgroundWorker,线程安全) /// internal class OptimizedDownloadProgressDialog : Form { private ProgressBar _progressBar; private Label _labelStatus; private Button _cancelButton; private BackgroundWorker _backgroundWorker; private int _maximum = 100; private string _header = "正在处理..."; private int _lastProgressValue = -1; private DateTime _lastProgressTime = DateTime.MinValue; public Form OwnerForm { get; set; } public Action DoWorkAction { get; set; } public OptimizedDownloadProgressDialog(string headerText) { _header = headerText; InitializeComponent(); } private void InitializeComponent() { Text = _header; StartPosition = FormStartPosition.CenterParent; FormBorderStyle = FormBorderStyle.FixedDialog; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false; TopMost = true; ClientSize = new Size(800, 100); _progressBar = new ProgressBar { Location = new Point(12, 12), Size = new Size(700, 23), Style = ProgressBarStyle.Continuous, Maximum = 100, Value = 0 }; Controls.Add(_progressBar); _labelStatus = new Label { Location = new Point(12, 41), Size = new Size(700, 23) }; Controls.Add(_labelStatus); _cancelButton = new Button { Text = "取消", Location = new Point(520, 60), Size = new Size(75, 23) }; _cancelButton.Click += CancelButton_Click; Controls.Add(_cancelButton); _backgroundWorker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true }; _backgroundWorker.DoWork += BackgroundWorker_DoWork; _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged; _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted; } public void Run() { if (_backgroundWorker.IsBusy) return; // 先启动后台任务,再模态显示对话框 _backgroundWorker.RunWorkerAsync(); // ShowDialog 会让 UI 线程进入对话框消息循环 // BackgroundWorker 事件正常处理,RunWorkerCompleted 中关闭对话框 if (OwnerForm != null && !OwnerForm.IsDisposed) { ShowDialog(OwnerForm); } else { ShowDialog(); } } private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e) { try { DoWorkAction?.Invoke(_backgroundWorker, this); } catch (Exception ex) { Global.writeLog("OptimizedDownloadBackgroundWorker_DoWork 异常:" + ex.Message); throw; } } private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) { if (IsDisposed) return; if (e.ProgressPercentage >= 0 && e.ProgressPercentage <= _maximum) { _progressBar.Value = e.ProgressPercentage; _labelStatus.Text = $"已完成 {e.ProgressPercentage}/{_maximum}"; } if (e.UserState is string status) { Text = status; } } private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { try { if (!IsDisposed) { DialogResult = e.Cancelled || e.Error != null ? DialogResult.Cancel : DialogResult.OK; Close(); } } catch (Exception ex) { Global.writeLog("OptimizedDownloadRunWorkerCompleted 异常:" + ex.Message); } } private void CancelButton_Click(object sender, EventArgs e) { if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation && _backgroundWorker.IsBusy) { _backgroundWorker.CancelAsync(); _cancelButton.Enabled = false; _labelStatus.Text = "正在取消..."; } } protected override void OnFormClosing(FormClosingEventArgs e) { if (_backgroundWorker != null && _backgroundWorker.IsBusy) { _backgroundWorker.CancelAsync(); e.Cancel = true; _cancelButton.Enabled = false; _labelStatus.Text = "正在取消..."; } else { base.OnFormClosing(e); } } /// /// 设置进度条最大值 /// public void SetMaximum(int max) { _maximum = max; _lastProgressValue = -1; _lastProgressTime = DateTime.MinValue; BeginInvokeIfRequired(() => { if (IsDisposed) return; _progressBar.Style = ProgressBarStyle.Continuous; _progressBar.Maximum = max; _progressBar.Value = 0; }); } /// /// 设置标题和进度条样式 /// public void SetHeaderText(ProgressBarStyle style, string header, int speed) { BeginInvokeIfRequired(() => { if (IsDisposed) return; _header = header; Text = header; _progressBar.Style = style; if (style == ProgressBarStyle.Marquee) { _progressBar.MarqueeAnimationSpeed = speed; } }); } /// /// 报告进度(带节流) /// public void ReportProgress(int value) { if (_backgroundWorker == null || !_backgroundWorker.WorkerReportsProgress) return; int minStep = Math.Max(1, _maximum / 200); // 约 0.5% 更新一次 const int minIntervalMs = 50; if (value != 0 && value != _maximum && value - _lastProgressValue < minStep && (DateTime.Now - _lastProgressTime).TotalMilliseconds < minIntervalMs) { return; } _lastProgressValue = value; _lastProgressTime = DateTime.Now; _backgroundWorker.ReportProgress(value); } /// /// 报告状态文本 /// public void ReportStatus(string status) { _backgroundWorker?.ReportProgress(-1, status); } private void BeginInvokeIfRequired(MethodInvoker action) { if (InvokeRequired) { try { BeginInvoke(action); } catch (Exception ex) when (ex is InvalidOperationException || ex is InvalidAsynchronousStateException) { Global.writeLog("OptimizedDownload BeginInvokeIfRequired 异常:" + ex.Message); } } else { action(); } } } }