| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514 |
- /******************************************************************************
- * 文件名称: 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
- {
- /// <summary>
- /// 医保目录下载优化服务
- /// </summary>
- public class DirectoryDownloadOptimizedService
- {
- private readonly CenterBusiness _cBus = new CenterBusiness();
- private readonly ComputerInfo _comp = new ComputerInfo();
- private static readonly Dictionary<DirectoryTypeEnum, TradeEnum> TradeMap = new Dictionary<DirectoryTypeEnum, TradeEnum>
- {
- { 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 公共接口
- /// <summary>
- /// 单次下载并导入
- /// </summary>
- /// <param name="version">起始版本号</param>
- /// <param name="category">目录类型</param>
- /// <param name="ownerForm">父窗体</param>
- /// <param name="errorMessage">错误信息</param>
- /// <returns>0 成功,-1 失败</returns>
- 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;
- }
- /// <summary>
- /// 循环下载并导入,直到版本号不再变化或达到最大迭代次数
- /// </summary>
- /// <param name="version">起始版本号</param>
- /// <param name="category">目录类型</param>
- /// <param name="ownerForm">父窗体</param>
- /// <param name="errorMessage">错误信息</param>
- /// <returns>0 成功,-1 失败</returns>
- 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 内部下载与导入逻辑
- /// <summary>
- /// 执行一次下载并导入
- /// </summary>
- 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);
- }
- /// <summary>
- /// 查询目录文件名(用于单次下载前判断本地是否已存在)
- /// </summary>
- /// <returns>文件名(含 .zip 后缀);失败返回 null</returns>
- 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;
- }
- /// <summary>
- /// 从 txt 文件流式读取并导入 IRIS
- /// </summary>
- 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 配置与工具
- /// <summary>
- /// 从当前 DLL 对应的 .config 文件中读取配置值
- /// </summary>
- 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];
- }
- /// <summary>
- /// 从 app.config 读取批量大小,默认 100
- /// </summary>
- 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;
- }
- /// <summary>
- /// 从 app.config 读取下载超时时间(毫秒),默认 30 分钟
- /// </summary>
- 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;
- }
- /// <summary>
- /// 从 app.config 读取循环下载最大迭代次数,默认 20
- /// </summary>
- 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;
- }
- /// <summary>
- /// 提交数据到 IRIS
- /// </summary>
- 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);
- }
- }
- /// <summary>
- /// 带进度显示的目录下载并解压(不修改 HisMainBusiness.DownloadDirectory)
- /// </summary>
- 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);
- }
- }
- /// <summary>
- /// 带进度显示的中心文件下载(9102)
- /// </summary>
- 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();
- }
- }
- /// <summary>
- /// 获取各目录类型所需的最小列数(根据 BuildDirectoryJson 中最大字段索引 +1)
- /// </summary>
- 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
- }
- /// <summary>
- /// 下载上下文
- /// </summary>
- internal class OptimizedDownloadContext
- {
- public string Version { get; set; }
- public DirectoryTypeEnum Category { get; set; }
- public int BatchSize { get; set; } = 100;
- }
- /// <summary>
- /// 下载结果
- /// </summary>
- internal class DownloadResult
- {
- public int Result { get; set; }
- public string ErrorMessage { get; set; }
- }
- /// <summary>
- /// 优化的进度对话框(基于 BackgroundWorker,线程安全)
- /// </summary>
- 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<BackgroundWorker, OptimizedDownloadProgressDialog> 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);
- }
- }
- /// <summary>
- /// 设置进度条最大值
- /// </summary>
- 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;
- });
- }
- /// <summary>
- /// 设置标题和进度条样式
- /// </summary>
- 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;
- }
- });
- }
- /// <summary>
- /// 报告进度(带节流)
- /// </summary>
- 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);
- }
- /// <summary>
- /// 报告状态文本
- /// </summary>
- 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();
- }
- }
- }
- }
|