JiangSuWorkInjuryBusiness.cs 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. namespace ThCardReader
  11. {
  12. /// <summary>
  13. /// 江苏工伤联网结算业务类
  14. /// 基于JSSiInterface.dll动态库,严格按照江苏工伤联网接口规范v2.1实现
  15. /// 参考JiangSuSocialCardBusiness.cs的成功架构模式
  16. /// </summary>
  17. public class JiangSuWorkInjuryBusiness
  18. {
  19. #region DLL导入声明 - 严格按照工伤文档规范
  20. /// <summary>
  21. /// 初始化函数 - 检查整个运行环境
  22. /// </summary>
  23. /// <param name="pErrMsg">错误信息</param>
  24. /// <returns>成功:0,失败:-1</returns>
  25. [DllImport("JSSiInterface.dll", EntryPoint = "Si_INIT", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
  26. private extern static int Si_INIT(StringBuilder pErrMsg);
  27. /// <summary>
  28. /// 交易函数 - 处理所有业务交易
  29. /// </summary>
  30. /// <param name="inputdata">输入参数JSON字符串</param>
  31. /// <param name="outputdata">输出参数JSON字符串</param>
  32. /// <returns>成功:0,失败:<0</returns>
  33. [DllImport("JSSiInterface.dll", EntryPoint = "Si_Busi", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
  34. private extern static int Si_Busi(string inputdata, StringBuilder outputdata);
  35. #endregion
  36. #region 状态管理和内部变量
  37. /// <summary>
  38. /// 系统初始化状态
  39. /// </summary>
  40. private static bool isInitialized = false;
  41. /// <summary>
  42. /// 当前配置信息
  43. /// </summary>
  44. private static WorkInjuryConfig currentConfig = null;
  45. /// <summary>
  46. /// 当前签到流水号
  47. /// </summary>
  48. private static string currentSignNo = "";
  49. /// <summary>
  50. /// 签到时间
  51. /// </summary>
  52. private static DateTime signInTime = DateTime.MinValue;
  53. /// <summary>
  54. /// 签到操作员
  55. /// </summary>
  56. private static string signInOperator = "";
  57. /// <summary>
  58. /// 报文ID缓存(用于冲正交易)
  59. /// </summary>
  60. private static readonly Dictionary<string, TransactionRecord> transactionRecords = new Dictionary<string, TransactionRecord>();
  61. /// <summary>
  62. /// 序列号计数器(用于生成唯一报文ID)
  63. /// </summary>
  64. private static int sequenceCounter = 0;
  65. private static readonly object sequenceLock = new object();
  66. /// <summary>
  67. /// 交易记录类
  68. /// </summary>
  69. private class TransactionRecord
  70. {
  71. public string MessageId { get; set; }
  72. public string TransactionCode { get; set; }
  73. public DateTime TransactionTime { get; set; }
  74. public string OperatorId { get; set; }
  75. }
  76. #endregion
  77. #region 配置管理类
  78. /// <summary>
  79. /// 江苏工伤联网配置类 - 严格按照工伤文档规范定义
  80. /// </summary>
  81. public class WorkInjuryConfig
  82. {
  83. /// <summary>
  84. /// 协议机构编号 - 由江苏人社分配
  85. /// </summary>
  86. public string FixmedinsCode { get; set; } = "SQ201348";
  87. /// <summary>
  88. /// 协议机构名称
  89. /// </summary>
  90. public string FixmedinsName { get; set; } = "沭阳铭和医院";
  91. /// <summary>
  92. /// 接收方系统代码 - 默认"JSYTH"
  93. /// </summary>
  94. public string ReceiverSysCode { get; set; } = "JSYTH";
  95. /// <summary>
  96. /// 接口版本号 - 如"V2.1"
  97. /// </summary>
  98. public string InterfaceVersion { get; set; } = "V2.1";
  99. /// <summary>
  100. /// 经办人类别 - 1:经办人 2:自助终端 3:移动终端
  101. /// </summary>
  102. public string OperatorType { get; set; } = "1";
  103. /// <summary>
  104. /// 默认经办人编号
  105. /// </summary>
  106. public string DefaultOperator { get; set; } = "001";
  107. /// <summary>
  108. /// 默认经办人姓名
  109. /// </summary>
  110. public string DefaultOperatorName { get; set; } = "系统管理员";
  111. /// <summary>
  112. /// 日志路径
  113. /// </summary>
  114. public string LogPath { get; set; } = "logs/workinjury/";
  115. }
  116. /// <summary>
  117. /// 工伤联网交易请求参数 - 按照工伤文档标准格式
  118. /// </summary>
  119. public class WorkInjuryTransactionRequest
  120. {
  121. /// <summary>
  122. /// 交易编号 - 4位数字
  123. /// </summary>
  124. public string TransactionCode { get; set; }
  125. /// <summary>
  126. /// 业务参数 - 具体交易的输入参数
  127. /// </summary>
  128. public object BusinessParams { get; set; }
  129. /// <summary>
  130. /// 识别方式 - 1:实体社保卡 2:电子凭证
  131. /// </summary>
  132. public string IdentifyMode { get; set; } = "1";
  133. /// <summary>
  134. /// 电子社保卡二维码(识别方式为2时必填)
  135. /// </summary>
  136. public string QrCodeInfo { get; set; } = "";
  137. /// <summary>
  138. /// 经办人编号(可选,使用默认值)
  139. /// </summary>
  140. public string OperatorId { get; set; } = "";
  141. /// <summary>
  142. /// 经办人姓名(可选,使用默认值)
  143. /// </summary>
  144. public string OperatorName { get; set; } = "";
  145. }
  146. #endregion
  147. #region 交易代码映射表
  148. /// <summary>
  149. /// 交易代码映射表 - 基于工伤文档接口列表
  150. /// </summary>
  151. private static readonly Dictionary<string, string> TransactionMapping = new Dictionary<string, string>
  152. {
  153. // 认证类
  154. {"SignIn", "9001"}, // 签到
  155. {"SignOut", "9002"}, // 签退
  156. // 业务类 - 核心功能
  157. {"ReadCard", "1101"}, // 读卡
  158. {"RegisterPatient", "2201"}, // 门诊/住院登记
  159. {"CancelRegister", "2202"}, // 登记撤销
  160. {"ModifyRegister", "2203"}, // 登记信息修改
  161. {"UploadPrescription", "2204"}, // 处方明细上报
  162. {"CancelPrescription", "2205"}, // 处方明细撤销
  163. {"PreSettle", "2206"}, // 费用预结算
  164. {"Settle", "2207"}, // 费用结算
  165. {"CancelSettle", "2208"}, // 费用结算撤销
  166. {"ReverseTransaction", "2209"}, // 冲正交易
  167. // 体检类 - 体检协议机构使用
  168. {"QueryExamSchedule", "8101"}, // 查询体检排班信息
  169. {"UpdateExamSchedule", "8102"}, // 更新体检排班信息
  170. {"QueryExamReservation", "8103"}, // 查询体检预约信息
  171. {"ExamRegister", "8104"}, // 体检登记
  172. {"UploadExamDetail", "8105"}, // 上传体检明细
  173. {"QueryExamSettle", "8106"}, // 查询体检结算信息
  174. {"QueryExamDetail", "8107"}, // 查询体检明细
  175. {"ConfirmExamResult", "8108"}, // 体检结果确认
  176. {"QuerySupplementCard", "8109"}, // 补刷卡登记查询
  177. // 转院类
  178. {"UploadReferral", "2301"}, // 转诊转院申请信息上传
  179. {"QueryReferral", "2302"}, // 转诊转院申请信息查询
  180. {"CancelReferral", "2303"}, // 转诊转院申请信息撤销
  181. // 对账类
  182. {"TotalAccount", "1320"}, // 总额对账
  183. {"DetailAccount", "1321"}, // 明细对账
  184. // 下载类
  185. {"BatchDownload", "1301"}, // 批量数据下载
  186. {"QueryFeeDetail", "9103"}, // 费用明细详细信息下载
  187. {"QueryPrescriptionDetail", "9104"}, // 处方明细下载
  188. {"QueryRecentVisit", "9105"} // 参保人近期就诊信息查询
  189. };
  190. #endregion
  191. #region 核心业务方法 - 初始化函数
  192. /// <summary>
  193. /// 初始化江苏工伤联网系统
  194. /// 参考JiangSuSocialCardBusiness的Initialize方法,但适配工伤业务
  195. /// </summary>
  196. /// <param name="config">配置参数</param>
  197. /// <returns>初始化结果</returns>
  198. [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
  199. [System.Security.SecurityCritical]
  200. public static JObject Initialize(WorkInjuryConfig config = null)
  201. {
  202. var result = new JObject();
  203. try
  204. {
  205. // 添加调试信息
  206. result["debug_init_step"] = "开始初始化";
  207. // 使用默认配置或传入配置
  208. if (config == null)
  209. {
  210. config = new WorkInjuryConfig();
  211. }
  212. result["debug_init_step"] = "配置准备完成";
  213. // 检查DLL文件存在性
  214. var dllCheckResult = CheckDllExists();
  215. result["debug_dll_check"] = dllCheckResult;
  216. if (!(bool)dllCheckResult["success"])
  217. {
  218. return dllCheckResult;
  219. }
  220. result["debug_init_step"] = "DLL检查通过";
  221. // 确保日志目录存在
  222. if (!Directory.Exists(config.LogPath))
  223. {
  224. Directory.CreateDirectory(config.LogPath);
  225. }
  226. result["debug_init_step"] = "日志目录准备完成";
  227. // 调用底层初始化函数 - 增加缓冲区大小并添加调试信息
  228. StringBuilder errMsg = new StringBuilder(4096); // 增加缓冲区大小
  229. result["debug_init_step"] = "准备调用Si_INIT";
  230. // 添加DLL调用前的最后检查
  231. try
  232. {
  233. // 测试DLL是否可以加载(不调用函数)
  234. result["debug_init_step"] = "检查DLL加载状态";
  235. var dllPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JSSiInterface.dll");
  236. if (!File.Exists(dllPath))
  237. {
  238. result["success"] = false;
  239. result["code"] = 2004;
  240. result["message"] = $"DLL文件不存在: {dllPath}";
  241. result["device"] = "江苏工伤联网接口";
  242. result["debug_init_step"] = "DLL文件不存在";
  243. return result;
  244. }
  245. result["debug_dll_path"] = dllPath;
  246. result["debug_dll_size"] = new FileInfo(dllPath).Length;
  247. result["debug_init_step"] = "DLL文件检查通过,准备调用Si_INIT";
  248. }
  249. catch (Exception dllCheckEx)
  250. {
  251. result["success"] = false;
  252. result["code"] = 2005;
  253. result["message"] = $"DLL文件检查异常: {dllCheckEx.Message}";
  254. result["device"] = "江苏工伤联网接口";
  255. result["debug_init_step"] = "DLL文件检查异常";
  256. result["debug_error"] = dllCheckEx.Message;
  257. return result;
  258. }
  259. int initResult;
  260. try
  261. {
  262. // 在调用前添加更多保护
  263. result["debug_init_step"] = "即将调用Si_INIT - 这里可能发生异常";
  264. // 设置一个标记,如果DLL调用导致进程崩溃,至少我们知道问题在这里
  265. var beforeCallTime = DateTime.Now;
  266. result["debug_si_init_call_time"] = beforeCallTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
  267. initResult = Si_INIT(errMsg);
  268. var afterCallTime = DateTime.Now;
  269. var callDuration = (afterCallTime - beforeCallTime).TotalMilliseconds;
  270. result["debug_init_step"] = "Si_INIT调用完成";
  271. result["debug_dll_result"] = initResult;
  272. result["debug_dll_errmsg"] = errMsg.ToString();
  273. result["debug_si_init_duration"] = $"{callDuration}ms";
  274. result["debug_si_init_return_time"] = afterCallTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
  275. }
  276. catch (System.AccessViolationException avEx)
  277. {
  278. result["success"] = false;
  279. result["code"] = 2001;
  280. result["message"] = "DLL访问冲突异常 - 可能是DLL版本不匹配或依赖缺失";
  281. result["device"] = "江苏工伤联网接口";
  282. result["exception"] = "AccessViolationException";
  283. result["debug_init_step"] = "Si_INIT调用发生访问冲突";
  284. result["debug_error"] = avEx.Message;
  285. return result;
  286. }
  287. catch (System.DllNotFoundException dllEx)
  288. {
  289. result["success"] = false;
  290. result["code"] = 2002;
  291. result["message"] = "找不到JSSiInterface.dll或其依赖库";
  292. result["device"] = "江苏工伤联网接口";
  293. result["exception"] = "DllNotFoundException";
  294. result["debug_init_step"] = "Si_INIT调用时DLL未找到";
  295. result["debug_error"] = dllEx.Message;
  296. return result;
  297. }
  298. catch (System.EntryPointNotFoundException epEx)
  299. {
  300. result["success"] = false;
  301. result["code"] = 2003;
  302. result["message"] = "DLL中找不到Si_INIT函数入口点";
  303. result["device"] = "江苏工伤联网接口";
  304. result["exception"] = "EntryPointNotFoundException";
  305. result["debug_init_step"] = "Si_INIT函数入口点未找到";
  306. result["debug_error"] = epEx.Message;
  307. return result;
  308. }
  309. if (initResult == 0)
  310. {
  311. isInitialized = true;
  312. currentConfig = config;
  313. result["success"] = true;
  314. result["code"] = 200;
  315. result["message"] = "江苏工伤联网系统初始化成功";
  316. result["device"] = "江苏工伤联网接口";
  317. result["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
  318. result["version"] = config.InterfaceVersion;
  319. result["dllErrorMsg"] = errMsg.ToString();
  320. result["debug_init_step"] = "初始化成功";
  321. result["config"] = new JObject
  322. {
  323. ["fixmedinsCode"] = config.FixmedinsCode,
  324. ["fixmedinsName"] = config.FixmedinsName,
  325. ["interfaceVersion"] = config.InterfaceVersion
  326. };
  327. LogInfo($"系统初始化成功,版本: {config.InterfaceVersion}");
  328. }
  329. else
  330. {
  331. string errorMsg = errMsg.ToString();
  332. result["success"] = false;
  333. result["code"] = 1000 + Math.Abs(initResult);
  334. result["message"] = $"江苏工伤联网系统初始化失败: {errorMsg}";
  335. result["device"] = "江苏工伤联网接口";
  336. result["errorCode"] = initResult;
  337. result["dllErrorMsg"] = errorMsg;
  338. result["debug_init_step"] = "初始化失败";
  339. LogError($"系统初始化失败,错误码: {initResult}, 错误信息: {errorMsg}");
  340. }
  341. }
  342. catch (Exception ex)
  343. {
  344. result["success"] = false;
  345. result["code"] = 1001;
  346. result["message"] = $"江苏工伤联网系统初始化异常: {ex.Message}";
  347. result["device"] = "江苏工伤联网接口";
  348. result["exception"] = ex.GetType().Name;
  349. result["debug_init_step"] = "捕获到异常";
  350. result["debug_exception_details"] = ex.ToString();
  351. LogError($"系统初始化异常: {ex}");
  352. }
  353. return result;
  354. }
  355. #endregion
  356. #region 核心业务方法 - 通用接口函数
  357. /// <summary>
  358. /// 通用工伤联网交易处理接口
  359. /// 支持所有工伤文档定义的交易类型
  360. /// </summary>
  361. /// <param name="transactionName">交易名称(可使用中文名称或交易编号)</param>
  362. /// <param name="businessParams">业务参数对象</param>
  363. /// <param name="identifyMode">识别方式:1-实体社保卡,2-电子凭证</param>
  364. /// <param name="qrCodeInfo">电子社保卡二维码(识别方式为2时必填)</param>
  365. /// <param name="operatorId">经办人编号(可选)</param>
  366. /// <param name="operatorName">经办人姓名(可选)</param>
  367. /// <returns>交易处理结果</returns>
  368. [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
  369. [System.Security.SecurityCritical]
  370. public static JObject ProcessWorkInjuryTransaction(
  371. string transactionName,
  372. object businessParams = null,
  373. string identifyMode = "1",
  374. string qrCodeInfo = "",
  375. string operatorId = "",
  376. string operatorName = "")
  377. {
  378. var result = new JObject();
  379. try
  380. {
  381. // 1. 解析交易编号
  382. string transactionCode = GetTransactionCode(transactionName);
  383. if (string.IsNullOrEmpty(transactionCode))
  384. {
  385. result["success"] = false;
  386. result["code"] = 1002;
  387. result["message"] = $"不支持的交易类型: {transactionName}";
  388. result["device"] = "江苏工伤联网接口";
  389. return result;
  390. }
  391. // 2. 检查初始化状态
  392. if (!isInitialized)
  393. {
  394. var autoInitResult = Initialize();
  395. if (!(bool)autoInitResult["success"])
  396. {
  397. result["success"] = false;
  398. result["code"] = 1003;
  399. result["message"] = "江苏工伤联网系统未初始化";
  400. result["device"] = "江苏工伤联网接口";
  401. result["autoInitError"] = autoInitResult["message"];
  402. return result;
  403. }
  404. }
  405. // 3. 检查签到状态(除签到交易外)
  406. if (transactionCode != "9001" && string.IsNullOrEmpty(currentSignNo))
  407. {
  408. var signInResult = ProcessWorkInjuryTransaction("SignIn");
  409. if (!(bool)signInResult["success"])
  410. {
  411. result["success"] = false;
  412. result["code"] = 1004;
  413. result["message"] = "自动签到失败,无法进行业务交易";
  414. result["device"] = "江苏工伤联网接口";
  415. result["signInError"] = signInResult["message"];
  416. return result;
  417. }
  418. }
  419. // 4. 构造标准输入参数
  420. var inputData = BuildTransactionInput(transactionCode, businessParams, identifyMode, qrCodeInfo, operatorId, operatorName);
  421. string inputJson = JsonConvert.SerializeObject(inputData, Formatting.None);
  422. // 5. 调用底层DLL交易函数 - 增强异常处理
  423. StringBuilder outputBuffer = new StringBuilder(40000);
  424. result["debug_input_json"] = inputJson;
  425. result["debug_transaction_step"] = "准备调用Si_Busi";
  426. int dllResult;
  427. try
  428. {
  429. dllResult = Si_Busi(inputJson, outputBuffer);
  430. result["debug_transaction_step"] = "Si_Busi调用完成";
  431. result["debug_dll_result"] = dllResult;
  432. }
  433. catch (System.AccessViolationException avEx)
  434. {
  435. result["success"] = false;
  436. result["code"] = 2011;
  437. result["message"] = $"交易{transactionName} DLL访问冲突异常";
  438. result["device"] = "江苏工伤联网接口";
  439. result["exception"] = "AccessViolationException";
  440. result["debug_transaction_step"] = "Si_Busi调用发生访问冲突";
  441. result["debug_error"] = avEx.Message;
  442. result["transactionCode"] = transactionCode;
  443. return result;
  444. }
  445. catch (System.DllNotFoundException dllEx)
  446. {
  447. result["success"] = false;
  448. result["code"] = 2012;
  449. result["message"] = $"交易{transactionName} 找不到JSSiInterface.dll";
  450. result["device"] = "江苏工伤联网接口";
  451. result["exception"] = "DllNotFoundException";
  452. result["debug_transaction_step"] = "Si_Busi调用时DLL未找到";
  453. result["debug_error"] = dllEx.Message;
  454. result["transactionCode"] = transactionCode;
  455. return result;
  456. }
  457. catch (System.EntryPointNotFoundException epEx)
  458. {
  459. result["success"] = false;
  460. result["code"] = 2013;
  461. result["message"] = $"交易{transactionName} DLL中找不到Si_Busi函数入口点";
  462. result["device"] = "江苏工伤联网接口";
  463. result["exception"] = "EntryPointNotFoundException";
  464. result["debug_transaction_step"] = "Si_Busi函数入口点未找到";
  465. result["debug_error"] = epEx.Message;
  466. result["transactionCode"] = transactionCode;
  467. return result;
  468. }
  469. // 6. 解析和处理返回结果
  470. string outputJson = outputBuffer.ToString();
  471. result["debug_output_json"] = outputJson;
  472. result = ParseTransactionOutput(outputJson, dllResult, transactionCode);
  473. // 7. 特殊交易后处理
  474. PostProcessTransaction(transactionCode, result);
  475. LogInfo($"交易 {transactionName}({transactionCode}) 完成,结果: {result["success"]}");
  476. }
  477. catch (Exception ex)
  478. {
  479. result["success"] = false;
  480. result["code"] = 1005;
  481. result["message"] = $"工伤联网交易异常: {ex.Message}";
  482. result["device"] = "江苏工伤联网接口";
  483. result["exception"] = ex.GetType().Name;
  484. result["transactionName"] = transactionName;
  485. LogError($"交易 {transactionName} 异常: {ex.Message}");
  486. }
  487. return result;
  488. }
  489. #endregion
  490. #region 输入输出处理方法
  491. /// <summary>
  492. /// 构造标准的工伤联网交易输入参数
  493. /// 严格按照工伤文档表2格式构造,支持特殊交易格式
  494. /// </summary>
  495. private static object BuildTransactionInput(string transactionCode, object businessParams,
  496. string identifyMode, string qrCodeInfo, string operatorId, string operatorName)
  497. {
  498. // 生成唯一的发送方报文ID:协议机构编号(6)+时间(14)+顺序号(4)
  499. string msgId = GenerateMessageId();
  500. // 使用配置的经办人信息或传入的参数
  501. string finalOperatorId = string.IsNullOrEmpty(operatorId) ? currentConfig.DefaultOperator : operatorId;
  502. string finalOperatorName = string.IsNullOrEmpty(operatorName) ? currentConfig.DefaultOperatorName : operatorName;
  503. // 构造基础参数对象
  504. var baseInputData = new
  505. {
  506. infno = transactionCode, // 交易编号
  507. msgid = msgId, // 发送方报文ID
  508. recer_sys_code = currentConfig.ReceiverSysCode, // 接收方系统代码
  509. infver = currentConfig.InterfaceVersion, // 接口版本号
  510. opter_type = currentConfig.OperatorType, // 经办人类别
  511. opter = finalOperatorId, // 经办人
  512. opter_name = finalOperatorName, // 经办人姓名
  513. inf_time = DateTime.Now.ToString("yyyyMMddHHmmss"), // 交易时间
  514. fixmedins_code = currentConfig.FixmedinsCode, // 协议机构编号
  515. fixmedins_name = currentConfig.FixmedinsName, // 协议机构名称
  516. sign_no = transactionCode == "9001" ? "" : currentSignNo, // 签到流水号
  517. idfi_mode = identifyMode, // 识别方式
  518. qrcode_info = qrCodeInfo // 电子社保卡二维码
  519. };
  520. // 处理特殊交易格式
  521. object finalInputData = BuildSpecialTransactionInput(baseInputData, transactionCode, businessParams);
  522. // 保存发送方报文ID用于可能的冲正操作
  523. SaveMessageId(msgId, transactionCode);
  524. return finalInputData;
  525. }
  526. /// <summary>
  527. /// 处理特殊交易的输入格式
  528. /// 按照工伤文档要求,某些交易需要特殊的参数格式
  529. /// </summary>
  530. private static object BuildSpecialTransactionInput(object baseInputData, string transactionCode, object businessParams)
  531. {
  532. switch (transactionCode)
  533. {
  534. case "2204": // 处方明细上报 - 使用feedetail代替input
  535. return new
  536. {
  537. // 复制基础参数
  538. infno = ((dynamic)baseInputData).infno,
  539. msgid = ((dynamic)baseInputData).msgid,
  540. recer_sys_code = ((dynamic)baseInputData).recer_sys_code,
  541. infver = ((dynamic)baseInputData).infver,
  542. opter_type = ((dynamic)baseInputData).opter_type,
  543. opter = ((dynamic)baseInputData).opter,
  544. opter_name = ((dynamic)baseInputData).opter_name,
  545. inf_time = ((dynamic)baseInputData).inf_time,
  546. fixmedins_code = ((dynamic)baseInputData).fixmedins_code,
  547. fixmedins_name = ((dynamic)baseInputData).fixmedins_name,
  548. sign_no = ((dynamic)baseInputData).sign_no,
  549. idfi_mode = ((dynamic)baseInputData).idfi_mode,
  550. qrcode_info = ((dynamic)baseInputData).qrcode_info,
  551. // 特殊格式:使用feedetail替代input
  552. feedetail = businessParams ?? new object[] { }
  553. };
  554. case "8105": // 上传体检明细 - 使用tjfeedetail代替input
  555. return new
  556. {
  557. // 复制基础参数
  558. infno = ((dynamic)baseInputData).infno,
  559. msgid = ((dynamic)baseInputData).msgid,
  560. recer_sys_code = ((dynamic)baseInputData).recer_sys_code,
  561. infver = ((dynamic)baseInputData).infver,
  562. opter_type = ((dynamic)baseInputData).opter_type,
  563. opter = ((dynamic)baseInputData).opter,
  564. opter_name = ((dynamic)baseInputData).opter_name,
  565. inf_time = ((dynamic)baseInputData).inf_time,
  566. fixmedins_code = ((dynamic)baseInputData).fixmedins_code,
  567. fixmedins_name = ((dynamic)baseInputData).fixmedins_name,
  568. sign_no = ((dynamic)baseInputData).sign_no,
  569. idfi_mode = ((dynamic)baseInputData).idfi_mode,
  570. qrcode_info = ((dynamic)baseInputData).qrcode_info,
  571. // 特殊格式:使用tjfeedetail替代input
  572. tjfeedetail = businessParams ?? new object[] { }
  573. };
  574. default: // 标准交易格式
  575. return new
  576. {
  577. // 复制基础参数
  578. infno = ((dynamic)baseInputData).infno,
  579. msgid = ((dynamic)baseInputData).msgid,
  580. recer_sys_code = ((dynamic)baseInputData).recer_sys_code,
  581. infver = ((dynamic)baseInputData).infver,
  582. opter_type = ((dynamic)baseInputData).opter_type,
  583. opter = ((dynamic)baseInputData).opter,
  584. opter_name = ((dynamic)baseInputData).opter_name,
  585. inf_time = ((dynamic)baseInputData).inf_time,
  586. fixmedins_code = ((dynamic)baseInputData).fixmedins_code,
  587. fixmedins_name = ((dynamic)baseInputData).fixmedins_name,
  588. sign_no = ((dynamic)baseInputData).sign_no,
  589. idfi_mode = ((dynamic)baseInputData).idfi_mode,
  590. qrcode_info = ((dynamic)baseInputData).qrcode_info,
  591. // 标准格式:使用input
  592. input = businessParams ?? new { }
  593. };
  594. }
  595. }
  596. /// <summary>
  597. /// 解析交易输出结果并进行错误处理
  598. /// </summary>
  599. private static JObject ParseTransactionOutput(string outputJson, int dllResult, string transactionCode)
  600. {
  601. var result = new JObject();
  602. try
  603. {
  604. // DLL层面错误
  605. if (dllResult != 0)
  606. {
  607. result["success"] = false;
  608. result["code"] = 2000 + Math.Abs(dllResult);
  609. result["message"] = $"DLL调用失败,错误码: {dllResult}";
  610. result["device"] = "江苏工伤联网接口";
  611. result["dllErrorCode"] = dllResult;
  612. result["transactionCode"] = transactionCode;
  613. result["rawOutput"] = outputJson;
  614. return result;
  615. }
  616. // 解析JSON输出
  617. if (string.IsNullOrEmpty(outputJson))
  618. {
  619. result["success"] = false;
  620. result["code"] = 2001;
  621. result["message"] = "交易返回数据为空";
  622. return result;
  623. }
  624. var outputData = JObject.Parse(outputJson);
  625. // 业务层面错误检查
  626. string infcode = outputData["infcode"]?.ToString() ?? "";
  627. string errMsg = outputData["err_msg"]?.ToString() ?? "";
  628. string warnMsg = outputData["warn_msg"]?.ToString() ?? "";
  629. if (infcode == "0")
  630. {
  631. // 交易成功
  632. result["success"] = true;
  633. result["code"] = 200;
  634. result["message"] = string.IsNullOrEmpty(warnMsg) ? "交易成功" : warnMsg;
  635. result["data"] = outputData["output"];
  636. result["transactionCode"] = transactionCode;
  637. result["infRefMsgId"] = outputData["inf_refmsgid"];
  638. result["refMsgTime"] = outputData["refmsg_time"];
  639. result["respondTime"] = outputData["respond_time"];
  640. result["warnMsg"] = warnMsg;
  641. }
  642. else
  643. {
  644. // 业务失败
  645. result["success"] = false;
  646. result["code"] = 3000 + Math.Abs(int.Parse(infcode));
  647. result["message"] = string.IsNullOrEmpty(errMsg) ? "交易失败" : errMsg;
  648. result["transactionCode"] = transactionCode;
  649. result["businessErrorCode"] = infcode;
  650. result["businessErrorMsg"] = errMsg;
  651. }
  652. // 保存完整的原始返回数据
  653. result["rawOutput"] = outputJson;
  654. }
  655. catch (JsonException jsonEx)
  656. {
  657. result["success"] = false;
  658. result["code"] = 2002;
  659. result["message"] = $"返回数据解析失败: {jsonEx.Message}";
  660. result["rawOutput"] = outputJson;
  661. }
  662. catch (Exception ex)
  663. {
  664. result["success"] = false;
  665. result["code"] = 2003;
  666. result["message"] = $"输出解析异常: {ex.Message}";
  667. result["exception"] = ex.GetType().Name;
  668. }
  669. return result;
  670. }
  671. /// <summary>
  672. /// 特殊交易后处理逻辑
  673. /// </summary>
  674. private static void PostProcessTransaction(string transactionCode, JObject result)
  675. {
  676. if ((bool)result["success"])
  677. {
  678. switch (transactionCode)
  679. {
  680. case "9001": // 签到交易成功
  681. var signData = result["data"];
  682. if (signData != null)
  683. {
  684. currentSignNo = signData["sign_no"]?.ToString() ?? "";
  685. // 从服务器返回数据中获取签到时间,格式:yyyyMMddHHmmss
  686. string signTimeStr = signData["sign_time"]?.ToString() ?? "";
  687. if (!string.IsNullOrEmpty(signTimeStr) && signTimeStr.Length == 14)
  688. {
  689. try
  690. {
  691. signInTime = DateTime.ParseExact(signTimeStr, "yyyyMMddHHmmss", null);
  692. }
  693. catch
  694. {
  695. // 如果解析失败,使用本地时间作为备选
  696. signInTime = DateTime.Now;
  697. LogError($"服务器返回的签到时间格式错误: {signTimeStr},使用本地时间");
  698. }
  699. }
  700. else
  701. {
  702. // 如果服务器没有返回签到时间,使用本地时间
  703. signInTime = DateTime.Now;
  704. LogInfo($"服务器未返回签到时间,使用本地时间: {signInTime:yyyy-MM-dd HH:mm:ss}");
  705. }
  706. signInOperator = currentConfig?.DefaultOperator ?? "";
  707. // 记录签到成功日志
  708. LogInfo($"签到成功,流水号: {currentSignNo}, 时间: {signInTime:yyyy-MM-dd HH:mm:ss}");
  709. }
  710. break;
  711. case "9002": // 签退交易成功
  712. // 清除签到状态
  713. currentSignNo = "";
  714. signInTime = DateTime.MinValue;
  715. signInOperator = "";
  716. // 记录签退时间,使用统一格式
  717. string signOutTimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
  718. LogInfo($"签退成功,时间: {signOutTimeStr}");
  719. break;
  720. }
  721. }
  722. }
  723. #endregion
  724. #region 辅助工具方法
  725. /// <summary>
  726. /// 获取交易编号
  727. /// 支持中文名称、英文名称和直接的数字编号
  728. /// </summary>
  729. private static string GetTransactionCode(string transactionName)
  730. {
  731. if (string.IsNullOrEmpty(transactionName))
  732. return "";
  733. // 如果直接是4位数字编号,直接返回
  734. if (transactionName.Length == 4 && transactionName.All(char.IsDigit))
  735. return transactionName;
  736. // 从映射表中查找
  737. if (TransactionMapping.ContainsKey(transactionName))
  738. return TransactionMapping[transactionName];
  739. // 支持中文名称映射
  740. var chineseMapping = new Dictionary<string, string>
  741. {
  742. {"签到", "9001"}, {"签退", "9002"},
  743. {"读卡", "1101"}, {"登记", "2201"}, {"结算", "2207"},
  744. {"撤销", "2208"}, {"冲正", "2209"}, {"预结算", "2206"},
  745. {"处方上报", "2204"}, {"处方撤销", "2205"},
  746. {"总额对账", "1320"}, {"明细对账", "1321"},
  747. {"批量下载", "1301"}
  748. };
  749. if (chineseMapping.ContainsKey(transactionName))
  750. return chineseMapping[transactionName];
  751. return "";
  752. }
  753. /// <summary>
  754. /// 生成唯一的发送方报文ID
  755. /// 格式:协议机构编号(6位) + 时间戳(14位) + 序列号(4位) = 24位
  756. /// </summary>
  757. private static string GenerateMessageId()
  758. {
  759. lock (sequenceLock)
  760. {
  761. string institutionCode = currentConfig?.FixmedinsCode ?? "SQ201348";
  762. if (institutionCode.Length > 6)
  763. institutionCode = institutionCode.Substring(0, 6);
  764. else
  765. institutionCode = institutionCode.PadRight(6, '0');
  766. string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
  767. sequenceCounter = (sequenceCounter + 1) % 10000; // 保持4位数字
  768. string sequence = sequenceCounter.ToString("D4");
  769. return institutionCode + timestamp + sequence;
  770. }
  771. }
  772. /// <summary>
  773. /// 保存发送方报文ID用于冲正交易
  774. /// </summary>
  775. private static void SaveMessageId(string msgId, string transactionCode)
  776. {
  777. var record = new TransactionRecord
  778. {
  779. MessageId = msgId,
  780. TransactionCode = transactionCode,
  781. TransactionTime = DateTime.Now,
  782. OperatorId = currentConfig?.DefaultOperator ?? ""
  783. };
  784. transactionRecords[msgId] = record;
  785. // 清理过期记录(7天前的)
  786. var expireTime = DateTime.Now.AddDays(-7);
  787. var expiredKeys = transactionRecords
  788. .Where(kv => kv.Value.TransactionTime < expireTime)
  789. .Select(kv => kv.Key)
  790. .ToList();
  791. foreach (var key in expiredKeys)
  792. {
  793. transactionRecords.Remove(key);
  794. }
  795. }
  796. /// <summary>
  797. /// 确保DLL文件在正确位置(参考医保代码的成功实现)
  798. /// </summary>
  799. private static JObject CheckDllExists()
  800. {
  801. var result = new JObject();
  802. try
  803. {
  804. string programDir = AppDomain.CurrentDomain.BaseDirectory;
  805. string targetDllPath = Path.Combine(programDir, "JSSiInterface.dll");
  806. // 如果目标位置已经有DLL文件,直接返回成功
  807. if (File.Exists(targetDllPath))
  808. {
  809. FileInfo fileInfo = new FileInfo(targetDllPath);
  810. result["success"] = true;
  811. result["code"] = 200;
  812. result["message"] = "JSSiInterface.dll文件检查通过";
  813. result["device"] = "江苏工伤联网接口";
  814. result["data"] = new JObject
  815. {
  816. ["dllPath"] = targetDllPath,
  817. ["fileSize"] = fileInfo.Length,
  818. ["lastModified"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
  819. ["programDirectory"] = programDir
  820. };
  821. return result;
  822. }
  823. // 如果目标位置没有DLL,尝试从其他位置查找并复制(参考医保代码)
  824. string[] possiblePaths = {
  825. Path.Combine(programDir, "bin", "x86", "Release", "JSSiInterface.dll"),
  826. Path.Combine(programDir, "bin", "Debug", "JSSiInterface.dll"),
  827. Path.Combine(programDir, "bin", "Release", "JSSiInterface.dll"),
  828. Path.Combine(programDir, "ThCardReader", "bin", "x86", "Release", "JSSiInterface.dll"),
  829. Path.Combine(programDir, "ThCardReader", "bin", "Debug", "JSSiInterface.dll"),
  830. Path.Combine(programDir, "..", "ThCardReader", "bin", "x86", "Release", "JSSiInterface.dll")
  831. };
  832. string sourcePath = null;
  833. foreach (string path in possiblePaths)
  834. {
  835. if (File.Exists(path))
  836. {
  837. sourcePath = path;
  838. break;
  839. }
  840. }
  841. if (sourcePath != null)
  842. {
  843. // 复制DLL文件到程序目录
  844. File.Copy(sourcePath, targetDllPath, true);
  845. FileInfo fileInfo = new FileInfo(targetDllPath);
  846. result["success"] = true;
  847. result["code"] = 200;
  848. result["message"] = "JSSiInterface.dll文件已复制到位";
  849. result["device"] = "江苏工伤联网接口";
  850. result["data"] = new JObject
  851. {
  852. ["sourcePath"] = sourcePath,
  853. ["targetPath"] = targetDllPath,
  854. ["fileSize"] = fileInfo.Length,
  855. ["lastModified"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
  856. };
  857. }
  858. else
  859. {
  860. result["success"] = false;
  861. result["code"] = 8001;
  862. result["message"] = "找不到JSSiInterface.dll文件";
  863. result["device"] = "江苏工伤联网接口";
  864. result["data"] = new JObject
  865. {
  866. ["searchedPaths"] = string.Join("; ", possiblePaths),
  867. ["programDirectory"] = programDir,
  868. ["suggestion"] = "请确保JSSiInterface.dll文件在程序目录或bin/x86/Release目录中"
  869. };
  870. }
  871. }
  872. catch (Exception ex)
  873. {
  874. result["success"] = false;
  875. result["code"] = 8002;
  876. result["message"] = $"DLL文件检查异常: {ex.Message}";
  877. result["device"] = "江苏工伤联网接口";
  878. result["exception"] = ex.GetType().Name;
  879. }
  880. return result;
  881. }
  882. /// <summary>
  883. /// 记录信息日志
  884. /// </summary>
  885. private static void LogInfo(string message)
  886. {
  887. try
  888. {
  889. if (currentConfig != null)
  890. {
  891. string logPath = Path.Combine(currentConfig.LogPath, $"workinjury_{DateTime.Now:yyyyMMdd}.log");
  892. string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [INFO] {message}{Environment.NewLine}";
  893. File.AppendAllText(logPath, logEntry);
  894. }
  895. }
  896. catch
  897. {
  898. // 日志记录失败不影响主要业务
  899. }
  900. }
  901. /// <summary>
  902. /// 记录错误日志
  903. /// </summary>
  904. private static void LogError(string message)
  905. {
  906. try
  907. {
  908. if (currentConfig != null)
  909. {
  910. string logPath = Path.Combine(currentConfig.LogPath, $"workinjury_{DateTime.Now:yyyyMMdd}.log");
  911. string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [ERROR] {message}{Environment.NewLine}";
  912. File.AppendAllText(logPath, logEntry);
  913. }
  914. }
  915. catch
  916. {
  917. // 日志记录失败不影响主要业务
  918. }
  919. }
  920. #endregion
  921. #region 便民方法集合 - 按照设计文档要求
  922. /// <summary>
  923. /// 批量上传处方明细
  924. /// 自动处理大量处方的分批上传(每批最多50条)
  925. /// </summary>
  926. public static JObject BatchUploadPrescriptions(object[] prescriptions, string patientId = "", string visitNo = "")
  927. {
  928. var result = new JObject();
  929. var results = new JArray();
  930. try
  931. {
  932. if (prescriptions == null || prescriptions.Length == 0)
  933. {
  934. result["success"] = false;
  935. result["code"] = 1006;
  936. result["message"] = "处方明细不能为空";
  937. return result;
  938. }
  939. // 分批处理(每批50条)
  940. const int batchSize = 50;
  941. int totalBatches = (int)Math.Ceiling((double)prescriptions.Length / batchSize);
  942. int successCount = 0;
  943. int failureCount = 0;
  944. for (int i = 0; i < totalBatches; i++)
  945. {
  946. var batch = prescriptions.Skip(i * batchSize).Take(batchSize).ToArray();
  947. var batchParams = new
  948. {
  949. patient_id = patientId,
  950. visit_no = visitNo,
  951. batch_no = (i + 1).ToString(),
  952. prescriptions = batch
  953. };
  954. var batchResult = ProcessWorkInjuryTransaction("UploadPrescription", batchParams);
  955. if ((bool)batchResult["success"])
  956. {
  957. successCount++;
  958. }
  959. else
  960. {
  961. failureCount++;
  962. }
  963. results.Add(new JObject
  964. {
  965. ["batchNo"] = i + 1,
  966. ["itemCount"] = batch.Length,
  967. ["success"] = batchResult["success"],
  968. ["message"] = batchResult["message"],
  969. ["code"] = batchResult["code"]
  970. });
  971. }
  972. result["success"] = failureCount == 0;
  973. result["code"] = failureCount == 0 ? 200 : 1007;
  974. result["message"] = $"批量上传完成,成功{successCount}批,失败{failureCount}批";
  975. result["data"] = new JObject
  976. {
  977. ["totalBatches"] = totalBatches,
  978. ["totalItems"] = prescriptions.Length,
  979. ["successCount"] = successCount,
  980. ["failureCount"] = failureCount,
  981. ["batchResults"] = results
  982. };
  983. }
  984. catch (Exception ex)
  985. {
  986. result["success"] = false;
  987. result["code"] = 1008;
  988. result["message"] = $"批量上传异常: {ex.Message}";
  989. result["exception"] = ex.GetType().Name;
  990. }
  991. return result;
  992. }
  993. /// <summary>
  994. /// 完整的工伤就医流程
  995. /// 自动完成:读卡 -> 登记 -> 预结算 -> 结算 的完整流程
  996. /// </summary>
  997. public static JObject CompleteWorkInjuryProcess(object patientInfo = null, object[] feeDetails = null)
  998. {
  999. var result = new JObject();
  1000. var processSteps = new JArray();
  1001. try
  1002. {
  1003. // 第1步:读卡
  1004. var readCardResult = ProcessWorkInjuryTransaction("ReadCard");
  1005. processSteps.Add(new JObject
  1006. {
  1007. ["step"] = 1,
  1008. ["name"] = "读卡",
  1009. ["success"] = readCardResult["success"],
  1010. ["message"] = readCardResult["message"],
  1011. ["data"] = readCardResult["data"]
  1012. });
  1013. if (!(bool)readCardResult["success"])
  1014. {
  1015. result["success"] = false;
  1016. result["message"] = "读卡失败,流程终止";
  1017. result["processSteps"] = processSteps;
  1018. return result;
  1019. }
  1020. // 第2步:登记
  1021. var registerParams = patientInfo ?? new
  1022. {
  1023. visit_type = "1", // 门诊
  1024. dept_code = "001",
  1025. dept_name = "内科",
  1026. doctor_code = "DOC001",
  1027. doctor_name = "张医生"
  1028. };
  1029. var registerResult = ProcessWorkInjuryTransaction("RegisterPatient", registerParams);
  1030. processSteps.Add(new JObject
  1031. {
  1032. ["step"] = 2,
  1033. ["name"] = "登记",
  1034. ["success"] = registerResult["success"],
  1035. ["message"] = registerResult["message"],
  1036. ["data"] = registerResult["data"]
  1037. });
  1038. if (!(bool)registerResult["success"])
  1039. {
  1040. result["success"] = false;
  1041. result["message"] = "登记失败,流程终止";
  1042. result["processSteps"] = processSteps;
  1043. return result;
  1044. }
  1045. // 如果有费用明细,进行预结算和结算
  1046. if (feeDetails != null && feeDetails.Length > 0)
  1047. {
  1048. // 第3步:预结算
  1049. var preSettleParams = new
  1050. {
  1051. visit_no = registerResult["data"]?["visit_no"]?.ToString() ?? "",
  1052. fee_details = feeDetails
  1053. };
  1054. var preSettleResult = ProcessWorkInjuryTransaction("PreSettle", preSettleParams);
  1055. processSteps.Add(new JObject
  1056. {
  1057. ["step"] = 3,
  1058. ["name"] = "预结算",
  1059. ["success"] = preSettleResult["success"],
  1060. ["message"] = preSettleResult["message"],
  1061. ["data"] = preSettleResult["data"]
  1062. });
  1063. if ((bool)preSettleResult["success"])
  1064. {
  1065. // 第4步:正式结算
  1066. var settleParams = new
  1067. {
  1068. visit_no = registerResult["data"]?["visit_no"]?.ToString() ?? "",
  1069. pre_settle_id = preSettleResult["data"]?["pre_settle_id"]?.ToString() ?? ""
  1070. };
  1071. var settleResult = ProcessWorkInjuryTransaction("Settle", settleParams);
  1072. processSteps.Add(new JObject
  1073. {
  1074. ["step"] = 4,
  1075. ["name"] = "结算",
  1076. ["success"] = settleResult["success"],
  1077. ["message"] = settleResult["message"],
  1078. ["data"] = settleResult["data"]
  1079. });
  1080. }
  1081. }
  1082. result["success"] = true;
  1083. result["code"] = 200;
  1084. result["message"] = "工伤就医流程完成";
  1085. result["processSteps"] = processSteps;
  1086. }
  1087. catch (Exception ex)
  1088. {
  1089. result["success"] = false;
  1090. result["code"] = 1009;
  1091. result["message"] = $"工伤就医流程异常: {ex.Message}";
  1092. result["exception"] = ex.GetType().Name;
  1093. result["processSteps"] = processSteps;
  1094. }
  1095. return result;
  1096. }
  1097. /// <summary>
  1098. /// 智能重试交易
  1099. /// 自动重试失败的交易,使用指数退避算法
  1100. /// </summary>
  1101. public static JObject SmartRetryTransaction(string transactionName, object businessParams = null,
  1102. int maxRetries = 3, int baseDelayMs = 1000)
  1103. {
  1104. var result = new JObject();
  1105. var retryAttempts = new JArray();
  1106. for (int attempt = 1; attempt <= maxRetries; attempt++)
  1107. {
  1108. var attemptResult = ProcessWorkInjuryTransaction(transactionName, businessParams);
  1109. retryAttempts.Add(new JObject
  1110. {
  1111. ["attempt"] = attempt,
  1112. ["success"] = attemptResult["success"],
  1113. ["message"] = attemptResult["message"],
  1114. ["code"] = attemptResult["code"],
  1115. ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
  1116. });
  1117. if ((bool)attemptResult["success"])
  1118. {
  1119. result = attemptResult; // 成功时返回最后一次的结果
  1120. result["retryInfo"] = new JObject
  1121. {
  1122. ["totalAttempts"] = attempt,
  1123. ["success"] = true,
  1124. ["retryAttempts"] = retryAttempts
  1125. };
  1126. return result;
  1127. }
  1128. // 如果不是最后一次尝试,等待后重试
  1129. if (attempt < maxRetries)
  1130. {
  1131. int delay = baseDelayMs * (int)Math.Pow(2, attempt - 1); // 指数退避
  1132. Thread.Sleep(delay);
  1133. }
  1134. }
  1135. // 所有重试都失败了
  1136. result["success"] = false;
  1137. result["code"] = 1010;
  1138. result["message"] = $"交易{transactionName}经过{maxRetries}次重试后仍然失败";
  1139. result["retryInfo"] = new JObject
  1140. {
  1141. ["totalAttempts"] = maxRetries,
  1142. ["success"] = false,
  1143. ["retryAttempts"] = retryAttempts
  1144. };
  1145. return result;
  1146. }
  1147. /// <summary>
  1148. /// 获取交易统计信息
  1149. /// 提供系统性能和健康状况监控
  1150. /// </summary>
  1151. public static JObject GetTransactionStatistics()
  1152. {
  1153. var result = new JObject();
  1154. try
  1155. {
  1156. var stats = new JObject
  1157. {
  1158. ["currentTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1159. ["systemStatus"] = new JObject
  1160. {
  1161. ["initialized"] = isInitialized,
  1162. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1163. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss"),
  1164. ["currentSignNo"] = currentSignNo,
  1165. ["signInOperator"] = signInOperator
  1166. },
  1167. ["transactionRecords"] = new JObject
  1168. {
  1169. ["totalCount"] = transactionRecords.Count,
  1170. ["oldestRecord"] = transactionRecords.Count > 0 ?
  1171. transactionRecords.Values.Min(r => r.TransactionTime).ToString("yyyy-MM-dd HH:mm:ss") : null,
  1172. ["newestRecord"] = transactionRecords.Count > 0 ?
  1173. transactionRecords.Values.Max(r => r.TransactionTime).ToString("yyyy-MM-dd HH:mm:ss") : null
  1174. },
  1175. ["configuration"] = currentConfig != null ? new JObject
  1176. {
  1177. ["fixmedinsCode"] = currentConfig.FixmedinsCode,
  1178. ["fixmedinsName"] = currentConfig.FixmedinsName,
  1179. ["interfaceVersion"] = currentConfig.InterfaceVersion,
  1180. ["logPath"] = currentConfig.LogPath
  1181. } : null
  1182. };
  1183. result["success"] = true;
  1184. result["code"] = 200;
  1185. result["message"] = "统计信息获取成功";
  1186. result["data"] = stats;
  1187. }
  1188. catch (Exception ex)
  1189. {
  1190. result["success"] = false;
  1191. result["code"] = 1011;
  1192. result["message"] = $"获取统计信息异常: {ex.Message}";
  1193. result["exception"] = ex.GetType().Name;
  1194. }
  1195. return result;
  1196. }
  1197. /// <summary>
  1198. /// 系统健康检查
  1199. /// 全面检查系统状态和连接性
  1200. /// </summary>
  1201. public static JObject HealthCheck()
  1202. {
  1203. var result = new JObject();
  1204. var checks = new JObject();
  1205. try
  1206. {
  1207. // 1. 检查DLL文件
  1208. var dllCheck = CheckDllExists();
  1209. checks["dllStatus"] = new JObject
  1210. {
  1211. ["success"] = dllCheck["success"],
  1212. ["message"] = dllCheck["message"]
  1213. };
  1214. // 2. 检查初始化状态
  1215. checks["initStatus"] = new JObject
  1216. {
  1217. ["initialized"] = isInitialized,
  1218. ["hasConfig"] = currentConfig != null
  1219. };
  1220. // 3. 检查签到状态
  1221. checks["signInStatus"] = new JObject
  1222. {
  1223. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1224. ["signNo"] = currentSignNo,
  1225. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss")
  1226. };
  1227. // 4. 尝试调用系统函数(如果已初始化)
  1228. if (isInitialized)
  1229. {
  1230. var testResult = ProcessWorkInjuryTransaction("SignIn");
  1231. checks["connectionTest"] = new JObject
  1232. {
  1233. ["success"] = testResult["success"],
  1234. ["message"] = testResult["message"]
  1235. };
  1236. }
  1237. else
  1238. {
  1239. checks["connectionTest"] = new JObject
  1240. {
  1241. ["success"] = false,
  1242. ["message"] = "系统未初始化,无法测试连接"
  1243. };
  1244. }
  1245. // 5. 检查日志目录
  1246. if (currentConfig != null)
  1247. {
  1248. checks["logStatus"] = new JObject
  1249. {
  1250. ["pathExists"] = Directory.Exists(currentConfig.LogPath),
  1251. ["logPath"] = currentConfig.LogPath,
  1252. ["writable"] = true // 简化检查,实际可以尝试写入测试
  1253. };
  1254. }
  1255. // 综合评估健康状态
  1256. bool overallHealth = (bool)checks["dllStatus"]["success"] &&
  1257. (bool)checks["initStatus"]["initialized"];
  1258. result["success"] = true;
  1259. result["code"] = 200;
  1260. result["message"] = overallHealth ? "系统健康状态良好" : "系统存在问题";
  1261. result["data"] = new JObject
  1262. {
  1263. ["overallHealth"] = overallHealth,
  1264. ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1265. ["checks"] = checks
  1266. };
  1267. }
  1268. catch (Exception ex)
  1269. {
  1270. result["success"] = false;
  1271. result["code"] = 1012;
  1272. result["message"] = $"健康检查异常: {ex.Message}";
  1273. result["exception"] = ex.GetType().Name;
  1274. }
  1275. return result;
  1276. }
  1277. /// <summary>
  1278. /// 获取当前签到状态
  1279. /// </summary>
  1280. public static JObject GetSignInStatus()
  1281. {
  1282. var result = new JObject();
  1283. try
  1284. {
  1285. result["success"] = true;
  1286. result["code"] = 200;
  1287. result["message"] = "签到状态获取成功";
  1288. result["data"] = new JObject
  1289. {
  1290. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1291. ["signNo"] = currentSignNo,
  1292. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss"),
  1293. ["signInOperator"] = signInOperator,
  1294. ["sessionDuration"] = signInTime == DateTime.MinValue ? null :
  1295. ((int)(DateTime.Now - signInTime).TotalMinutes).ToString() + "分钟"
  1296. };
  1297. }
  1298. catch (Exception ex)
  1299. {
  1300. result["success"] = false;
  1301. result["code"] = 1013;
  1302. result["message"] = $"获取签到状态异常: {ex.Message}";
  1303. result["exception"] = ex.GetType().Name;
  1304. }
  1305. return result;
  1306. }
  1307. /// <summary>
  1308. /// 根据交易记录进行冲正操作
  1309. /// </summary>
  1310. public static JObject ReverseTransactionByRecord(string originalMessageId)
  1311. {
  1312. var result = new JObject();
  1313. try
  1314. {
  1315. if (!transactionRecords.ContainsKey(originalMessageId))
  1316. {
  1317. result["success"] = false;
  1318. result["code"] = 1014;
  1319. result["message"] = $"找不到原交易记录: {originalMessageId}";
  1320. return result;
  1321. }
  1322. var originalRecord = transactionRecords[originalMessageId];
  1323. var reverseParams = new
  1324. {
  1325. original_msg_id = originalMessageId,
  1326. original_transaction_code = originalRecord.TransactionCode,
  1327. original_transaction_time = originalRecord.TransactionTime.ToString("yyyyMMddHHmmss"),
  1328. reverse_reason = "系统冲正"
  1329. };
  1330. result = ProcessWorkInjuryTransaction("ReverseTransaction", reverseParams);
  1331. if ((bool)result["success"])
  1332. {
  1333. // 冲正成功后,可以选择移除原记录
  1334. // transactionRecords.Remove(originalMessageId);
  1335. LogInfo($"冲正交易成功,原交易ID: {originalMessageId}");
  1336. }
  1337. }
  1338. catch (Exception ex)
  1339. {
  1340. result["success"] = false;
  1341. result["code"] = 1015;
  1342. result["message"] = $"冲正交易异常: {ex.Message}";
  1343. result["exception"] = ex.GetType().Name;
  1344. }
  1345. return result;
  1346. }
  1347. #endregion
  1348. }
  1349. }