JiangSuWorkInjuryBusiness.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568
  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. object inputData = null; // 新增变量,便于所有分支都能访问
  380. try
  381. {
  382. // 1. 解析交易编号
  383. string transactionCode = GetTransactionCode(transactionName);
  384. if (string.IsNullOrEmpty(transactionCode))
  385. {
  386. result["success"] = false;
  387. result["code"] = 1002;
  388. result["message"] = $"不支持的交易类型: {transactionName}";
  389. result["device"] = "江苏工伤联网接口";
  390. return result;
  391. }
  392. // 2. 检查初始化状态
  393. if (!isInitialized)
  394. {
  395. var autoInitResult = Initialize();
  396. if (!(bool)autoInitResult["success"])
  397. {
  398. result["success"] = false;
  399. result["code"] = 1003;
  400. result["message"] = "江苏工伤联网系统未初始化";
  401. result["device"] = "江苏工伤联网接口";
  402. result["autoInitError"] = autoInitResult["message"];
  403. return result;
  404. }
  405. }
  406. // // 3. 检查签到状态(除签到交易外)
  407. // if (transactionCode != "9001" && string.IsNullOrEmpty(currentSignNo))
  408. // {
  409. // var signInResult = ProcessWorkInjuryTransaction("SignIn");
  410. // if (!(bool)signInResult["success"])
  411. // {
  412. // result["success"] = false;
  413. // result["code"] = 1004;
  414. // result["message"] = "自动签到失败,无法进行业务交易";
  415. // result["device"] = "江苏工伤联网接口";
  416. // result["signInError"] = signInResult["message"];
  417. // return result;
  418. // }
  419. // }
  420. // === 自动签到功能(只在业务类交易且未带sign_no时自动签到) ===
  421. if (transactionCode != "9001" && transactionCode != "9002")
  422. {
  423. string signNoFromParams = null;
  424. if (businessParams is JObject bpObj && bpObj["sign_no"] != null)
  425. signNoFromParams = bpObj["sign_no"].ToString();
  426. else if (businessParams != null)
  427. {
  428. var prop = businessParams.GetType().GetProperty("sign_no");
  429. if (prop != null)
  430. signNoFromParams = prop.GetValue(businessParams)?.ToString();
  431. }
  432. if (string.IsNullOrEmpty(signNoFromParams))
  433. {
  434. var signInResult = ProcessWorkInjuryTransaction("SignIn");
  435. if (!(bool)signInResult["success"])
  436. {
  437. result["success"] = false;
  438. result["code"] = 1004;
  439. result["message"] = "自动签到失败,无法进行业务交易";
  440. result["device"] = "江苏工伤联网接口";
  441. result["signInError"] = signInResult["message"];
  442. return result;
  443. }
  444. string newSignNo = signInResult["data"]?["sign_no"]?.ToString() ?? "";
  445. if (businessParams is JObject bpObj2)
  446. bpObj2["sign_no"] = newSignNo;
  447. else if (businessParams != null)
  448. {
  449. var prop = businessParams.GetType().GetProperty("sign_no");
  450. if (prop != null && prop.CanWrite)
  451. prop.SetValue(businessParams, newSignNo);
  452. }
  453. }
  454. }
  455. // 4. 构造标准输入参数
  456. inputData = BuildTransactionInput(transactionCode, businessParams, identifyMode, qrCodeInfo, operatorId, operatorName);
  457. string inputJson = JsonConvert.SerializeObject(inputData, Formatting.None);
  458. // 5. 调用底层DLL交易函数 - 增强异常处理
  459. StringBuilder outputBuffer = new StringBuilder(40000);
  460. result["debug_input_json"] = inputJson;
  461. result["debug_transaction_step"] = "准备调用Si_Busi";
  462. int dllResult;
  463. try
  464. {
  465. dllResult = Si_Busi(inputJson, outputBuffer);
  466. result["debug_transaction_step"] = "Si_Busi调用完成";
  467. result["debug_dll_result"] = dllResult;
  468. }
  469. catch (System.AccessViolationException avEx)
  470. {
  471. result["success"] = false;
  472. result["code"] = 2011;
  473. result["message"] = $"交易{transactionName} DLL访问冲突异常";
  474. result["device"] = "江苏工伤联网接口";
  475. result["exception"] = "AccessViolationException";
  476. result["debug_transaction_step"] = "Si_Busi调用发生访问冲突";
  477. result["debug_error"] = avEx.Message;
  478. result["transactionCode"] = transactionCode;
  479. if (inputData != null) result["transformed_parameters"] = JToken.FromObject(inputData);
  480. return result;
  481. }
  482. catch (System.DllNotFoundException dllEx)
  483. {
  484. result["success"] = false;
  485. result["code"] = 2012;
  486. result["message"] = $"交易{transactionName} 找不到JSSiInterface.dll";
  487. result["device"] = "江苏工伤联网接口";
  488. result["exception"] = "DllNotFoundException";
  489. result["debug_transaction_step"] = "Si_Busi调用时DLL未找到";
  490. result["debug_error"] = dllEx.Message;
  491. result["transactionCode"] = transactionCode;
  492. if (inputData != null) result["transformed_parameters"] = JToken.FromObject(inputData);
  493. return result;
  494. }
  495. catch (System.EntryPointNotFoundException epEx)
  496. {
  497. result["success"] = false;
  498. result["code"] = 2013;
  499. result["message"] = $"交易{transactionName} DLL中找不到Si_Busi函数入口点";
  500. result["device"] = "江苏工伤联网接口";
  501. result["exception"] = "EntryPointNotFoundException";
  502. result["debug_transaction_step"] = "Si_Busi函数入口点未找到";
  503. result["debug_error"] = epEx.Message;
  504. result["transactionCode"] = transactionCode;
  505. if (inputData != null) result["transformed_parameters"] = JToken.FromObject(inputData);
  506. return result;
  507. }
  508. // 6. 解析和处理返回结果
  509. string outputJson = outputBuffer.ToString();
  510. result["debug_output_json"] = outputJson;
  511. result = ParseTransactionOutput(outputJson, dllResult, transactionCode);
  512. // 7. 特殊交易后处理
  513. PostProcessTransaction(transactionCode, result);
  514. if (inputData != null) result["transformed_parameters"] = JToken.FromObject(inputData);
  515. LogInfo($"交易 {transactionName}({transactionCode}) 完成,结果: {result["success"]}");
  516. }
  517. catch (Exception ex)
  518. {
  519. result["success"] = false;
  520. result["code"] = 1005;
  521. result["message"] = $"工伤联网交易异常: {ex.Message}";
  522. result["device"] = "江苏工伤联网接口";
  523. result["exception"] = ex.GetType().Name;
  524. result["transactionName"] = transactionName;
  525. if (inputData != null) result["transformed_parameters"] = JToken.FromObject(inputData);
  526. LogError($"交易 {transactionName} 异常: {ex.Message}");
  527. }
  528. return result;
  529. }
  530. #endregion
  531. #region 输入输出处理方法
  532. /// <summary>
  533. /// 构造标准的工伤联网交易输入参数
  534. /// 严格按照工伤文档表2格式构造,支持特殊交易格式
  535. /// </summary>
  536. private static object BuildTransactionInput(string transactionCode, object businessParams,
  537. string identifyMode, string qrCodeInfo, string operatorId, string operatorName)
  538. {
  539. // 生成唯一的发送方报文ID:协议机构编号(6)+时间(14)+顺序号(4)
  540. string msgId = GenerateMessageId();
  541. // 使用配置的经办人信息或传入的参数
  542. string finalOperatorId = string.IsNullOrEmpty(operatorId) ? currentConfig.DefaultOperator : operatorId;
  543. string finalOperatorName = string.IsNullOrEmpty(operatorName) ? currentConfig.DefaultOperatorName : operatorName;
  544. // 构造基础参数对象
  545. var baseInputData = new
  546. {
  547. infno = transactionCode, // 交易编号
  548. msgid = msgId, // 发送方报文ID
  549. recer_sys_code = currentConfig.ReceiverSysCode, // 接收方系统代码
  550. infver = currentConfig.InterfaceVersion, // 接口版本号
  551. opter_type = currentConfig.OperatorType, // 经办人类别
  552. opter = finalOperatorId, // 经办人
  553. opter_name = finalOperatorName, // 经办人姓名
  554. inf_time = DateTime.Now.ToString("yyyyMMddHHmmss"), // 交易时间
  555. fixmedins_code = currentConfig.FixmedinsCode, // 协议机构编号
  556. fixmedins_name = currentConfig.FixmedinsName, // 协议机构名称
  557. sign_no = transactionCode == "9001" ? "" : currentSignNo, // 签到流水号
  558. idfi_mode = identifyMode, // 识别方式
  559. qrcode_info = qrCodeInfo // 电子社保卡二维码
  560. };
  561. // 处理特殊交易格式
  562. object finalInputData = BuildSpecialTransactionInput(baseInputData, transactionCode, businessParams);
  563. // 保存发送方报文ID用于可能的冲正操作
  564. SaveMessageId(msgId, transactionCode);
  565. return finalInputData;
  566. }
  567. /// <summary>
  568. /// 处理特殊交易的输入格式
  569. /// 按照工伤文档要求,某些交易需要特殊的参数格式
  570. /// </summary>
  571. private static object BuildSpecialTransactionInput(object baseInputData, string transactionCode, object businessParams)
  572. {
  573. switch (transactionCode)
  574. {
  575. case "2204": // 处方明细上报 - 使用feedetail代替input
  576. return new
  577. {
  578. // 复制基础参数
  579. infno = ((dynamic)baseInputData).infno,
  580. msgid = ((dynamic)baseInputData).msgid,
  581. recer_sys_code = ((dynamic)baseInputData).recer_sys_code,
  582. infver = ((dynamic)baseInputData).infver,
  583. opter_type = ((dynamic)baseInputData).opter_type,
  584. opter = ((dynamic)baseInputData).opter,
  585. opter_name = ((dynamic)baseInputData).opter_name,
  586. inf_time = ((dynamic)baseInputData).inf_time,
  587. fixmedins_code = ((dynamic)baseInputData).fixmedins_code,
  588. fixmedins_name = ((dynamic)baseInputData).fixmedins_name,
  589. sign_no = ((dynamic)baseInputData).sign_no,
  590. idfi_mode = ((dynamic)baseInputData).idfi_mode,
  591. qrcode_info = ((dynamic)baseInputData).qrcode_info,
  592. // 特殊格式:使用feedetail替代input
  593. feedetail = businessParams ?? new object[] { }
  594. };
  595. case "8105": // 上传体检明细 - 使用tjfeedetail代替input
  596. return new
  597. {
  598. // 复制基础参数
  599. infno = ((dynamic)baseInputData).infno,
  600. msgid = ((dynamic)baseInputData).msgid,
  601. recer_sys_code = ((dynamic)baseInputData).recer_sys_code,
  602. infver = ((dynamic)baseInputData).infver,
  603. opter_type = ((dynamic)baseInputData).opter_type,
  604. opter = ((dynamic)baseInputData).opter,
  605. opter_name = ((dynamic)baseInputData).opter_name,
  606. inf_time = ((dynamic)baseInputData).inf_time,
  607. fixmedins_code = ((dynamic)baseInputData).fixmedins_code,
  608. fixmedins_name = ((dynamic)baseInputData).fixmedins_name,
  609. sign_no = ((dynamic)baseInputData).sign_no,
  610. idfi_mode = ((dynamic)baseInputData).idfi_mode,
  611. qrcode_info = ((dynamic)baseInputData).qrcode_info,
  612. // 特殊格式:使用tjfeedetail替代input
  613. tjfeedetail = businessParams ?? new object[] { }
  614. };
  615. default: // 标准交易格式
  616. return new
  617. {
  618. // 复制基础参数
  619. infno = ((dynamic)baseInputData).infno,
  620. msgid = ((dynamic)baseInputData).msgid,
  621. recer_sys_code = ((dynamic)baseInputData).recer_sys_code,
  622. infver = ((dynamic)baseInputData).infver,
  623. opter_type = ((dynamic)baseInputData).opter_type,
  624. opter = ((dynamic)baseInputData).opter,
  625. opter_name = ((dynamic)baseInputData).opter_name,
  626. inf_time = ((dynamic)baseInputData).inf_time,
  627. fixmedins_code = ((dynamic)baseInputData).fixmedins_code,
  628. fixmedins_name = ((dynamic)baseInputData).fixmedins_name,
  629. sign_no = ((dynamic)baseInputData).sign_no,
  630. idfi_mode = ((dynamic)baseInputData).idfi_mode,
  631. qrcode_info = ((dynamic)baseInputData).qrcode_info,
  632. // 标准格式:使用input
  633. input = businessParams ?? new { }
  634. };
  635. }
  636. }
  637. /// <summary>
  638. /// 解析交易输出结果并进行错误处理
  639. /// </summary>
  640. private static JObject ParseTransactionOutput(string outputJson, int dllResult, string transactionCode)
  641. {
  642. var result = new JObject();
  643. try
  644. {
  645. // DLL层面错误
  646. if (dllResult != 0)
  647. {
  648. result["success"] = false;
  649. result["code"] = 2000 + Math.Abs(dllResult);
  650. result["message"] = $"DLL调用失败,错误码: {dllResult}";
  651. result["device"] = "江苏工伤联网接口";
  652. result["dllErrorCode"] = dllResult;
  653. result["transactionCode"] = transactionCode;
  654. result["rawOutput"] = outputJson;
  655. return result;
  656. }
  657. // 解析JSON输出
  658. if (string.IsNullOrEmpty(outputJson))
  659. {
  660. result["success"] = false;
  661. result["code"] = 2001;
  662. result["message"] = "交易返回数据为空";
  663. return result;
  664. }
  665. var outputData = JObject.Parse(outputJson);
  666. // 业务层面错误检查
  667. string infcode = outputData["infcode"]?.ToString() ?? "";
  668. string errMsg = outputData["err_msg"]?.ToString() ?? "";
  669. string warnMsg = outputData["warn_msg"]?.ToString() ?? "";
  670. if (infcode == "0")
  671. {
  672. // 交易成功
  673. result["success"] = true;
  674. result["code"] = 200;
  675. result["message"] = string.IsNullOrEmpty(warnMsg) ? "交易成功" : warnMsg;
  676. // 返回完整的输出对象,包含 infcode/err_msg/warn_msg/output 等
  677. result["data"] = outputData;
  678. result["transactionCode"] = transactionCode;
  679. result["infRefMsgId"] = outputData["inf_refmsgid"];
  680. result["refMsgTime"] = outputData["refmsg_time"];
  681. result["respondTime"] = outputData["respond_time"];
  682. result["warnMsg"] = warnMsg;
  683. }
  684. else
  685. {
  686. // 业务失败
  687. result["success"] = false;
  688. result["code"] = 3000 + Math.Abs(int.Parse(infcode));
  689. result["message"] = string.IsNullOrEmpty(errMsg) ? "交易失败" : errMsg;
  690. result["transactionCode"] = transactionCode;
  691. result["businessErrorCode"] = infcode;
  692. result["businessErrorMsg"] = errMsg;
  693. }
  694. // 保存完整的原始返回数据
  695. result["rawOutput"] = outputJson;
  696. }
  697. catch (JsonException jsonEx)
  698. {
  699. result["success"] = false;
  700. result["code"] = 2002;
  701. result["message"] = $"返回数据解析失败: {jsonEx.Message}";
  702. result["rawOutput"] = outputJson;
  703. }
  704. catch (Exception ex)
  705. {
  706. result["success"] = false;
  707. result["code"] = 2003;
  708. result["message"] = $"输出解析异常: {ex.Message}";
  709. result["exception"] = ex.GetType().Name;
  710. }
  711. return result;
  712. }
  713. /// <summary>
  714. /// 特殊交易后处理逻辑
  715. /// </summary>
  716. private static void PostProcessTransaction(string transactionCode, JObject result)
  717. {
  718. if ((bool)result["success"])
  719. {
  720. switch (transactionCode)
  721. {
  722. case "9001": // 签到交易成功
  723. // 统一后的返回结构:data 为完整 outputData(含 infcode/err_msg/warn_msg/output)
  724. // 签到具体业务字段位于 data.output 下
  725. var signData = result["data"]? ["output"];
  726. if (signData != null)
  727. {
  728. currentSignNo = signData["sign_no"]?.ToString() ?? "";
  729. // 从服务器返回数据中获取签到时间,格式:yyyyMMddHHmmss
  730. string signTimeStr = signData["sign_time"]?.ToString() ?? "";
  731. if (!string.IsNullOrEmpty(signTimeStr) && signTimeStr.Length == 14)
  732. {
  733. try
  734. {
  735. signInTime = DateTime.ParseExact(signTimeStr, "yyyyMMddHHmmss", null);
  736. }
  737. catch
  738. {
  739. // 如果解析失败,使用本地时间作为备选
  740. signInTime = DateTime.Now;
  741. LogError($"服务器返回的签到时间格式错误: {signTimeStr},使用本地时间");
  742. }
  743. }
  744. else
  745. {
  746. // 如果服务器没有返回签到时间,使用本地时间
  747. signInTime = DateTime.Now;
  748. LogInfo($"服务器未返回签到时间,使用本地时间: {signInTime:yyyy-MM-dd HH:mm:ss}");
  749. }
  750. signInOperator = currentConfig?.DefaultOperator ?? "";
  751. // 记录签到成功日志
  752. LogInfo($"签到成功,流水号: {currentSignNo}, 时间: {signInTime:yyyy-MM-dd HH:mm:ss}");
  753. }
  754. break;
  755. case "9002": // 签退交易成功
  756. // 清除签到状态
  757. currentSignNo = "";
  758. signInTime = DateTime.MinValue;
  759. signInOperator = "";
  760. // 记录签退时间,使用统一格式
  761. string signOutTimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
  762. LogInfo($"签退成功,时间: {signOutTimeStr}");
  763. break;
  764. }
  765. }
  766. }
  767. #endregion
  768. #region 辅助工具方法
  769. /// <summary>
  770. /// 获取交易编号
  771. /// 支持中文名称、英文名称和直接的数字编号
  772. /// </summary>
  773. private static string GetTransactionCode(string transactionName)
  774. {
  775. if (string.IsNullOrEmpty(transactionName))
  776. return "";
  777. // 如果直接是4位数字编号,直接返回
  778. if (transactionName.Length == 4 && transactionName.All(char.IsDigit))
  779. return transactionName;
  780. // 从映射表中查找
  781. if (TransactionMapping.ContainsKey(transactionName))
  782. return TransactionMapping[transactionName];
  783. // 支持中文名称映射
  784. var chineseMapping = new Dictionary<string, string>
  785. {
  786. {"签到", "9001"}, {"签退", "9002"},
  787. {"读卡", "1101"}, {"登记", "2201"}, {"结算", "2207"},
  788. {"撤销", "2208"}, {"冲正", "2209"}, {"预结算", "2206"},
  789. {"处方上报", "2204"}, {"处方撤销", "2205"},
  790. {"总额对账", "1320"}, {"明细对账", "1321"},
  791. {"批量下载", "1301"}
  792. };
  793. if (chineseMapping.ContainsKey(transactionName))
  794. return chineseMapping[transactionName];
  795. return "";
  796. }
  797. /// <summary>
  798. /// 生成唯一的发送方报文ID
  799. /// 格式:协议机构编号(6位) + 时间戳(14位) + 序列号(4位) = 24位
  800. /// </summary>
  801. private static string GenerateMessageId()
  802. {
  803. lock (sequenceLock)
  804. {
  805. string institutionCode = currentConfig?.FixmedinsCode ?? "SQ201348";
  806. if (institutionCode.Length > 6)
  807. institutionCode = institutionCode.Substring(0, 6);
  808. else
  809. institutionCode = institutionCode.PadRight(6, '0');
  810. string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
  811. sequenceCounter = (sequenceCounter + 1) % 10000; // 保持4位数字
  812. string sequence = sequenceCounter.ToString("D4");
  813. return institutionCode + timestamp + sequence;
  814. }
  815. }
  816. /// <summary>
  817. /// 保存发送方报文ID用于冲正交易
  818. /// </summary>
  819. private static void SaveMessageId(string msgId, string transactionCode)
  820. {
  821. var record = new TransactionRecord
  822. {
  823. MessageId = msgId,
  824. TransactionCode = transactionCode,
  825. TransactionTime = DateTime.Now,
  826. OperatorId = currentConfig?.DefaultOperator ?? ""
  827. };
  828. transactionRecords[msgId] = record;
  829. // 清理过期记录(7天前的)
  830. var expireTime = DateTime.Now.AddDays(-7);
  831. var expiredKeys = transactionRecords
  832. .Where(kv => kv.Value.TransactionTime < expireTime)
  833. .Select(kv => kv.Key)
  834. .ToList();
  835. foreach (var key in expiredKeys)
  836. {
  837. transactionRecords.Remove(key);
  838. }
  839. }
  840. /// <summary>
  841. /// 确保DLL文件在正确位置(参考医保代码的成功实现)
  842. /// </summary>
  843. private static JObject CheckDllExists()
  844. {
  845. var result = new JObject();
  846. try
  847. {
  848. string programDir = AppDomain.CurrentDomain.BaseDirectory;
  849. string targetDllPath = Path.Combine(programDir, "JSSiInterface.dll");
  850. // 如果目标位置已经有DLL文件,直接返回成功
  851. if (File.Exists(targetDllPath))
  852. {
  853. FileInfo fileInfo = new FileInfo(targetDllPath);
  854. result["success"] = true;
  855. result["code"] = 200;
  856. result["message"] = "JSSiInterface.dll文件检查通过";
  857. result["device"] = "江苏工伤联网接口";
  858. result["data"] = new JObject
  859. {
  860. ["dllPath"] = targetDllPath,
  861. ["fileSize"] = fileInfo.Length,
  862. ["lastModified"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
  863. ["programDirectory"] = programDir
  864. };
  865. return result;
  866. }
  867. // 如果目标位置没有DLL,尝试从其他位置查找并复制(参考医保代码)
  868. string[] possiblePaths = {
  869. Path.Combine(programDir, "bin", "x86", "Release", "JSSiInterface.dll"),
  870. Path.Combine(programDir, "bin", "Debug", "JSSiInterface.dll"),
  871. Path.Combine(programDir, "bin", "Release", "JSSiInterface.dll"),
  872. Path.Combine(programDir, "ThCardReader", "bin", "x86", "Release", "JSSiInterface.dll"),
  873. Path.Combine(programDir, "ThCardReader", "bin", "Debug", "JSSiInterface.dll"),
  874. Path.Combine(programDir, "..", "ThCardReader", "bin", "x86", "Release", "JSSiInterface.dll")
  875. };
  876. string sourcePath = null;
  877. foreach (string path in possiblePaths)
  878. {
  879. if (File.Exists(path))
  880. {
  881. sourcePath = path;
  882. break;
  883. }
  884. }
  885. if (sourcePath != null)
  886. {
  887. // 复制DLL文件到程序目录
  888. File.Copy(sourcePath, targetDllPath, true);
  889. FileInfo fileInfo = new FileInfo(targetDllPath);
  890. result["success"] = true;
  891. result["code"] = 200;
  892. result["message"] = "JSSiInterface.dll文件已复制到位";
  893. result["device"] = "江苏工伤联网接口";
  894. result["data"] = new JObject
  895. {
  896. ["sourcePath"] = sourcePath,
  897. ["targetPath"] = targetDllPath,
  898. ["fileSize"] = fileInfo.Length,
  899. ["lastModified"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
  900. };
  901. }
  902. else
  903. {
  904. result["success"] = false;
  905. result["code"] = 8001;
  906. result["message"] = "找不到JSSiInterface.dll文件";
  907. result["device"] = "江苏工伤联网接口";
  908. result["data"] = new JObject
  909. {
  910. ["searchedPaths"] = string.Join("; ", possiblePaths),
  911. ["programDirectory"] = programDir,
  912. ["suggestion"] = "请确保JSSiInterface.dll文件在程序目录或bin/x86/Release目录中"
  913. };
  914. }
  915. }
  916. catch (Exception ex)
  917. {
  918. result["success"] = false;
  919. result["code"] = 8002;
  920. result["message"] = $"DLL文件检查异常: {ex.Message}";
  921. result["device"] = "江苏工伤联网接口";
  922. result["exception"] = ex.GetType().Name;
  923. }
  924. return result;
  925. }
  926. /// <summary>
  927. /// 记录信息日志
  928. /// </summary>
  929. private static void LogInfo(string message)
  930. {
  931. try
  932. {
  933. if (currentConfig != null)
  934. {
  935. string logPath = Path.Combine(currentConfig.LogPath, $"workinjury_{DateTime.Now:yyyyMMdd}.log");
  936. string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [INFO] {message}{Environment.NewLine}";
  937. File.AppendAllText(logPath, logEntry);
  938. }
  939. }
  940. catch
  941. {
  942. // 日志记录失败不影响主要业务
  943. }
  944. }
  945. /// <summary>
  946. /// 记录错误日志
  947. /// </summary>
  948. private static void LogError(string message)
  949. {
  950. try
  951. {
  952. if (currentConfig != null)
  953. {
  954. string logPath = Path.Combine(currentConfig.LogPath, $"workinjury_{DateTime.Now:yyyyMMdd}.log");
  955. string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [ERROR] {message}{Environment.NewLine}";
  956. File.AppendAllText(logPath, logEntry);
  957. }
  958. }
  959. catch
  960. {
  961. // 日志记录失败不影响主要业务
  962. }
  963. }
  964. #endregion
  965. #region 便民方法集合 - 按照设计文档要求
  966. /// <summary>
  967. /// 批量上传处方明细
  968. /// 自动处理大量处方的分批上传(每批最多50条)
  969. /// </summary>
  970. public static JObject BatchUploadPrescriptions(object[] prescriptions, string patientId = "", string visitNo = "")
  971. {
  972. var result = new JObject();
  973. var results = new JArray();
  974. try
  975. {
  976. if (prescriptions == null || prescriptions.Length == 0)
  977. {
  978. result["success"] = false;
  979. result["code"] = 1006;
  980. result["message"] = "处方明细不能为空";
  981. return result;
  982. }
  983. // 分批处理(每批50条)
  984. const int batchSize = 50;
  985. int totalBatches = (int)Math.Ceiling((double)prescriptions.Length / batchSize);
  986. int successCount = 0;
  987. int failureCount = 0;
  988. for (int i = 0; i < totalBatches; i++)
  989. {
  990. var batch = prescriptions.Skip(i * batchSize).Take(batchSize).ToArray();
  991. var batchParams = new
  992. {
  993. patient_id = patientId,
  994. visit_no = visitNo,
  995. batch_no = (i + 1).ToString(),
  996. prescriptions = batch
  997. };
  998. var batchResult = ProcessWorkInjuryTransaction("UploadPrescription", batchParams);
  999. if ((bool)batchResult["success"])
  1000. {
  1001. successCount++;
  1002. }
  1003. else
  1004. {
  1005. failureCount++;
  1006. }
  1007. results.Add(new JObject
  1008. {
  1009. ["batchNo"] = i + 1,
  1010. ["itemCount"] = batch.Length,
  1011. ["success"] = batchResult["success"],
  1012. ["message"] = batchResult["message"],
  1013. ["code"] = batchResult["code"]
  1014. });
  1015. }
  1016. result["success"] = failureCount == 0;
  1017. result["code"] = failureCount == 0 ? 200 : 1007;
  1018. result["message"] = $"批量上传完成,成功{successCount}批,失败{failureCount}批";
  1019. result["data"] = new JObject
  1020. {
  1021. ["totalBatches"] = totalBatches,
  1022. ["totalItems"] = prescriptions.Length,
  1023. ["successCount"] = successCount,
  1024. ["failureCount"] = failureCount,
  1025. ["batchResults"] = results
  1026. };
  1027. }
  1028. catch (Exception ex)
  1029. {
  1030. result["success"] = false;
  1031. result["code"] = 1008;
  1032. result["message"] = $"批量上传异常: {ex.Message}";
  1033. result["exception"] = ex.GetType().Name;
  1034. }
  1035. return result;
  1036. }
  1037. /// <summary>
  1038. /// 完整的工伤就医流程
  1039. /// 自动完成:读卡 -> 登记 -> 预结算 -> 结算 的完整流程
  1040. /// </summary>
  1041. public static JObject CompleteWorkInjuryProcess(object patientInfo = null, object[] feeDetails = null)
  1042. {
  1043. var result = new JObject();
  1044. var processSteps = new JArray();
  1045. try
  1046. {
  1047. // 第1步:读卡
  1048. var readCardResult = ProcessWorkInjuryTransaction("ReadCard");
  1049. processSteps.Add(new JObject
  1050. {
  1051. ["step"] = 1,
  1052. ["name"] = "读卡",
  1053. ["success"] = readCardResult["success"],
  1054. ["message"] = readCardResult["message"],
  1055. ["data"] = readCardResult["data"]
  1056. });
  1057. if (!(bool)readCardResult["success"])
  1058. {
  1059. result["success"] = false;
  1060. result["message"] = "读卡失败,流程终止";
  1061. result["processSteps"] = processSteps;
  1062. return result;
  1063. }
  1064. // 第2步:登记
  1065. var registerParams = patientInfo ?? new
  1066. {
  1067. visit_type = "1", // 门诊
  1068. dept_code = "001",
  1069. dept_name = "内科",
  1070. doctor_code = "DOC001",
  1071. doctor_name = "张医生"
  1072. };
  1073. var registerResult = ProcessWorkInjuryTransaction("RegisterPatient", registerParams);
  1074. processSteps.Add(new JObject
  1075. {
  1076. ["step"] = 2,
  1077. ["name"] = "登记",
  1078. ["success"] = registerResult["success"],
  1079. ["message"] = registerResult["message"],
  1080. ["data"] = registerResult["data"]
  1081. });
  1082. if (!(bool)registerResult["success"])
  1083. {
  1084. result["success"] = false;
  1085. result["message"] = "登记失败,流程终止";
  1086. result["processSteps"] = processSteps;
  1087. return result;
  1088. }
  1089. // 如果有费用明细,进行预结算和结算
  1090. if (feeDetails != null && feeDetails.Length > 0)
  1091. {
  1092. // 第3步:预结算
  1093. var preSettleParams = new
  1094. {
  1095. visit_no = registerResult["data"]?["visit_no"]?.ToString() ?? "",
  1096. fee_details = feeDetails
  1097. };
  1098. var preSettleResult = ProcessWorkInjuryTransaction("PreSettle", preSettleParams);
  1099. processSteps.Add(new JObject
  1100. {
  1101. ["step"] = 3,
  1102. ["name"] = "预结算",
  1103. ["success"] = preSettleResult["success"],
  1104. ["message"] = preSettleResult["message"],
  1105. ["data"] = preSettleResult["data"]
  1106. });
  1107. if ((bool)preSettleResult["success"])
  1108. {
  1109. // 第4步:正式结算
  1110. var settleParams = new
  1111. {
  1112. visit_no = registerResult["data"]?["visit_no"]?.ToString() ?? "",
  1113. pre_settle_id = preSettleResult["data"]?["pre_settle_id"]?.ToString() ?? ""
  1114. };
  1115. var settleResult = ProcessWorkInjuryTransaction("Settle", settleParams);
  1116. processSteps.Add(new JObject
  1117. {
  1118. ["step"] = 4,
  1119. ["name"] = "结算",
  1120. ["success"] = settleResult["success"],
  1121. ["message"] = settleResult["message"],
  1122. ["data"] = settleResult["data"]
  1123. });
  1124. }
  1125. }
  1126. result["success"] = true;
  1127. result["code"] = 200;
  1128. result["message"] = "工伤就医流程完成";
  1129. result["processSteps"] = processSteps;
  1130. }
  1131. catch (Exception ex)
  1132. {
  1133. result["success"] = false;
  1134. result["code"] = 1009;
  1135. result["message"] = $"工伤就医流程异常: {ex.Message}";
  1136. result["exception"] = ex.GetType().Name;
  1137. result["processSteps"] = processSteps;
  1138. }
  1139. return result;
  1140. }
  1141. /// <summary>
  1142. /// 智能重试交易
  1143. /// 自动重试失败的交易,使用指数退避算法
  1144. /// </summary>
  1145. public static JObject SmartRetryTransaction(string transactionName, object businessParams = null,
  1146. int maxRetries = 3, int baseDelayMs = 1000)
  1147. {
  1148. var result = new JObject();
  1149. var retryAttempts = new JArray();
  1150. for (int attempt = 1; attempt <= maxRetries; attempt++)
  1151. {
  1152. var attemptResult = ProcessWorkInjuryTransaction(transactionName, businessParams);
  1153. retryAttempts.Add(new JObject
  1154. {
  1155. ["attempt"] = attempt,
  1156. ["success"] = attemptResult["success"],
  1157. ["message"] = attemptResult["message"],
  1158. ["code"] = attemptResult["code"],
  1159. ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
  1160. });
  1161. if ((bool)attemptResult["success"])
  1162. {
  1163. result = attemptResult; // 成功时返回最后一次的结果
  1164. result["retryInfo"] = new JObject
  1165. {
  1166. ["totalAttempts"] = attempt,
  1167. ["success"] = true,
  1168. ["retryAttempts"] = retryAttempts
  1169. };
  1170. return result;
  1171. }
  1172. // 如果不是最后一次尝试,等待后重试
  1173. if (attempt < maxRetries)
  1174. {
  1175. int delay = baseDelayMs * (int)Math.Pow(2, attempt - 1); // 指数退避
  1176. Thread.Sleep(delay);
  1177. }
  1178. }
  1179. // 所有重试都失败了
  1180. result["success"] = false;
  1181. result["code"] = 1010;
  1182. result["message"] = $"交易{transactionName}经过{maxRetries}次重试后仍然失败";
  1183. result["retryInfo"] = new JObject
  1184. {
  1185. ["totalAttempts"] = maxRetries,
  1186. ["success"] = false,
  1187. ["retryAttempts"] = retryAttempts
  1188. };
  1189. return result;
  1190. }
  1191. /// <summary>
  1192. /// 获取交易统计信息
  1193. /// 提供系统性能和健康状况监控
  1194. /// </summary>
  1195. public static JObject GetTransactionStatistics()
  1196. {
  1197. var result = new JObject();
  1198. try
  1199. {
  1200. var stats = new JObject
  1201. {
  1202. ["currentTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1203. ["systemStatus"] = new JObject
  1204. {
  1205. ["initialized"] = isInitialized,
  1206. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1207. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss"),
  1208. ["currentSignNo"] = currentSignNo,
  1209. ["signInOperator"] = signInOperator
  1210. },
  1211. ["transactionRecords"] = new JObject
  1212. {
  1213. ["totalCount"] = transactionRecords.Count,
  1214. ["oldestRecord"] = transactionRecords.Count > 0 ?
  1215. transactionRecords.Values.Min(r => r.TransactionTime).ToString("yyyy-MM-dd HH:mm:ss") : null,
  1216. ["newestRecord"] = transactionRecords.Count > 0 ?
  1217. transactionRecords.Values.Max(r => r.TransactionTime).ToString("yyyy-MM-dd HH:mm:ss") : null
  1218. },
  1219. ["configuration"] = currentConfig != null ? new JObject
  1220. {
  1221. ["fixmedinsCode"] = currentConfig.FixmedinsCode,
  1222. ["fixmedinsName"] = currentConfig.FixmedinsName,
  1223. ["interfaceVersion"] = currentConfig.InterfaceVersion,
  1224. ["logPath"] = currentConfig.LogPath
  1225. } : null
  1226. };
  1227. result["success"] = true;
  1228. result["code"] = 200;
  1229. result["message"] = "统计信息获取成功";
  1230. result["data"] = stats;
  1231. }
  1232. catch (Exception ex)
  1233. {
  1234. result["success"] = false;
  1235. result["code"] = 1011;
  1236. result["message"] = $"获取统计信息异常: {ex.Message}";
  1237. result["exception"] = ex.GetType().Name;
  1238. }
  1239. return result;
  1240. }
  1241. /// <summary>
  1242. /// 系统健康检查
  1243. /// 全面检查系统状态和连接性
  1244. /// </summary>
  1245. public static JObject HealthCheck()
  1246. {
  1247. var result = new JObject();
  1248. var checks = new JObject();
  1249. try
  1250. {
  1251. // 1. 检查DLL文件
  1252. var dllCheck = CheckDllExists();
  1253. checks["dllStatus"] = new JObject
  1254. {
  1255. ["success"] = dllCheck["success"],
  1256. ["message"] = dllCheck["message"]
  1257. };
  1258. // 2. 检查初始化状态
  1259. checks["initStatus"] = new JObject
  1260. {
  1261. ["initialized"] = isInitialized,
  1262. ["hasConfig"] = currentConfig != null
  1263. };
  1264. // 3. 检查签到状态
  1265. checks["signInStatus"] = new JObject
  1266. {
  1267. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1268. ["signNo"] = currentSignNo,
  1269. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss")
  1270. };
  1271. // 4. 尝试调用系统函数(如果已初始化)
  1272. if (isInitialized)
  1273. {
  1274. var testResult = ProcessWorkInjuryTransaction("SignIn");
  1275. checks["connectionTest"] = new JObject
  1276. {
  1277. ["success"] = testResult["success"],
  1278. ["message"] = testResult["message"]
  1279. };
  1280. }
  1281. else
  1282. {
  1283. checks["connectionTest"] = new JObject
  1284. {
  1285. ["success"] = false,
  1286. ["message"] = "系统未初始化,无法测试连接"
  1287. };
  1288. }
  1289. // 5. 检查日志目录
  1290. if (currentConfig != null)
  1291. {
  1292. checks["logStatus"] = new JObject
  1293. {
  1294. ["pathExists"] = Directory.Exists(currentConfig.LogPath),
  1295. ["logPath"] = currentConfig.LogPath,
  1296. ["writable"] = true // 简化检查,实际可以尝试写入测试
  1297. };
  1298. }
  1299. // 综合评估健康状态
  1300. bool overallHealth = (bool)checks["dllStatus"]["success"] &&
  1301. (bool)checks["initStatus"]["initialized"];
  1302. result["success"] = true;
  1303. result["code"] = 200;
  1304. result["message"] = overallHealth ? "系统健康状态良好" : "系统存在问题";
  1305. result["data"] = new JObject
  1306. {
  1307. ["overallHealth"] = overallHealth,
  1308. ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1309. ["checks"] = checks
  1310. };
  1311. }
  1312. catch (Exception ex)
  1313. {
  1314. result["success"] = false;
  1315. result["code"] = 1012;
  1316. result["message"] = $"健康检查异常: {ex.Message}";
  1317. result["exception"] = ex.GetType().Name;
  1318. }
  1319. return result;
  1320. }
  1321. /// <summary>
  1322. /// 获取当前签到状态
  1323. /// </summary>
  1324. public static JObject GetSignInStatus()
  1325. {
  1326. var result = new JObject();
  1327. try
  1328. {
  1329. result["success"] = true;
  1330. result["code"] = 200;
  1331. result["message"] = "签到状态获取成功";
  1332. result["data"] = new JObject
  1333. {
  1334. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1335. ["signNo"] = currentSignNo,
  1336. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss"),
  1337. ["signInOperator"] = signInOperator,
  1338. ["sessionDuration"] = signInTime == DateTime.MinValue ? null :
  1339. ((int)(DateTime.Now - signInTime).TotalMinutes).ToString() + "分钟"
  1340. };
  1341. }
  1342. catch (Exception ex)
  1343. {
  1344. result["success"] = false;
  1345. result["code"] = 1013;
  1346. result["message"] = $"获取签到状态异常: {ex.Message}";
  1347. result["exception"] = ex.GetType().Name;
  1348. }
  1349. return result;
  1350. }
  1351. /// <summary>
  1352. /// 根据交易记录进行冲正操作
  1353. /// </summary>
  1354. public static JObject ReverseTransactionByRecord(string originalMessageId)
  1355. {
  1356. var result = new JObject();
  1357. try
  1358. {
  1359. if (!transactionRecords.ContainsKey(originalMessageId))
  1360. {
  1361. result["success"] = false;
  1362. result["code"] = 1014;
  1363. result["message"] = $"找不到原交易记录: {originalMessageId}";
  1364. return result;
  1365. }
  1366. var originalRecord = transactionRecords[originalMessageId];
  1367. var reverseParams = new
  1368. {
  1369. original_msg_id = originalMessageId,
  1370. original_transaction_code = originalRecord.TransactionCode,
  1371. original_transaction_time = originalRecord.TransactionTime.ToString("yyyyMMddHHmmss"),
  1372. reverse_reason = "系统冲正"
  1373. };
  1374. result = ProcessWorkInjuryTransaction("ReverseTransaction", reverseParams);
  1375. if ((bool)result["success"])
  1376. {
  1377. // 冲正成功后,可以选择移除原记录
  1378. // transactionRecords.Remove(originalMessageId);
  1379. LogInfo($"冲正交易成功,原交易ID: {originalMessageId}");
  1380. }
  1381. }
  1382. catch (Exception ex)
  1383. {
  1384. result["success"] = false;
  1385. result["code"] = 1015;
  1386. result["message"] = $"冲正交易异常: {ex.Message}";
  1387. result["exception"] = ex.GetType().Name;
  1388. }
  1389. return result;
  1390. }
  1391. #endregion
  1392. }
  1393. }