DirectoryDownloadOptimizedService.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514
  1. /******************************************************************************
  2. * 文件名称: DirectoryDownloadOptimizedService.cs
  3. * 文件说明: 医保目录下载优化服务(不改动原下载/导入代码)
  4. * 当前版本: V1.0
  5. * 创建日期: 2026-08-13
  6. *
  7. * 说明:
  8. * 为解决 BasicData 页面大数据量目录下载卡死问题,新增本服务类。
  9. * 本类独立实现后台下载、流式读取、批量导入、进度刷新节流、循环下载退出控制,
  10. * 不修改 DirectoryDownloadService、DataImoport、ProgressWrapper 等原有文件。
  11. * 仅在 DataDownload.cs 的调用入口将旧调用替换为本类调用。
  12. ******************************************************************************/
  13. using Newtonsoft.Json.Linq;
  14. using PTMedicalInsurance.Business;
  15. using PTMedicalInsurance.Common;
  16. using PTMedicalInsurance.Helper;
  17. using PTMedicalInsurance.Variables;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.ComponentModel;
  21. using System.Configuration;
  22. using System.Drawing;
  23. using System.IO;
  24. using System.Net;
  25. using System.Reflection;
  26. using System.Text;
  27. using System.Threading;
  28. using System.Windows.Forms;
  29. namespace PTMedicalInsurance.Forms.BasicDatas.services
  30. {
  31. /// <summary>
  32. /// 医保目录下载优化服务
  33. /// </summary>
  34. public class DirectoryDownloadOptimizedService
  35. {
  36. private readonly CenterBusiness _cBus = new CenterBusiness();
  37. private readonly ComputerInfo _comp = new ComputerInfo();
  38. private static readonly Dictionary<DirectoryTypeEnum, TradeEnum> TradeMap = new Dictionary<DirectoryTypeEnum, TradeEnum>
  39. {
  40. { DirectoryTypeEnum.Drug, TradeEnum.CMDirectory },
  41. { DirectoryTypeEnum.MedicalService, TradeEnum.MedicalServiceDirectory },
  42. { DirectoryTypeEnum.Consumables, TradeEnum.MaterialDirectory },
  43. { DirectoryTypeEnum.DiseaseDiagnosis, TradeEnum.DiseaseDiagDirectory },
  44. { DirectoryTypeEnum.Surgery, TradeEnum.OperationDirectory },
  45. { DirectoryTypeEnum.OutpatientChronicDiseases, TradeEnum.OPSDiseaseDirectory },
  46. { DirectoryTypeEnum.Drgs, TradeEnum.DRGDiseaseDirectory },
  47. { DirectoryTypeEnum.DaySurgery, TradeEnum.DayOperationDiseaseDirectory },
  48. { DirectoryTypeEnum.Dictionary, TradeEnum.DictionaryDownload },
  49. { DirectoryTypeEnum.ChineseHerbalPieces, TradeEnum.CMPiecesDirectory },
  50. { DirectoryTypeEnum.HospMadeMedicines, TradeEnum.MedOrgSelfDrug },
  51. { DirectoryTypeEnum.TumorMorphology, TradeEnum.TumorDirectory },
  52. { DirectoryTypeEnum.TcmDisease, TradeEnum.CMDiseaseDirectory },
  53. { DirectoryTypeEnum.TcmSyndrome, TradeEnum.CMSyndromeDirectory }
  54. };
  55. private const int DefaultBatchSize = 500;
  56. private const string BatchSizeConfigKey = "DirectoryDownloadBatchSize";
  57. private const int DefaultTimeout = 1800000; // 30 分钟
  58. private const string TimeoutConfigKey = "DirectoryDownloadTimeout";
  59. private const int DefaultMaxLoopIterations = 20;
  60. private const string MaxLoopIterationsConfigKey = "DirectoryDownloadMaxLoopIterations";
  61. private const string ApplyDataCode = "09010035";
  62. #region 公共接口
  63. /// <summary>
  64. /// 单次下载并导入
  65. /// </summary>
  66. /// <param name="version">起始版本号</param>
  67. /// <param name="category">目录类型</param>
  68. /// <param name="ownerForm">父窗体</param>
  69. /// <param name="errorMessage">错误信息</param>
  70. /// <returns>0 成功,-1 失败</returns>
  71. public int SingleDownload(string version, DirectoryTypeEnum category, Form ownerForm, out string errorMessage)
  72. {
  73. errorMessage = string.Empty;
  74. var context = new OptimizedDownloadContext
  75. {
  76. Version = version,
  77. Category = category,
  78. BatchSize = GetBatchSize()
  79. };
  80. Global.writeLog($"[DirectoryDownloadOptimizedService] SingleDownload 配置:BatchSize={context.BatchSize}, Timeout={GetTimeout()}, MaxLoopIterations={GetMaxLoopIterations()}");
  81. var result = new DownloadResult();
  82. // 单次下载:先查询文件名,若本地 txt 已存在则询问是否重新下载
  83. string filename = QueryDirectoryFilename(category, version, out errorMessage);
  84. if (filename == null)
  85. {
  86. return -1;
  87. }
  88. string txtFileDir = System.Environment.CurrentDirectory + "\\Download";
  89. string txtFilePath = txtFileDir + "\\" + filename.Substring(0, filename.Length - 4);
  90. bool needDownload = true;
  91. if (File.Exists(txtFilePath))
  92. {
  93. DialogResult dr = DialogResult.Yes;
  94. if (ownerForm != null && !ownerForm.IsDisposed)
  95. {
  96. ownerForm.Invoke(new Action(() =>
  97. {
  98. dr = MessageBox.Show("该目录文件已存在,是否重新下载并导入?\r\n选择【否】将直接导入本地已有文件。",
  99. "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  100. }));
  101. }
  102. needDownload = (dr == DialogResult.Yes);
  103. }
  104. if (!needDownload)
  105. {
  106. // 直接用本地已有文件导入
  107. using (var dialog = new OptimizedDownloadProgressDialog("正在导入目录..."))
  108. {
  109. dialog.OwnerForm = ownerForm;
  110. dialog.DoWorkAction = (worker, dlg) =>
  111. {
  112. string tempError;
  113. result.Result = ImportDataFromTxt(context, txtFilePath, worker, dlg, out tempError);
  114. result.ErrorMessage = tempError;
  115. };
  116. dialog.Run();
  117. }
  118. }
  119. else
  120. {
  121. using (var dialog = new OptimizedDownloadProgressDialog("正在下载目录..."))
  122. {
  123. dialog.OwnerForm = ownerForm;
  124. dialog.DoWorkAction = (worker, dlg) =>
  125. {
  126. string tempError;
  127. result.Result = DoSingleDownload(context, worker, dlg, out tempError);
  128. result.ErrorMessage = tempError;
  129. };
  130. dialog.Run();
  131. }
  132. }
  133. errorMessage = result.ErrorMessage;
  134. return result.Result;
  135. }
  136. /// <summary>
  137. /// 循环下载并导入,直到版本号不再变化或达到最大迭代次数
  138. /// </summary>
  139. /// <param name="version">起始版本号</param>
  140. /// <param name="category">目录类型</param>
  141. /// <param name="ownerForm">父窗体</param>
  142. /// <param name="errorMessage">错误信息</param>
  143. /// <returns>0 成功,-1 失败</returns>
  144. public int LoopDownload(string version, DirectoryTypeEnum category, Form ownerForm, out string errorMessage)
  145. {
  146. errorMessage = string.Empty;
  147. var context = new OptimizedDownloadContext
  148. {
  149. Version = version,
  150. Category = category,
  151. BatchSize = GetBatchSize()
  152. };
  153. Global.writeLog($"[DirectoryDownloadOptimizedService] LoopDownload 配置:BatchSize={context.BatchSize}, Timeout={GetTimeout()}, MaxLoopIterations={GetMaxLoopIterations()}");
  154. var result = new DownloadResult();
  155. using (var dialog = new OptimizedDownloadProgressDialog("正在循环下载目录..."))
  156. {
  157. dialog.OwnerForm = ownerForm;
  158. dialog.DoWorkAction = (worker, dlg) =>
  159. {
  160. int maxLoopIterations = GetMaxLoopIterations();
  161. bool reachedLatestVersion = false;
  162. for (int i = 0; i < maxLoopIterations; i++)
  163. {
  164. if (worker.CancellationPending)
  165. {
  166. result.ErrorMessage = "操作取消!";
  167. result.Result = -1;
  168. return;
  169. }
  170. string previousVersion = context.Version;
  171. string tempError;
  172. result.Result = DoSingleDownload(context, worker, dlg, out tempError);
  173. result.ErrorMessage = tempError;
  174. if (result.Result != 0)
  175. {
  176. Global.writeLog("LoopDownload err:" + result.ErrorMessage);
  177. return;
  178. }
  179. // 版本号未变化,说明已到达最新版本
  180. if (context.Version == previousVersion)
  181. {
  182. reachedLatestVersion = true;
  183. break;
  184. }
  185. }
  186. if (!reachedLatestVersion)
  187. {
  188. string warnMsg = $"循环下载已达到最大次数 {maxLoopIterations},可能还有未下载完的版本。当前版本:{context.Version}。如需继续,请增大 app.config 中的 DirectoryDownloadMaxLoopIterations。";
  189. result.ErrorMessage = warnMsg;
  190. Global.writeLog(warnMsg);
  191. }
  192. };
  193. dialog.Run();
  194. }
  195. errorMessage = result.ErrorMessage;
  196. return result.Result;
  197. }
  198. #endregion
  199. #region 内部下载与导入逻辑
  200. /// <summary>
  201. /// 执行一次下载并导入
  202. /// </summary>
  203. private int DoSingleDownload(OptimizedDownloadContext context, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err)
  204. {
  205. err = string.Empty;
  206. if (context.Category == DirectoryTypeEnum.None)
  207. {
  208. err = "未选择有效大类!";
  209. return -1;
  210. }
  211. if (!TradeMap.TryGetValue(context.Category, out var trade))
  212. {
  213. err = "未找到对应的目录类型";
  214. return -1;
  215. }
  216. if (worker.CancellationPending)
  217. {
  218. err = "操作取消!";
  219. return -1;
  220. }
  221. // 1. 下载并解压目录文件
  222. Global.writeLog("OptimizedDownload1");
  223. JObject joRtn = DownloadDirectoryWithProgress(trade.GetCode(), context.Version, worker, dialog, out err);
  224. if (joRtn == null || JsonHelper.parseIrisRtnValue(joRtn, out err) != 0)
  225. {
  226. return -1;
  227. }
  228. Global.writeLog("OptimizedDownload2");
  229. string txtPath = joRtn["filePath"]?.ToString();
  230. if (string.IsNullOrEmpty(txtPath))
  231. {
  232. err = "文件路径为空";
  233. return -1;
  234. }
  235. if (worker.CancellationPending)
  236. {
  237. err = "操作取消!";
  238. return -1;
  239. }
  240. // 2. 流式导入
  241. return ImportDataFromTxt(context, txtPath, worker, dialog, out err);
  242. }
  243. /// <summary>
  244. /// 查询目录文件名(用于单次下载前判断本地是否已存在)
  245. /// </summary>
  246. /// <returns>文件名(含 .zip 后缀);失败返回 null</returns>
  247. private string QueryDirectoryFilename(DirectoryTypeEnum category, string version, out string err)
  248. {
  249. err = string.Empty;
  250. if (category == DirectoryTypeEnum.None)
  251. {
  252. err = "未选择有效大类!";
  253. return null;
  254. }
  255. if (!TradeMap.TryGetValue(category, out var trade))
  256. {
  257. err = "未找到对应的目录类型";
  258. return null;
  259. }
  260. JObject joCenterRtn = _cBus.DownDirecotry(trade.GetCode(), version);
  261. if (JsonHelper.parseCenterRtnValue(joCenterRtn, out err) != 0)
  262. {
  263. return null;
  264. }
  265. string filename = JsonHelper.getDestValue(joCenterRtn, "output.filename");
  266. if (string.IsNullOrEmpty(filename))
  267. {
  268. err = "中心返回的文件名为空";
  269. return null;
  270. }
  271. return filename;
  272. }
  273. /// <summary>
  274. /// 从 txt 文件流式读取并导入 IRIS
  275. /// </summary>
  276. private int ImportDataFromTxt(OptimizedDownloadContext context, string txtPath, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err)
  277. {
  278. err = string.Empty;
  279. int errorCount = 0;
  280. string errorMsg = string.Empty;
  281. int currentRow = 0;
  282. try
  283. {
  284. // 2.1 先统计行数
  285. int rows = 0;
  286. using (var counter = new StreamReader(txtPath, Encoding.UTF8))
  287. {
  288. while (counter.ReadLine() != null)
  289. {
  290. rows++;
  291. }
  292. }
  293. if (rows == 0)
  294. {
  295. err = "txt 文件为空";
  296. return -1;
  297. }
  298. // 2.2 设置进度条最大值
  299. dialog.SetMaximum(rows);
  300. dialog.SetHeaderText(ProgressBarStyle.Continuous,
  301. $"本次下载总条数【{rows}】,起始版本名称【{context.Version}】", 50);
  302. int direcType = (int)context.Category;
  303. int requiredLength = GetRequiredColumnCount(direcType);
  304. int progressInterval = Math.Max(1, rows / 100); // 约 1%
  305. currentRow = 0;
  306. int processedCount = 0;
  307. int skipCount = 0;
  308. dynamic jaParams = new JArray();
  309. string currentVersionName = context.Version;
  310. DateTime lastStatusUpdateTime = DateTime.MinValue;
  311. // 2.3 逐行处理(支持字段内换行:前列不足时与下一行合并)
  312. using (var reader = new StreamReader(txtPath, Encoding.UTF8))
  313. {
  314. string pendingLine = null;
  315. string lineTmp;
  316. while ((lineTmp = reader.ReadLine()) != null)
  317. {
  318. currentRow++;
  319. if (worker.CancellationPending)
  320. {
  321. err = "操作取消!";
  322. return -1;
  323. }
  324. // 跳过空行
  325. if (string.IsNullOrWhiteSpace(lineTmp))
  326. {
  327. continue;
  328. }
  329. // 尝试与之前挂起的行合并(字段内换行)
  330. if (pendingLine != null)
  331. {
  332. lineTmp = pendingLine + "\r\n" + lineTmp;
  333. pendingLine = null;
  334. }
  335. string[] arr = lineTmp.Split('\t');
  336. if (arr.Length < requiredLength)
  337. {
  338. // 列数不足,可能是字段内换行,挂起等下一行
  339. pendingLine = lineTmp;
  340. continue;
  341. }
  342. JObject joParam = BuildDirectoryJson(arr, direcType, currentRow);
  343. if (joParam == null)
  344. {
  345. skipCount++;
  346. continue;
  347. }
  348. processedCount++;
  349. // 只在进度节点取版本号,避免每行字符串解析
  350. if (currentRow % progressInterval == 0 || currentRow == rows)
  351. {
  352. currentVersionName = JsonHelper.getDestValue(joParam, "VersionName");
  353. }
  354. // 每 1 秒更新一次标题和进度条,让用户知道还在运行
  355. if ((DateTime.Now - lastStatusUpdateTime).TotalMilliseconds > 1000)
  356. {
  357. dialog.SetHeaderText(ProgressBarStyle.Continuous,
  358. $"本次下载总条数【{rows}】,正在导入第 {currentRow} 行,起始版本名称【{context.Version}】,当前版本名称【{currentVersionName}】", 50);
  359. dialog.ReportProgress(currentRow);
  360. lastStatusUpdateTime = DateTime.Now;
  361. }
  362. jaParams.Add(joParam);
  363. // 每 batchSize 条提交一次(按实际有效记录数)
  364. if (processedCount % context.BatchSize == 0 || currentRow == rows)
  365. {
  366. if (jaParams.Count > 0)
  367. {
  368. JObject joRtn = ApplyDataToIris(ApplyDataCode, jaParams);
  369. if (joRtn["errorCode"]?.ToString() != "0")
  370. {
  371. errorCount++;
  372. errorMsg += "\r\n" + joRtn["errorMessage"];
  373. }
  374. jaParams = new JArray();
  375. }
  376. // 在批次提交节点更新进度和标题
  377. if (currentRow % progressInterval == 0 || currentRow == rows)
  378. {
  379. dialog.ReportProgress(currentRow);
  380. dialog.SetHeaderText(ProgressBarStyle.Continuous,
  381. $"本次下载总条数【{rows}】,起始版本名称【{context.Version}】,当前版本名称【{currentVersionName}】", 50);
  382. }
  383. }
  384. }
  385. // 文件末尾可能还有未合并完的行
  386. if (pendingLine != null)
  387. {
  388. string[] arr = pendingLine.Split('\t');
  389. JObject joParam = BuildDirectoryJson(arr, direcType, currentRow);
  390. if (joParam != null)
  391. {
  392. processedCount++;
  393. jaParams.Add(joParam);
  394. }
  395. }
  396. }
  397. // 提交剩余未提交的数据
  398. if (jaParams.Count > 0)
  399. {
  400. JObject joRtn = ApplyDataToIris(ApplyDataCode, jaParams);
  401. if (joRtn["errorCode"]?.ToString() != "0")
  402. {
  403. errorCount++;
  404. errorMsg += "\r\n" + joRtn["errorMessage"];
  405. }
  406. jaParams = new JArray();
  407. dialog.ReportProgress(rows);
  408. }
  409. // 更新上下文版本号,供循环下载判断终止
  410. context.Version = currentVersionName;
  411. if (processedCount == 0)
  412. {
  413. err = $"未导入任何有效数据:txt 共 {rows} 行,跳过 {skipCount} 行(列数不足或格式错误)。请检查下载文件是否完整。";
  414. return -1;
  415. }
  416. if (errorCount > 0)
  417. {
  418. err = $"导入完成,成功 {processedCount} 条,IRIS 报错 {errorCount} 次,跳过 {skipCount} 行。详情:{errorMsg}";
  419. return 0 - errorCount;
  420. }
  421. if (skipCount > 0)
  422. {
  423. err = $"导入完成,成功 {processedCount} 条,跳过 {skipCount} 行(列数不足)。请查看日志确认是否有数据丢失。";
  424. // 跳过不严重的行,仍然返回 0,但给出提示
  425. }
  426. return 0;
  427. }
  428. catch (Exception ex)
  429. {
  430. err = $"ImportDataFromTxt 异常:{ex.Message}(目录类型 {context.Category},当前处理到第 {currentRow} 行,批次大小 {context.BatchSize})";
  431. Global.writeLog(err + "\r\n" + ex.StackTrace);
  432. return -1;
  433. }
  434. }
  435. #endregion
  436. #region 配置与工具
  437. /// <summary>
  438. /// 从当前 DLL 对应的 .config 文件中读取配置值
  439. /// </summary>
  440. private string GetAppSetting(string key)
  441. {
  442. try
  443. {
  444. string assemblyPath = Assembly.GetExecutingAssembly().Location;
  445. Configuration config = ConfigurationManager.OpenExeConfiguration(assemblyPath);
  446. if (config.AppSettings.Settings[key] != null)
  447. {
  448. return config.AppSettings.Settings[key].Value;
  449. }
  450. }
  451. catch
  452. {
  453. // 忽略异常,回退到默认的 AppSettings
  454. }
  455. return ConfigurationManager.AppSettings[key];
  456. }
  457. /// <summary>
  458. /// 从 app.config 读取批量大小,默认 100
  459. /// </summary>
  460. private int GetBatchSize()
  461. {
  462. int size = DefaultBatchSize;
  463. try
  464. {
  465. string cfg = GetAppSetting(BatchSizeConfigKey);
  466. if (!string.IsNullOrEmpty(cfg) && int.TryParse(cfg, out int parsed) && parsed > 0)
  467. {
  468. size = parsed;
  469. }
  470. }
  471. catch
  472. {
  473. // 忽略配置读取异常,使用默认值
  474. }
  475. return size;
  476. }
  477. /// <summary>
  478. /// 从 app.config 读取下载超时时间(毫秒),默认 30 分钟
  479. /// </summary>
  480. private int GetTimeout()
  481. {
  482. int timeout = DefaultTimeout;
  483. try
  484. {
  485. string cfg = GetAppSetting(TimeoutConfigKey);
  486. if (!string.IsNullOrEmpty(cfg) && int.TryParse(cfg, out int parsed) && parsed > 0)
  487. {
  488. timeout = parsed;
  489. }
  490. }
  491. catch
  492. {
  493. // 忽略配置读取异常,使用默认值
  494. }
  495. return timeout;
  496. }
  497. /// <summary>
  498. /// 从 app.config 读取循环下载最大迭代次数,默认 20
  499. /// </summary>
  500. private int GetMaxLoopIterations()
  501. {
  502. int iterations = DefaultMaxLoopIterations;
  503. try
  504. {
  505. string cfg = GetAppSetting(MaxLoopIterationsConfigKey);
  506. if (!string.IsNullOrEmpty(cfg) && int.TryParse(cfg, out int parsed) && parsed > 0)
  507. {
  508. iterations = parsed;
  509. }
  510. }
  511. catch
  512. {
  513. // 忽略配置读取异常,使用默认值
  514. }
  515. return iterations;
  516. }
  517. /// <summary>
  518. /// 提交数据到 IRIS
  519. /// </summary>
  520. private JObject ApplyDataToIris(string code, JArray jaParam)
  521. {
  522. try
  523. {
  524. JObject joIn = new JObject();
  525. joIn.Add(new JProperty("params", jaParam));
  526. joIn.Add("code", code);
  527. joIn.Add("updateUserID", Global.user.ID);
  528. InvokeHelper invoker = new InvokeHelper();
  529. return invoker.invokeInsuService(joIn.ToString(), "applyDataToIris");
  530. }
  531. catch (Exception ex)
  532. {
  533. return JsonHelper.setExceptionJson(-1, "applyDataToIris", ex.Message);
  534. }
  535. }
  536. /// <summary>
  537. /// 带进度显示的目录下载并解压(不修改 HisMainBusiness.DownloadDirectory)
  538. /// </summary>
  539. private JObject DownloadDirectoryWithProgress(string funNO, string version, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err)
  540. {
  541. err = string.Empty;
  542. try
  543. {
  544. // 1. 查询目录文件号
  545. dialog.SetHeaderText(ProgressBarStyle.Marquee, $"正在获取文件信息,版本【{version}】...", 50);
  546. JObject joCenterRtn = _cBus.DownDirecotry(funNO, version);
  547. if (JsonHelper.parseCenterRtnValue(joCenterRtn, out err) != 0)
  548. {
  549. return JsonHelper.setExceptionJson(-100, "下载异常", err);
  550. }
  551. string filename = JsonHelper.getDestValue(joCenterRtn, "output.filename");
  552. string fileQuryNo = JsonHelper.getDestValue(joCenterRtn, "output.file_qury_no");
  553. if (string.IsNullOrEmpty(filename) || string.IsNullOrEmpty(fileQuryNo))
  554. {
  555. err = "中心返回的文件信息不完整";
  556. return JsonHelper.setExceptionJson(-100, "下载异常", err);
  557. }
  558. if (worker.CancellationPending)
  559. {
  560. err = "操作取消!";
  561. return JsonHelper.setExceptionJson(-100, "下载取消", err);
  562. }
  563. // 2. 下载文件(带进度)
  564. JObject jo9102Rtn = DownloadCenterFileWithProgress(filename, fileQuryNo, worker, dialog, out err);
  565. if (jo9102Rtn == null || jo9102Rtn["errorCode"]?.ToString() != "0")
  566. {
  567. return JsonHelper.setExceptionJson(-100, "保存文件异常", err);
  568. }
  569. string zipFilePath = jo9102Rtn["filePath"]?.ToString();
  570. if (string.IsNullOrEmpty(zipFilePath) || !File.Exists(zipFilePath))
  571. {
  572. err = "下载后的zip文件不存在";
  573. return JsonHelper.setExceptionJson(-100, "保存文件异常", err);
  574. }
  575. // 3. 解压
  576. string txtFileDir = System.Environment.CurrentDirectory + "\\Download";
  577. string txtFilePath = txtFileDir + "\\" + filename.Substring(0, filename.Length - 4);
  578. if (!Directory.Exists(txtFileDir))
  579. {
  580. Directory.CreateDirectory(txtFileDir);
  581. }
  582. if (File.Exists(txtFilePath))
  583. {
  584. // 在后台线程中不能弹窗,先返回特殊错误码让上层处理
  585. // 但为了保持与原 HisMainBusiness.DownloadDirectory 相同的覆盖逻辑,
  586. // 这里默认直接覆盖(医保目录更新时通常需要最新版)
  587. File.Delete(txtFilePath);
  588. }
  589. if (tools.ExtractFile(zipFilePath, txtFileDir, out err) != 0)
  590. {
  591. return JsonHelper.setExceptionJson(-100, "提取文件", err);
  592. }
  593. JObject joRtn = (JObject)jo9102Rtn.DeepClone();
  594. joRtn["filePath"] = txtFilePath;
  595. return joRtn;
  596. }
  597. catch (Exception ex)
  598. {
  599. err = $"DownloadDirectoryWithProgress 异常:{ex.Message}";
  600. Global.writeLog(err);
  601. return JsonHelper.setExceptionJson(-100, "下载中心目录", err);
  602. }
  603. }
  604. /// <summary>
  605. /// 带进度显示的中心文件下载(9102)
  606. /// </summary>
  607. private JObject DownloadCenterFileWithProgress(string filename, string fileQuryNo, BackgroundWorker worker, OptimizedDownloadProgressDialog dialog, out string err)
  608. {
  609. err = string.Empty;
  610. string filePath = Global.curEvt.path + "\\Download\\" + filename;
  611. try
  612. {
  613. if (!Directory.Exists(Global.curEvt.path + "\\Download"))
  614. {
  615. Directory.CreateDirectory(Global.curEvt.path + "\\Download");
  616. }
  617. if (File.Exists(filePath))
  618. {
  619. File.Delete(filePath);
  620. }
  621. // 构造 9102 入参
  622. dynamic jo9102InParam = new JObject();
  623. dynamic jofsDownloadIn = new JObject();
  624. jofsDownloadIn.filename = filename;
  625. jofsDownloadIn.file_qury_no = fileQuryNo;
  626. jofsDownloadIn.fixmedins_code = Global.inf.hospitalNO;
  627. jo9102InParam.fsDownloadIn = jofsDownloadIn;
  628. string requestData = JsonHelper.setCenterInpar("9102", jo9102InParam.ToString());
  629. Global.curEvt.URL = _comp.getFunNoInsuURL("9102");
  630. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Global.curEvt.URL);
  631. request.Method = "POST";
  632. request.ContentType = "application/json";
  633. request.Headers.Add("apikey", "fa8kQMIF6LB0D7c6UGQoZc6TCcZO2G6O");
  634. request.Accept = "text/html, application/xhtml+xml, */*";
  635. int timeout = GetTimeout();
  636. request.Timeout = timeout;
  637. request.ReadWriteTimeout = timeout;
  638. byte[] payload = Encoding.UTF8.GetBytes(requestData);
  639. request.ContentLength = payload.Length;
  640. using (Stream writer = request.GetRequestStream())
  641. {
  642. writer.Write(payload, 0, payload.Length);
  643. }
  644. using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
  645. using (Stream responseStream = response.GetResponseStream())
  646. using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
  647. {
  648. long totalLength = response.ContentLength;
  649. byte[] buffer = new byte[8192];
  650. int bytesRead;
  651. long downloaded = 0;
  652. DateTime lastReportTime = DateTime.MinValue;
  653. while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
  654. {
  655. if (worker.CancellationPending)
  656. {
  657. err = "操作取消!";
  658. fs.Close();
  659. SafeDelete(filePath);
  660. return JsonHelper.setExceptionJson(-100, "下载取消", err);
  661. }
  662. fs.Write(buffer, 0, bytesRead);
  663. downloaded += bytesRead;
  664. // 每 300ms 或每 1MB 刷新一次标题,避免消息队列阻塞
  665. if ((DateTime.Now - lastReportTime).TotalMilliseconds > 300)
  666. {
  667. string progressText = FormatFileSize(downloaded);
  668. if (totalLength > 0)
  669. {
  670. int percent = (int)((downloaded * 100) / totalLength);
  671. progressText = $"已下载 {progressText} / {FormatFileSize(totalLength)} ({percent}%)";
  672. dialog.SetHeaderText(ProgressBarStyle.Marquee,
  673. $"正在下载文件【{filename}】,{progressText}", 50);
  674. }
  675. else
  676. {
  677. dialog.SetHeaderText(ProgressBarStyle.Marquee,
  678. $"正在下载文件【{filename}】,{progressText}", 50);
  679. }
  680. lastReportTime = DateTime.Now;
  681. }
  682. }
  683. }
  684. dynamic joReturn = new JObject();
  685. joReturn.errorCode = 0;
  686. joReturn.errorMessage = "";
  687. joReturn.filePath = filePath;
  688. return joReturn;
  689. }
  690. catch (Exception ex)
  691. {
  692. err = ex.Message;
  693. SafeDelete(filePath);
  694. Global.writeLog("DownloadCenterFileWithProgress 异常:" + ex.Message);
  695. dynamic joReturn = new JObject();
  696. joReturn.errorCode = -100;
  697. joReturn.errorMessage = err;
  698. joReturn.filePath = filePath;
  699. return joReturn;
  700. }
  701. }
  702. private void SafeDelete(string path)
  703. {
  704. try
  705. {
  706. if (File.Exists(path))
  707. {
  708. File.Delete(path);
  709. }
  710. }
  711. catch
  712. {
  713. // 忽略清理异常
  714. }
  715. }
  716. private string FormatFileSize(long bytes)
  717. {
  718. if (bytes < 1024) return $"{bytes} B";
  719. if (bytes < 1024 * 1024) return $"{bytes / 1024.0:F2} KB";
  720. if (bytes < 1024 * 1024 * 1024) return $"{bytes / (1024.0 * 1024.0):F2} MB";
  721. return $"{bytes / (1024.0 * 1024.0 * 1024.0):F2} GB";
  722. }
  723. private string ConvertArrayNull(string arrayValue)
  724. {
  725. return arrayValue == "null" ? string.Empty : arrayValue;
  726. }
  727. #endregion
  728. #region 目录 JSON 组装(从 DataImoport.cs 复刻,保持原逻辑不变)
  729. private JObject BuildDirectoryJson(string[] arr, int direcType, int rowNumber)
  730. {
  731. int requiredLength = GetRequiredColumnCount(direcType);
  732. if (requiredLength > 0 && arr.Length < requiredLength)
  733. {
  734. // 列数不足时填充空字符串,而不是跳过(医保目录中末尾空字段常见)
  735. int originalLength = arr.Length;
  736. Array.Resize(ref arr, requiredLength);
  737. for (int i = originalLength; i < requiredLength; i++)
  738. {
  739. arr[i] = string.Empty;
  740. }
  741. }
  742. switch (direcType)
  743. {
  744. case 1: return GetDrugsJsonByTxt(arr);
  745. case 2: return GetMedicalServiceJsonByTxt(arr);
  746. case 3: return GetMaterialJsonByTxt(arr);
  747. case 4: return GetDiagnoseJsonByTxt(arr);
  748. case 5: return GetOperationJsonByTxt(arr);
  749. case 6: return GetChronicDiseaseJsonByTxt(arr);
  750. case 7: return GetDRGsJsonByTxt(arr);
  751. case 8: return GetDaySurgeryJsonByTxt(arr);
  752. case 10: return GetChineseDrugJsonByTxt(arr);
  753. case 11: return GetHosPreparationJsonByTxt(arr);
  754. default: return new JObject();
  755. }
  756. }
  757. /// <summary>
  758. /// 获取各目录类型所需的最小列数(根据 BuildDirectoryJson 中最大字段索引 +1)
  759. /// </summary>
  760. private int GetRequiredColumnCount(int direcType)
  761. {
  762. switch (direcType)
  763. {
  764. case 1: return 92; // 药品:最大 arr[91]
  765. case 2: return 16; // 诊疗:最大 arr[15]
  766. case 3: return 71; // 材料:最大 arr[70]
  767. case 4: return 24; // 诊断:最大 arr[23]
  768. case 5: return 24; // 手术:最大 arr[23]
  769. case 6: return 16; // 慢性病:最大 arr[15]
  770. case 7: return 13; // DRGs:最大 arr[12]
  771. case 8: return 11; // 日间手术:最大 arr[10]
  772. case 10: return 11; // 中药饮片:最大 arr[10]
  773. case 11: return 78; // 医疗机构制剂:最大 arr[77]
  774. default: return 0;
  775. }
  776. }
  777. private JObject GetDrugsJsonByTxt(string[] arr)
  778. {
  779. dynamic jsonTemp = new JObject();
  780. jsonTemp.ID = "";
  781. jsonTemp.updateUserID = Global.user.ID;
  782. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  783. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  784. jsonTemp.Code = arr[0];
  785. jsonTemp.Name = arr[7];
  786. jsonTemp.HisType = "1";
  787. jsonTemp.HisTypeName = "药品";
  788. jsonTemp.LocateCode = "";
  789. jsonTemp.LocateName = "";
  790. jsonTemp.DosageFormCode = arr[9];
  791. jsonTemp.DosageFormName = arr[10];
  792. jsonTemp.CategoryCode = arr[11];
  793. jsonTemp.CategoryName = arr[12];
  794. jsonTemp.Specification = arr[13];
  795. jsonTemp.SpecificationCode = arr[14];
  796. jsonTemp.UnitOfPackag = arr[42];
  797. jsonTemp.UnitOfValuation = arr[48];
  798. jsonTemp.StartDate = ConvertArrayNull(arr[36]);
  799. jsonTemp.EndDate = ConvertArrayNull(arr[37]);
  800. jsonTemp.PinyinSearchCode = arr[50];
  801. jsonTemp.Instructions = arr[35];
  802. jsonTemp.ExceptContent = "";
  803. jsonTemp.Connotation = "";
  804. jsonTemp.ValidFlag = ConvertArrayNull(arr[78]);
  805. jsonTemp.Note = arr[77];
  806. jsonTemp.VersionNO = arr[82];
  807. jsonTemp.VersionName = arr[83];
  808. jsonTemp.UseFlag = ConvertArrayNull(arr[78]);
  809. jsonTemp.DrugSafetyStandardCode = arr[8];
  810. jsonTemp.ApprovalNO = arr[61];
  811. jsonTemp.SpecialFlag = ConvertArrayNull(arr[55]); //特殊药品标志
  812. jsonTemp.LimitFlag = ConvertArrayNull(arr[57]); //限制标志
  813. jsonTemp.LimitRange = arr[56];
  814. jsonTemp.UniqueRecordNO = arr[79];
  815. jsonTemp.Manufacturers = arr[53];
  816. jsonTemp.Company = arr[85];
  817. jsonTemp.ChargeItemLevelName = arr[91];
  818. //jsonTemp.CeilingPrice = arr[91]; // 最高限价
  819. jsonTemp.PackagingMaterial = arr[29]; // 包装材质
  820. jsonTemp.MinPackagingQuantity = arr[41]; // 最小包装数量
  821. jsonTemp.MinDosageUnit = arr[43]; // 最小制剂单位
  822. jsonTemp.MinPackagingUnit = arr[42]; // 最小包装单位
  823. SetChargeItemLevel(jsonTemp);
  824. return jsonTemp;
  825. }
  826. private JObject GetMedicalServiceJsonByTxt(string[] arr)
  827. {
  828. dynamic jsonTemp = new JObject();
  829. jsonTemp.ID = "";
  830. jsonTemp.updateUserID = Global.user.ID;
  831. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  832. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  833. jsonTemp.Code = arr[0];
  834. jsonTemp.Name = arr[9];
  835. jsonTemp.HisType = "2";
  836. jsonTemp.HisTypeName = "诊疗";
  837. jsonTemp.LocateCode = "";
  838. jsonTemp.LocateName = "";
  839. jsonTemp.DosageFormCode = arr[9];
  840. jsonTemp.DosageFormName = arr[10];
  841. jsonTemp.CategoryCode = arr[8];
  842. jsonTemp.CategoryName = arr[12];
  843. jsonTemp.Specification = "";
  844. jsonTemp.SpecificationCode = "";
  845. jsonTemp.UnitOfPackag = arr[1];
  846. jsonTemp.UnitOfValuation = arr[2];
  847. jsonTemp.Instructions = arr[3];
  848. jsonTemp.ExceptContent = arr[4];
  849. jsonTemp.Connotation = arr[5];
  850. jsonTemp.ValidFlag = arr[6];
  851. jsonTemp.Note = "";
  852. jsonTemp.VersionNO = arr[14];
  853. jsonTemp.VersionName = arr[15];
  854. jsonTemp.UseFlag = arr[6];
  855. jsonTemp.DrugSafetyStandardCode = "";
  856. jsonTemp.ApprovalNO = "";
  857. jsonTemp.SpecialFlag = "";
  858. jsonTemp.LimitFlag = "";
  859. jsonTemp.LimitRange = "";
  860. jsonTemp.UniqueRecordNO = arr[13];
  861. jsonTemp.ChargeItemLevel = arr[0];
  862. if (jsonTemp.ChargeItemLevel == "1")
  863. {
  864. jsonTemp.ChargeItemLevelName = "甲";
  865. jsonTemp.SelfPercent = "0";
  866. }
  867. else if (jsonTemp.ChargeItemLevel == "2")
  868. {
  869. jsonTemp.ChargeItemLevelName = "乙";
  870. jsonTemp.SelfPercent = "0";
  871. }
  872. else if (jsonTemp.ChargeItemLevel == "3")
  873. {
  874. jsonTemp.ChargeItemLevelName = "丙";
  875. jsonTemp.SelfPercent = "100";
  876. }
  877. else
  878. {
  879. jsonTemp.ChargeItemLevel = "4";
  880. jsonTemp.SelfPercent = "100";
  881. jsonTemp.ChargeItemLevelName = "未知";
  882. }
  883. return jsonTemp;
  884. }
  885. private JObject GetMaterialJsonByTxt(string[] arr)
  886. {
  887. dynamic jsonTemp = new JObject();
  888. jsonTemp.ID = "";
  889. jsonTemp.updateUserID = Global.user.ID;
  890. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  891. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  892. jsonTemp.Code = arr[0];
  893. jsonTemp.Name = arr[1];
  894. jsonTemp.HisType = "3";
  895. jsonTemp.HisTypeName = "材料";
  896. jsonTemp.LocateCode = "";
  897. jsonTemp.LocateName = "";
  898. jsonTemp.DosageFormCode = "";
  899. jsonTemp.DosageFormName = "";
  900. jsonTemp.CategoryCode = "";
  901. jsonTemp.CategoryName = "";
  902. jsonTemp.Specification = arr[7];
  903. jsonTemp.SpecificationCode = arr[6];
  904. jsonTemp.UnitOfPackag = arr[15];
  905. jsonTemp.UnitOfValuation = ConvertArrayNull(arr[35]);
  906. jsonTemp.StartDate = ConvertArrayNull(arr[46]);
  907. jsonTemp.EndDate = ConvertArrayNull(arr[47]);
  908. jsonTemp.Instructions = arr[27];
  909. jsonTemp.ExceptContent = arr[63];
  910. jsonTemp.Connotation = "";
  911. jsonTemp.ValidFlag = arr[67];
  912. jsonTemp.Note = arr[7];
  913. jsonTemp.VersionNO = arr[69];
  914. jsonTemp.VersionName = arr[70];
  915. jsonTemp.UseFlag = arr[67];
  916. jsonTemp.DrugSafetyStandardCode = "";
  917. jsonTemp.ApprovalNO = arr[50];
  918. jsonTemp.SpecialFlag = "";
  919. jsonTemp.LimitFlag = ConvertArrayNull(arr[33]);
  920. jsonTemp.LimitRange = arr[34];
  921. jsonTemp.UniqueRecordNO = arr[68];
  922. jsonTemp.Manufacturers = arr[59];
  923. jsonTemp.ChargeItemLevelName = arr[37];
  924. SetChargeItemLevel(jsonTemp);
  925. return jsonTemp;
  926. }
  927. private JObject GetDiagnoseJsonByTxt(string[] arr)
  928. {
  929. dynamic jsonTemp = new JObject();
  930. jsonTemp.ID = "";
  931. jsonTemp.updateUserID = Global.user.ID;
  932. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  933. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  934. jsonTemp.Code = arr[10];
  935. jsonTemp.Name = arr[11];
  936. jsonTemp.HisType = "4";
  937. jsonTemp.HisTypeName = "诊断";
  938. jsonTemp.LocateCode = "";
  939. jsonTemp.LocateName = "";
  940. jsonTemp.DosageFormCode = "";
  941. jsonTemp.DosageFormName = "";
  942. jsonTemp.CategoryCode = "";
  943. jsonTemp.CategoryName = "";
  944. jsonTemp.Specification = "";
  945. jsonTemp.SpecificationCode = "";
  946. jsonTemp.UnitOfPackag = "";
  947. jsonTemp.UnitOfValuation = "";
  948. jsonTemp.StartDate = "";
  949. jsonTemp.EndDate = "";
  950. jsonTemp.Instructions = "";
  951. jsonTemp.ExceptContent = "";
  952. jsonTemp.Connotation = "";
  953. jsonTemp.ValidFlag = arr[18];
  954. jsonTemp.Note = arr[17];
  955. jsonTemp.VersionNO = arr[22];
  956. jsonTemp.VersionName = arr[23];
  957. jsonTemp.UseFlag = arr[18];
  958. jsonTemp.DrugSafetyStandardCode = "";
  959. jsonTemp.ApprovalNO = "";
  960. jsonTemp.SpecialFlag = "";
  961. jsonTemp.LimitFlag = "";
  962. jsonTemp.LimitRange = "";
  963. jsonTemp.UniqueRecordNO = arr[19];
  964. jsonTemp.Manufacturers = "";
  965. return jsonTemp;
  966. }
  967. private JObject GetChronicDiseaseJsonByTxt(string[] arr)
  968. {
  969. dynamic jsonTemp = new JObject();
  970. jsonTemp.ID = "";
  971. jsonTemp.updateUserID = Global.user.ID;
  972. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  973. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  974. jsonTemp.Code = arr[0];
  975. jsonTemp.Name = arr[1];
  976. jsonTemp.HisType = "6";
  977. jsonTemp.HisTypeName = "慢性病";
  978. jsonTemp.LocateCode = "";
  979. jsonTemp.LocateName = "";
  980. jsonTemp.DosageFormCode = "";
  981. jsonTemp.DosageFormName = "";
  982. jsonTemp.CategoryCode = arr[14];
  983. jsonTemp.CategoryName = arr[15];
  984. jsonTemp.Specification = "";
  985. jsonTemp.SpecificationCode = "";
  986. jsonTemp.UnitOfPackag = "";
  987. jsonTemp.UnitOfValuation = "";
  988. jsonTemp.StartDate = "";
  989. jsonTemp.EndDate = "";
  990. jsonTemp.Instructions = "";
  991. jsonTemp.ExceptContent = "";
  992. jsonTemp.Connotation = arr[10];
  993. jsonTemp.ValidFlag = arr[5];
  994. jsonTemp.Note = arr[4];
  995. jsonTemp.VersionNO = arr[9];
  996. jsonTemp.VersionName = arr[11];
  997. jsonTemp.UseFlag = arr[5];
  998. jsonTemp.DrugSafetyStandardCode = "";
  999. jsonTemp.ApprovalNO = "";
  1000. jsonTemp.SpecialFlag = "";
  1001. jsonTemp.LimitFlag = "";
  1002. jsonTemp.LimitRange = "";
  1003. jsonTemp.UniqueRecordNO = arr[6];
  1004. jsonTemp.Manufacturers = "";
  1005. return jsonTemp;
  1006. }
  1007. private JObject GetOperationJsonByTxt(string[] arr)
  1008. {
  1009. dynamic jsonTemp = new JObject();
  1010. jsonTemp.ID = "";
  1011. jsonTemp.updateUserID = Global.user.ID;
  1012. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  1013. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  1014. jsonTemp.Code = arr[10];
  1015. jsonTemp.Name = arr[11];
  1016. jsonTemp.HisType = "5";
  1017. jsonTemp.HisTypeName = "手术";
  1018. jsonTemp.ValidFlag = arr[18];
  1019. jsonTemp.Note = arr[17];
  1020. jsonTemp.VersionNO = arr[22];
  1021. jsonTemp.VersionName = arr[23];
  1022. jsonTemp.UseFlag = arr[18];
  1023. jsonTemp.UniqueRecordNO = arr[19];
  1024. return jsonTemp;
  1025. }
  1026. private JObject GetDRGsJsonByTxt(string[] arr)
  1027. {
  1028. dynamic jsonTemp = new JObject();
  1029. jsonTemp.ID = "";
  1030. jsonTemp.updateUserID = Global.user.ID;
  1031. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  1032. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  1033. jsonTemp.Code = arr[1];
  1034. jsonTemp.Name = arr[2];
  1035. jsonTemp.HisType = "7";
  1036. jsonTemp.HisTypeName = "DRGs";
  1037. jsonTemp.Connotation = arr[10];
  1038. jsonTemp.Instructions = arr[3];
  1039. jsonTemp.ExceptContent = arr[4];
  1040. jsonTemp.ValidFlag = arr[5];
  1041. jsonTemp.Note = arr[11];
  1042. jsonTemp.VersionNO = arr[9];
  1043. jsonTemp.VersionName = arr[12];
  1044. jsonTemp.UseFlag = arr[5];
  1045. jsonTemp.UniqueRecordNO = arr[6];
  1046. return jsonTemp;
  1047. }
  1048. private JObject GetDaySurgeryJsonByTxt(string[] arr)
  1049. {
  1050. dynamic jsonTemp = new JObject();
  1051. jsonTemp.ID = "";
  1052. jsonTemp.updateUserID = Global.user.ID;
  1053. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  1054. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  1055. jsonTemp.Code = arr[1];
  1056. jsonTemp.Name = arr[2];
  1057. jsonTemp.HisType = "8";
  1058. jsonTemp.HisTypeName = "日间手术";
  1059. jsonTemp.Connotation = arr[8];
  1060. jsonTemp.ValidFlag = arr[3];
  1061. jsonTemp.Note = arr[9];
  1062. jsonTemp.VersionNO = arr[7];
  1063. jsonTemp.VersionName = arr[10];
  1064. jsonTemp.UseFlag = arr[3];
  1065. jsonTemp.UniqueRecordNO = arr[4];
  1066. return jsonTemp;
  1067. }
  1068. private JObject GetChineseDrugJsonByTxt(string[] arr)
  1069. {
  1070. dynamic jsonTemp = new JObject();
  1071. jsonTemp.ID = "";
  1072. jsonTemp.updateUserID = Global.user.ID;
  1073. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  1074. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  1075. jsonTemp.Code = arr[0];
  1076. jsonTemp.Name = arr[1];
  1077. jsonTemp.HisType = "10";
  1078. jsonTemp.HisTypeName = "中药饮片";
  1079. jsonTemp.Connotation = arr[8];
  1080. jsonTemp.ValidFlag = arr[3];
  1081. jsonTemp.Note = arr[9];
  1082. jsonTemp.VersionNO = arr[7];
  1083. jsonTemp.VersionName = arr[10];
  1084. jsonTemp.UseFlag = arr[3];
  1085. jsonTemp.UniqueRecordNO = arr[4];
  1086. return jsonTemp;
  1087. }
  1088. private JObject GetHosPreparationJsonByTxt(string[] arr)
  1089. {
  1090. dynamic jsonTemp = new JObject();
  1091. jsonTemp.ID = "";
  1092. jsonTemp.updateUserID = Global.user.ID;
  1093. jsonTemp.HospitalDr = Global.inf.hospitalDr;
  1094. jsonTemp.InterfaceDr = Global.inf.interfaceDr;
  1095. jsonTemp.Code = arr[0];
  1096. jsonTemp.Name = arr[1];
  1097. jsonTemp.HisType = "11";
  1098. jsonTemp.HisTypeName = "医疗机构制剂";
  1099. jsonTemp.Connotation = arr[8];
  1100. jsonTemp.ValidFlag = arr[64];
  1101. jsonTemp.Note = arr[9];
  1102. jsonTemp.VersionNO = arr[70];
  1103. jsonTemp.VersionName = arr[71];
  1104. jsonTemp.UseFlag = arr[64];
  1105. jsonTemp.UniqueRecordNO = arr[46];
  1106. jsonTemp.Instructions = arr[77];
  1107. jsonTemp.NationalCode = arr[57];
  1108. jsonTemp.NationalName = arr[58];
  1109. return jsonTemp;
  1110. }
  1111. private void SetChargeItemLevel(dynamic jsonTemp)
  1112. {
  1113. string levelName = jsonTemp.ChargeItemLevelName;
  1114. if (levelName == "甲")
  1115. {
  1116. jsonTemp.ChargeItemLevel = "01";
  1117. jsonTemp.SelfPercent = "0";
  1118. }
  1119. else if (levelName == "乙")
  1120. {
  1121. jsonTemp.ChargeItemLevel = "02";
  1122. jsonTemp.SelfPercent = "0";
  1123. }
  1124. else if (levelName == "丙")
  1125. {
  1126. jsonTemp.ChargeItemLevel = "03";
  1127. jsonTemp.SelfPercent = "100";
  1128. }
  1129. else
  1130. {
  1131. jsonTemp.ChargeItemLevel = "04";
  1132. jsonTemp.SelfPercent = "100";
  1133. jsonTemp.ChargeItemLevelName = "未知";
  1134. }
  1135. }
  1136. #endregion
  1137. }
  1138. /// <summary>
  1139. /// 下载上下文
  1140. /// </summary>
  1141. internal class OptimizedDownloadContext
  1142. {
  1143. public string Version { get; set; }
  1144. public DirectoryTypeEnum Category { get; set; }
  1145. public int BatchSize { get; set; } = 100;
  1146. }
  1147. /// <summary>
  1148. /// 下载结果
  1149. /// </summary>
  1150. internal class DownloadResult
  1151. {
  1152. public int Result { get; set; }
  1153. public string ErrorMessage { get; set; }
  1154. }
  1155. /// <summary>
  1156. /// 优化的进度对话框(基于 BackgroundWorker,线程安全)
  1157. /// </summary>
  1158. internal class OptimizedDownloadProgressDialog : Form
  1159. {
  1160. private ProgressBar _progressBar;
  1161. private Label _labelStatus;
  1162. private Button _cancelButton;
  1163. private BackgroundWorker _backgroundWorker;
  1164. private int _maximum = 100;
  1165. private string _header = "正在处理...";
  1166. private int _lastProgressValue = -1;
  1167. private DateTime _lastProgressTime = DateTime.MinValue;
  1168. public Form OwnerForm { get; set; }
  1169. public Action<BackgroundWorker, OptimizedDownloadProgressDialog> DoWorkAction { get; set; }
  1170. public OptimizedDownloadProgressDialog(string headerText)
  1171. {
  1172. _header = headerText;
  1173. InitializeComponent();
  1174. }
  1175. private void InitializeComponent()
  1176. {
  1177. Text = _header;
  1178. StartPosition = FormStartPosition.CenterParent;
  1179. FormBorderStyle = FormBorderStyle.FixedDialog;
  1180. MaximizeBox = false;
  1181. MinimizeBox = false;
  1182. ShowInTaskbar = false;
  1183. TopMost = true;
  1184. ClientSize = new Size(800, 100);
  1185. _progressBar = new ProgressBar
  1186. {
  1187. Location = new Point(12, 12),
  1188. Size = new Size(700, 23),
  1189. Style = ProgressBarStyle.Continuous,
  1190. Maximum = 100,
  1191. Value = 0
  1192. };
  1193. Controls.Add(_progressBar);
  1194. _labelStatus = new Label
  1195. {
  1196. Location = new Point(12, 41),
  1197. Size = new Size(700, 23)
  1198. };
  1199. Controls.Add(_labelStatus);
  1200. _cancelButton = new Button
  1201. {
  1202. Text = "取消",
  1203. Location = new Point(520, 60),
  1204. Size = new Size(75, 23)
  1205. };
  1206. _cancelButton.Click += CancelButton_Click;
  1207. Controls.Add(_cancelButton);
  1208. _backgroundWorker = new BackgroundWorker
  1209. {
  1210. WorkerReportsProgress = true,
  1211. WorkerSupportsCancellation = true
  1212. };
  1213. _backgroundWorker.DoWork += BackgroundWorker_DoWork;
  1214. _backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
  1215. _backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;
  1216. }
  1217. public void Run()
  1218. {
  1219. if (_backgroundWorker.IsBusy) return;
  1220. // 先启动后台任务,再模态显示对话框
  1221. _backgroundWorker.RunWorkerAsync();
  1222. // ShowDialog 会让 UI 线程进入对话框消息循环
  1223. // BackgroundWorker 事件正常处理,RunWorkerCompleted 中关闭对话框
  1224. if (OwnerForm != null && !OwnerForm.IsDisposed)
  1225. {
  1226. ShowDialog(OwnerForm);
  1227. }
  1228. else
  1229. {
  1230. ShowDialog();
  1231. }
  1232. }
  1233. private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  1234. {
  1235. try
  1236. {
  1237. DoWorkAction?.Invoke(_backgroundWorker, this);
  1238. }
  1239. catch (Exception ex)
  1240. {
  1241. Global.writeLog("OptimizedDownloadBackgroundWorker_DoWork 异常:" + ex.Message);
  1242. throw;
  1243. }
  1244. }
  1245. private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
  1246. {
  1247. if (IsDisposed) return;
  1248. if (e.ProgressPercentage >= 0 && e.ProgressPercentage <= _maximum)
  1249. {
  1250. _progressBar.Value = e.ProgressPercentage;
  1251. _labelStatus.Text = $"已完成 {e.ProgressPercentage}/{_maximum}";
  1252. }
  1253. if (e.UserState is string status)
  1254. {
  1255. Text = status;
  1256. }
  1257. }
  1258. private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
  1259. {
  1260. try
  1261. {
  1262. if (!IsDisposed)
  1263. {
  1264. DialogResult = e.Cancelled || e.Error != null ? DialogResult.Cancel : DialogResult.OK;
  1265. Close();
  1266. }
  1267. }
  1268. catch (Exception ex)
  1269. {
  1270. Global.writeLog("OptimizedDownloadRunWorkerCompleted 异常:" + ex.Message);
  1271. }
  1272. }
  1273. private void CancelButton_Click(object sender, EventArgs e)
  1274. {
  1275. if (_backgroundWorker != null && _backgroundWorker.WorkerSupportsCancellation && _backgroundWorker.IsBusy)
  1276. {
  1277. _backgroundWorker.CancelAsync();
  1278. _cancelButton.Enabled = false;
  1279. _labelStatus.Text = "正在取消...";
  1280. }
  1281. }
  1282. protected override void OnFormClosing(FormClosingEventArgs e)
  1283. {
  1284. if (_backgroundWorker != null && _backgroundWorker.IsBusy)
  1285. {
  1286. _backgroundWorker.CancelAsync();
  1287. e.Cancel = true;
  1288. _cancelButton.Enabled = false;
  1289. _labelStatus.Text = "正在取消...";
  1290. }
  1291. else
  1292. {
  1293. base.OnFormClosing(e);
  1294. }
  1295. }
  1296. /// <summary>
  1297. /// 设置进度条最大值
  1298. /// </summary>
  1299. public void SetMaximum(int max)
  1300. {
  1301. _maximum = max;
  1302. _lastProgressValue = -1;
  1303. _lastProgressTime = DateTime.MinValue;
  1304. BeginInvokeIfRequired(() =>
  1305. {
  1306. if (IsDisposed) return;
  1307. _progressBar.Style = ProgressBarStyle.Continuous;
  1308. _progressBar.Maximum = max;
  1309. _progressBar.Value = 0;
  1310. });
  1311. }
  1312. /// <summary>
  1313. /// 设置标题和进度条样式
  1314. /// </summary>
  1315. public void SetHeaderText(ProgressBarStyle style, string header, int speed)
  1316. {
  1317. BeginInvokeIfRequired(() =>
  1318. {
  1319. if (IsDisposed) return;
  1320. _header = header;
  1321. Text = header;
  1322. _progressBar.Style = style;
  1323. if (style == ProgressBarStyle.Marquee)
  1324. {
  1325. _progressBar.MarqueeAnimationSpeed = speed;
  1326. }
  1327. });
  1328. }
  1329. /// <summary>
  1330. /// 报告进度(带节流)
  1331. /// </summary>
  1332. public void ReportProgress(int value)
  1333. {
  1334. if (_backgroundWorker == null || !_backgroundWorker.WorkerReportsProgress) return;
  1335. int minStep = Math.Max(1, _maximum / 200); // 约 0.5% 更新一次
  1336. const int minIntervalMs = 50;
  1337. if (value != 0 && value != _maximum &&
  1338. value - _lastProgressValue < minStep &&
  1339. (DateTime.Now - _lastProgressTime).TotalMilliseconds < minIntervalMs)
  1340. {
  1341. return;
  1342. }
  1343. _lastProgressValue = value;
  1344. _lastProgressTime = DateTime.Now;
  1345. _backgroundWorker.ReportProgress(value);
  1346. }
  1347. /// <summary>
  1348. /// 报告状态文本
  1349. /// </summary>
  1350. public void ReportStatus(string status)
  1351. {
  1352. _backgroundWorker?.ReportProgress(-1, status);
  1353. }
  1354. private void BeginInvokeIfRequired(MethodInvoker action)
  1355. {
  1356. if (InvokeRequired)
  1357. {
  1358. try
  1359. {
  1360. BeginInvoke(action);
  1361. }
  1362. catch (Exception ex) when (ex is InvalidOperationException || ex is InvalidAsynchronousStateException)
  1363. {
  1364. Global.writeLog("OptimizedDownload BeginInvokeIfRequired 异常:" + ex.Message);
  1365. }
  1366. }
  1367. else
  1368. {
  1369. action();
  1370. }
  1371. }
  1372. }
  1373. }