JiangSuWorkInjuryBusiness.cs 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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. result["data"] = outputData["output"];
  677. result["transactionCode"] = transactionCode;
  678. result["infRefMsgId"] = outputData["inf_refmsgid"];
  679. result["refMsgTime"] = outputData["refmsg_time"];
  680. result["respondTime"] = outputData["respond_time"];
  681. result["warnMsg"] = warnMsg;
  682. }
  683. else
  684. {
  685. // 业务失败
  686. result["success"] = false;
  687. result["code"] = 3000 + Math.Abs(int.Parse(infcode));
  688. result["message"] = string.IsNullOrEmpty(errMsg) ? "交易失败" : errMsg;
  689. result["transactionCode"] = transactionCode;
  690. result["businessErrorCode"] = infcode;
  691. result["businessErrorMsg"] = errMsg;
  692. }
  693. // 保存完整的原始返回数据
  694. result["rawOutput"] = outputJson;
  695. }
  696. catch (JsonException jsonEx)
  697. {
  698. result["success"] = false;
  699. result["code"] = 2002;
  700. result["message"] = $"返回数据解析失败: {jsonEx.Message}";
  701. result["rawOutput"] = outputJson;
  702. }
  703. catch (Exception ex)
  704. {
  705. result["success"] = false;
  706. result["code"] = 2003;
  707. result["message"] = $"输出解析异常: {ex.Message}";
  708. result["exception"] = ex.GetType().Name;
  709. }
  710. return result;
  711. }
  712. /// <summary>
  713. /// 特殊交易后处理逻辑
  714. /// </summary>
  715. private static void PostProcessTransaction(string transactionCode, JObject result)
  716. {
  717. if ((bool)result["success"])
  718. {
  719. switch (transactionCode)
  720. {
  721. case "9001": // 签到交易成功
  722. var signData = result["data"];
  723. if (signData != null)
  724. {
  725. currentSignNo = signData["sign_no"]?.ToString() ?? "";
  726. // 从服务器返回数据中获取签到时间,格式:yyyyMMddHHmmss
  727. string signTimeStr = signData["sign_time"]?.ToString() ?? "";
  728. if (!string.IsNullOrEmpty(signTimeStr) && signTimeStr.Length == 14)
  729. {
  730. try
  731. {
  732. signInTime = DateTime.ParseExact(signTimeStr, "yyyyMMddHHmmss", null);
  733. }
  734. catch
  735. {
  736. // 如果解析失败,使用本地时间作为备选
  737. signInTime = DateTime.Now;
  738. LogError($"服务器返回的签到时间格式错误: {signTimeStr},使用本地时间");
  739. }
  740. }
  741. else
  742. {
  743. // 如果服务器没有返回签到时间,使用本地时间
  744. signInTime = DateTime.Now;
  745. LogInfo($"服务器未返回签到时间,使用本地时间: {signInTime:yyyy-MM-dd HH:mm:ss}");
  746. }
  747. signInOperator = currentConfig?.DefaultOperator ?? "";
  748. // 记录签到成功日志
  749. LogInfo($"签到成功,流水号: {currentSignNo}, 时间: {signInTime:yyyy-MM-dd HH:mm:ss}");
  750. }
  751. break;
  752. case "9002": // 签退交易成功
  753. // 清除签到状态
  754. currentSignNo = "";
  755. signInTime = DateTime.MinValue;
  756. signInOperator = "";
  757. // 记录签退时间,使用统一格式
  758. string signOutTimeStr = DateTime.Now.ToString("yyyyMMddHHmmss");
  759. LogInfo($"签退成功,时间: {signOutTimeStr}");
  760. break;
  761. }
  762. }
  763. }
  764. #endregion
  765. #region 辅助工具方法
  766. /// <summary>
  767. /// 获取交易编号
  768. /// 支持中文名称、英文名称和直接的数字编号
  769. /// </summary>
  770. private static string GetTransactionCode(string transactionName)
  771. {
  772. if (string.IsNullOrEmpty(transactionName))
  773. return "";
  774. // 如果直接是4位数字编号,直接返回
  775. if (transactionName.Length == 4 && transactionName.All(char.IsDigit))
  776. return transactionName;
  777. // 从映射表中查找
  778. if (TransactionMapping.ContainsKey(transactionName))
  779. return TransactionMapping[transactionName];
  780. // 支持中文名称映射
  781. var chineseMapping = new Dictionary<string, string>
  782. {
  783. {"签到", "9001"}, {"签退", "9002"},
  784. {"读卡", "1101"}, {"登记", "2201"}, {"结算", "2207"},
  785. {"撤销", "2208"}, {"冲正", "2209"}, {"预结算", "2206"},
  786. {"处方上报", "2204"}, {"处方撤销", "2205"},
  787. {"总额对账", "1320"}, {"明细对账", "1321"},
  788. {"批量下载", "1301"}
  789. };
  790. if (chineseMapping.ContainsKey(transactionName))
  791. return chineseMapping[transactionName];
  792. return "";
  793. }
  794. /// <summary>
  795. /// 生成唯一的发送方报文ID
  796. /// 格式:协议机构编号(6位) + 时间戳(14位) + 序列号(4位) = 24位
  797. /// </summary>
  798. private static string GenerateMessageId()
  799. {
  800. lock (sequenceLock)
  801. {
  802. string institutionCode = currentConfig?.FixmedinsCode ?? "SQ201348";
  803. if (institutionCode.Length > 6)
  804. institutionCode = institutionCode.Substring(0, 6);
  805. else
  806. institutionCode = institutionCode.PadRight(6, '0');
  807. string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
  808. sequenceCounter = (sequenceCounter + 1) % 10000; // 保持4位数字
  809. string sequence = sequenceCounter.ToString("D4");
  810. return institutionCode + timestamp + sequence;
  811. }
  812. }
  813. /// <summary>
  814. /// 保存发送方报文ID用于冲正交易
  815. /// </summary>
  816. private static void SaveMessageId(string msgId, string transactionCode)
  817. {
  818. var record = new TransactionRecord
  819. {
  820. MessageId = msgId,
  821. TransactionCode = transactionCode,
  822. TransactionTime = DateTime.Now,
  823. OperatorId = currentConfig?.DefaultOperator ?? ""
  824. };
  825. transactionRecords[msgId] = record;
  826. // 清理过期记录(7天前的)
  827. var expireTime = DateTime.Now.AddDays(-7);
  828. var expiredKeys = transactionRecords
  829. .Where(kv => kv.Value.TransactionTime < expireTime)
  830. .Select(kv => kv.Key)
  831. .ToList();
  832. foreach (var key in expiredKeys)
  833. {
  834. transactionRecords.Remove(key);
  835. }
  836. }
  837. /// <summary>
  838. /// 确保DLL文件在正确位置(参考医保代码的成功实现)
  839. /// </summary>
  840. private static JObject CheckDllExists()
  841. {
  842. var result = new JObject();
  843. try
  844. {
  845. string programDir = AppDomain.CurrentDomain.BaseDirectory;
  846. string targetDllPath = Path.Combine(programDir, "JSSiInterface.dll");
  847. // 如果目标位置已经有DLL文件,直接返回成功
  848. if (File.Exists(targetDllPath))
  849. {
  850. FileInfo fileInfo = new FileInfo(targetDllPath);
  851. result["success"] = true;
  852. result["code"] = 200;
  853. result["message"] = "JSSiInterface.dll文件检查通过";
  854. result["device"] = "江苏工伤联网接口";
  855. result["data"] = new JObject
  856. {
  857. ["dllPath"] = targetDllPath,
  858. ["fileSize"] = fileInfo.Length,
  859. ["lastModified"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
  860. ["programDirectory"] = programDir
  861. };
  862. return result;
  863. }
  864. // 如果目标位置没有DLL,尝试从其他位置查找并复制(参考医保代码)
  865. string[] possiblePaths = {
  866. Path.Combine(programDir, "bin", "x86", "Release", "JSSiInterface.dll"),
  867. Path.Combine(programDir, "bin", "Debug", "JSSiInterface.dll"),
  868. Path.Combine(programDir, "bin", "Release", "JSSiInterface.dll"),
  869. Path.Combine(programDir, "ThCardReader", "bin", "x86", "Release", "JSSiInterface.dll"),
  870. Path.Combine(programDir, "ThCardReader", "bin", "Debug", "JSSiInterface.dll"),
  871. Path.Combine(programDir, "..", "ThCardReader", "bin", "x86", "Release", "JSSiInterface.dll")
  872. };
  873. string sourcePath = null;
  874. foreach (string path in possiblePaths)
  875. {
  876. if (File.Exists(path))
  877. {
  878. sourcePath = path;
  879. break;
  880. }
  881. }
  882. if (sourcePath != null)
  883. {
  884. // 复制DLL文件到程序目录
  885. File.Copy(sourcePath, targetDllPath, true);
  886. FileInfo fileInfo = new FileInfo(targetDllPath);
  887. result["success"] = true;
  888. result["code"] = 200;
  889. result["message"] = "JSSiInterface.dll文件已复制到位";
  890. result["device"] = "江苏工伤联网接口";
  891. result["data"] = new JObject
  892. {
  893. ["sourcePath"] = sourcePath,
  894. ["targetPath"] = targetDllPath,
  895. ["fileSize"] = fileInfo.Length,
  896. ["lastModified"] = fileInfo.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss")
  897. };
  898. }
  899. else
  900. {
  901. result["success"] = false;
  902. result["code"] = 8001;
  903. result["message"] = "找不到JSSiInterface.dll文件";
  904. result["device"] = "江苏工伤联网接口";
  905. result["data"] = new JObject
  906. {
  907. ["searchedPaths"] = string.Join("; ", possiblePaths),
  908. ["programDirectory"] = programDir,
  909. ["suggestion"] = "请确保JSSiInterface.dll文件在程序目录或bin/x86/Release目录中"
  910. };
  911. }
  912. }
  913. catch (Exception ex)
  914. {
  915. result["success"] = false;
  916. result["code"] = 8002;
  917. result["message"] = $"DLL文件检查异常: {ex.Message}";
  918. result["device"] = "江苏工伤联网接口";
  919. result["exception"] = ex.GetType().Name;
  920. }
  921. return result;
  922. }
  923. /// <summary>
  924. /// 记录信息日志
  925. /// </summary>
  926. private static void LogInfo(string message)
  927. {
  928. try
  929. {
  930. if (currentConfig != null)
  931. {
  932. string logPath = Path.Combine(currentConfig.LogPath, $"workinjury_{DateTime.Now:yyyyMMdd}.log");
  933. string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [INFO] {message}{Environment.NewLine}";
  934. File.AppendAllText(logPath, logEntry);
  935. }
  936. }
  937. catch
  938. {
  939. // 日志记录失败不影响主要业务
  940. }
  941. }
  942. /// <summary>
  943. /// 记录错误日志
  944. /// </summary>
  945. private static void LogError(string message)
  946. {
  947. try
  948. {
  949. if (currentConfig != null)
  950. {
  951. string logPath = Path.Combine(currentConfig.LogPath, $"workinjury_{DateTime.Now:yyyyMMdd}.log");
  952. string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [ERROR] {message}{Environment.NewLine}";
  953. File.AppendAllText(logPath, logEntry);
  954. }
  955. }
  956. catch
  957. {
  958. // 日志记录失败不影响主要业务
  959. }
  960. }
  961. #endregion
  962. #region 便民方法集合 - 按照设计文档要求
  963. /// <summary>
  964. /// 批量上传处方明细
  965. /// 自动处理大量处方的分批上传(每批最多50条)
  966. /// </summary>
  967. public static JObject BatchUploadPrescriptions(object[] prescriptions, string patientId = "", string visitNo = "")
  968. {
  969. var result = new JObject();
  970. var results = new JArray();
  971. try
  972. {
  973. if (prescriptions == null || prescriptions.Length == 0)
  974. {
  975. result["success"] = false;
  976. result["code"] = 1006;
  977. result["message"] = "处方明细不能为空";
  978. return result;
  979. }
  980. // 分批处理(每批50条)
  981. const int batchSize = 50;
  982. int totalBatches = (int)Math.Ceiling((double)prescriptions.Length / batchSize);
  983. int successCount = 0;
  984. int failureCount = 0;
  985. for (int i = 0; i < totalBatches; i++)
  986. {
  987. var batch = prescriptions.Skip(i * batchSize).Take(batchSize).ToArray();
  988. var batchParams = new
  989. {
  990. patient_id = patientId,
  991. visit_no = visitNo,
  992. batch_no = (i + 1).ToString(),
  993. prescriptions = batch
  994. };
  995. var batchResult = ProcessWorkInjuryTransaction("UploadPrescription", batchParams);
  996. if ((bool)batchResult["success"])
  997. {
  998. successCount++;
  999. }
  1000. else
  1001. {
  1002. failureCount++;
  1003. }
  1004. results.Add(new JObject
  1005. {
  1006. ["batchNo"] = i + 1,
  1007. ["itemCount"] = batch.Length,
  1008. ["success"] = batchResult["success"],
  1009. ["message"] = batchResult["message"],
  1010. ["code"] = batchResult["code"]
  1011. });
  1012. }
  1013. result["success"] = failureCount == 0;
  1014. result["code"] = failureCount == 0 ? 200 : 1007;
  1015. result["message"] = $"批量上传完成,成功{successCount}批,失败{failureCount}批";
  1016. result["data"] = new JObject
  1017. {
  1018. ["totalBatches"] = totalBatches,
  1019. ["totalItems"] = prescriptions.Length,
  1020. ["successCount"] = successCount,
  1021. ["failureCount"] = failureCount,
  1022. ["batchResults"] = results
  1023. };
  1024. }
  1025. catch (Exception ex)
  1026. {
  1027. result["success"] = false;
  1028. result["code"] = 1008;
  1029. result["message"] = $"批量上传异常: {ex.Message}";
  1030. result["exception"] = ex.GetType().Name;
  1031. }
  1032. return result;
  1033. }
  1034. /// <summary>
  1035. /// 完整的工伤就医流程
  1036. /// 自动完成:读卡 -> 登记 -> 预结算 -> 结算 的完整流程
  1037. /// </summary>
  1038. public static JObject CompleteWorkInjuryProcess(object patientInfo = null, object[] feeDetails = null)
  1039. {
  1040. var result = new JObject();
  1041. var processSteps = new JArray();
  1042. try
  1043. {
  1044. // 第1步:读卡
  1045. var readCardResult = ProcessWorkInjuryTransaction("ReadCard");
  1046. processSteps.Add(new JObject
  1047. {
  1048. ["step"] = 1,
  1049. ["name"] = "读卡",
  1050. ["success"] = readCardResult["success"],
  1051. ["message"] = readCardResult["message"],
  1052. ["data"] = readCardResult["data"]
  1053. });
  1054. if (!(bool)readCardResult["success"])
  1055. {
  1056. result["success"] = false;
  1057. result["message"] = "读卡失败,流程终止";
  1058. result["processSteps"] = processSteps;
  1059. return result;
  1060. }
  1061. // 第2步:登记
  1062. var registerParams = patientInfo ?? new
  1063. {
  1064. visit_type = "1", // 门诊
  1065. dept_code = "001",
  1066. dept_name = "内科",
  1067. doctor_code = "DOC001",
  1068. doctor_name = "张医生"
  1069. };
  1070. var registerResult = ProcessWorkInjuryTransaction("RegisterPatient", registerParams);
  1071. processSteps.Add(new JObject
  1072. {
  1073. ["step"] = 2,
  1074. ["name"] = "登记",
  1075. ["success"] = registerResult["success"],
  1076. ["message"] = registerResult["message"],
  1077. ["data"] = registerResult["data"]
  1078. });
  1079. if (!(bool)registerResult["success"])
  1080. {
  1081. result["success"] = false;
  1082. result["message"] = "登记失败,流程终止";
  1083. result["processSteps"] = processSteps;
  1084. return result;
  1085. }
  1086. // 如果有费用明细,进行预结算和结算
  1087. if (feeDetails != null && feeDetails.Length > 0)
  1088. {
  1089. // 第3步:预结算
  1090. var preSettleParams = new
  1091. {
  1092. visit_no = registerResult["data"]?["visit_no"]?.ToString() ?? "",
  1093. fee_details = feeDetails
  1094. };
  1095. var preSettleResult = ProcessWorkInjuryTransaction("PreSettle", preSettleParams);
  1096. processSteps.Add(new JObject
  1097. {
  1098. ["step"] = 3,
  1099. ["name"] = "预结算",
  1100. ["success"] = preSettleResult["success"],
  1101. ["message"] = preSettleResult["message"],
  1102. ["data"] = preSettleResult["data"]
  1103. });
  1104. if ((bool)preSettleResult["success"])
  1105. {
  1106. // 第4步:正式结算
  1107. var settleParams = new
  1108. {
  1109. visit_no = registerResult["data"]?["visit_no"]?.ToString() ?? "",
  1110. pre_settle_id = preSettleResult["data"]?["pre_settle_id"]?.ToString() ?? ""
  1111. };
  1112. var settleResult = ProcessWorkInjuryTransaction("Settle", settleParams);
  1113. processSteps.Add(new JObject
  1114. {
  1115. ["step"] = 4,
  1116. ["name"] = "结算",
  1117. ["success"] = settleResult["success"],
  1118. ["message"] = settleResult["message"],
  1119. ["data"] = settleResult["data"]
  1120. });
  1121. }
  1122. }
  1123. result["success"] = true;
  1124. result["code"] = 200;
  1125. result["message"] = "工伤就医流程完成";
  1126. result["processSteps"] = processSteps;
  1127. }
  1128. catch (Exception ex)
  1129. {
  1130. result["success"] = false;
  1131. result["code"] = 1009;
  1132. result["message"] = $"工伤就医流程异常: {ex.Message}";
  1133. result["exception"] = ex.GetType().Name;
  1134. result["processSteps"] = processSteps;
  1135. }
  1136. return result;
  1137. }
  1138. /// <summary>
  1139. /// 智能重试交易
  1140. /// 自动重试失败的交易,使用指数退避算法
  1141. /// </summary>
  1142. public static JObject SmartRetryTransaction(string transactionName, object businessParams = null,
  1143. int maxRetries = 3, int baseDelayMs = 1000)
  1144. {
  1145. var result = new JObject();
  1146. var retryAttempts = new JArray();
  1147. for (int attempt = 1; attempt <= maxRetries; attempt++)
  1148. {
  1149. var attemptResult = ProcessWorkInjuryTransaction(transactionName, businessParams);
  1150. retryAttempts.Add(new JObject
  1151. {
  1152. ["attempt"] = attempt,
  1153. ["success"] = attemptResult["success"],
  1154. ["message"] = attemptResult["message"],
  1155. ["code"] = attemptResult["code"],
  1156. ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")
  1157. });
  1158. if ((bool)attemptResult["success"])
  1159. {
  1160. result = attemptResult; // 成功时返回最后一次的结果
  1161. result["retryInfo"] = new JObject
  1162. {
  1163. ["totalAttempts"] = attempt,
  1164. ["success"] = true,
  1165. ["retryAttempts"] = retryAttempts
  1166. };
  1167. return result;
  1168. }
  1169. // 如果不是最后一次尝试,等待后重试
  1170. if (attempt < maxRetries)
  1171. {
  1172. int delay = baseDelayMs * (int)Math.Pow(2, attempt - 1); // 指数退避
  1173. Thread.Sleep(delay);
  1174. }
  1175. }
  1176. // 所有重试都失败了
  1177. result["success"] = false;
  1178. result["code"] = 1010;
  1179. result["message"] = $"交易{transactionName}经过{maxRetries}次重试后仍然失败";
  1180. result["retryInfo"] = new JObject
  1181. {
  1182. ["totalAttempts"] = maxRetries,
  1183. ["success"] = false,
  1184. ["retryAttempts"] = retryAttempts
  1185. };
  1186. return result;
  1187. }
  1188. /// <summary>
  1189. /// 获取交易统计信息
  1190. /// 提供系统性能和健康状况监控
  1191. /// </summary>
  1192. public static JObject GetTransactionStatistics()
  1193. {
  1194. var result = new JObject();
  1195. try
  1196. {
  1197. var stats = new JObject
  1198. {
  1199. ["currentTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1200. ["systemStatus"] = new JObject
  1201. {
  1202. ["initialized"] = isInitialized,
  1203. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1204. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss"),
  1205. ["currentSignNo"] = currentSignNo,
  1206. ["signInOperator"] = signInOperator
  1207. },
  1208. ["transactionRecords"] = new JObject
  1209. {
  1210. ["totalCount"] = transactionRecords.Count,
  1211. ["oldestRecord"] = transactionRecords.Count > 0 ?
  1212. transactionRecords.Values.Min(r => r.TransactionTime).ToString("yyyy-MM-dd HH:mm:ss") : null,
  1213. ["newestRecord"] = transactionRecords.Count > 0 ?
  1214. transactionRecords.Values.Max(r => r.TransactionTime).ToString("yyyy-MM-dd HH:mm:ss") : null
  1215. },
  1216. ["configuration"] = currentConfig != null ? new JObject
  1217. {
  1218. ["fixmedinsCode"] = currentConfig.FixmedinsCode,
  1219. ["fixmedinsName"] = currentConfig.FixmedinsName,
  1220. ["interfaceVersion"] = currentConfig.InterfaceVersion,
  1221. ["logPath"] = currentConfig.LogPath
  1222. } : null
  1223. };
  1224. result["success"] = true;
  1225. result["code"] = 200;
  1226. result["message"] = "统计信息获取成功";
  1227. result["data"] = stats;
  1228. }
  1229. catch (Exception ex)
  1230. {
  1231. result["success"] = false;
  1232. result["code"] = 1011;
  1233. result["message"] = $"获取统计信息异常: {ex.Message}";
  1234. result["exception"] = ex.GetType().Name;
  1235. }
  1236. return result;
  1237. }
  1238. /// <summary>
  1239. /// 系统健康检查
  1240. /// 全面检查系统状态和连接性
  1241. /// </summary>
  1242. public static JObject HealthCheck()
  1243. {
  1244. var result = new JObject();
  1245. var checks = new JObject();
  1246. try
  1247. {
  1248. // 1. 检查DLL文件
  1249. var dllCheck = CheckDllExists();
  1250. checks["dllStatus"] = new JObject
  1251. {
  1252. ["success"] = dllCheck["success"],
  1253. ["message"] = dllCheck["message"]
  1254. };
  1255. // 2. 检查初始化状态
  1256. checks["initStatus"] = new JObject
  1257. {
  1258. ["initialized"] = isInitialized,
  1259. ["hasConfig"] = currentConfig != null
  1260. };
  1261. // 3. 检查签到状态
  1262. checks["signInStatus"] = new JObject
  1263. {
  1264. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1265. ["signNo"] = currentSignNo,
  1266. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss")
  1267. };
  1268. // 4. 尝试调用系统函数(如果已初始化)
  1269. if (isInitialized)
  1270. {
  1271. var testResult = ProcessWorkInjuryTransaction("SignIn");
  1272. checks["connectionTest"] = new JObject
  1273. {
  1274. ["success"] = testResult["success"],
  1275. ["message"] = testResult["message"]
  1276. };
  1277. }
  1278. else
  1279. {
  1280. checks["connectionTest"] = new JObject
  1281. {
  1282. ["success"] = false,
  1283. ["message"] = "系统未初始化,无法测试连接"
  1284. };
  1285. }
  1286. // 5. 检查日志目录
  1287. if (currentConfig != null)
  1288. {
  1289. checks["logStatus"] = new JObject
  1290. {
  1291. ["pathExists"] = Directory.Exists(currentConfig.LogPath),
  1292. ["logPath"] = currentConfig.LogPath,
  1293. ["writable"] = true // 简化检查,实际可以尝试写入测试
  1294. };
  1295. }
  1296. // 综合评估健康状态
  1297. bool overallHealth = (bool)checks["dllStatus"]["success"] &&
  1298. (bool)checks["initStatus"]["initialized"];
  1299. result["success"] = true;
  1300. result["code"] = 200;
  1301. result["message"] = overallHealth ? "系统健康状态良好" : "系统存在问题";
  1302. result["data"] = new JObject
  1303. {
  1304. ["overallHealth"] = overallHealth,
  1305. ["timestamp"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
  1306. ["checks"] = checks
  1307. };
  1308. }
  1309. catch (Exception ex)
  1310. {
  1311. result["success"] = false;
  1312. result["code"] = 1012;
  1313. result["message"] = $"健康检查异常: {ex.Message}";
  1314. result["exception"] = ex.GetType().Name;
  1315. }
  1316. return result;
  1317. }
  1318. /// <summary>
  1319. /// 获取当前签到状态
  1320. /// </summary>
  1321. public static JObject GetSignInStatus()
  1322. {
  1323. var result = new JObject();
  1324. try
  1325. {
  1326. result["success"] = true;
  1327. result["code"] = 200;
  1328. result["message"] = "签到状态获取成功";
  1329. result["data"] = new JObject
  1330. {
  1331. ["signedIn"] = !string.IsNullOrEmpty(currentSignNo),
  1332. ["signNo"] = currentSignNo,
  1333. ["signInTime"] = signInTime == DateTime.MinValue ? null : signInTime.ToString("yyyy-MM-dd HH:mm:ss"),
  1334. ["signInOperator"] = signInOperator,
  1335. ["sessionDuration"] = signInTime == DateTime.MinValue ? null :
  1336. ((int)(DateTime.Now - signInTime).TotalMinutes).ToString() + "分钟"
  1337. };
  1338. }
  1339. catch (Exception ex)
  1340. {
  1341. result["success"] = false;
  1342. result["code"] = 1013;
  1343. result["message"] = $"获取签到状态异常: {ex.Message}";
  1344. result["exception"] = ex.GetType().Name;
  1345. }
  1346. return result;
  1347. }
  1348. /// <summary>
  1349. /// 根据交易记录进行冲正操作
  1350. /// </summary>
  1351. public static JObject ReverseTransactionByRecord(string originalMessageId)
  1352. {
  1353. var result = new JObject();
  1354. try
  1355. {
  1356. if (!transactionRecords.ContainsKey(originalMessageId))
  1357. {
  1358. result["success"] = false;
  1359. result["code"] = 1014;
  1360. result["message"] = $"找不到原交易记录: {originalMessageId}";
  1361. return result;
  1362. }
  1363. var originalRecord = transactionRecords[originalMessageId];
  1364. var reverseParams = new
  1365. {
  1366. original_msg_id = originalMessageId,
  1367. original_transaction_code = originalRecord.TransactionCode,
  1368. original_transaction_time = originalRecord.TransactionTime.ToString("yyyyMMddHHmmss"),
  1369. reverse_reason = "系统冲正"
  1370. };
  1371. result = ProcessWorkInjuryTransaction("ReverseTransaction", reverseParams);
  1372. if ((bool)result["success"])
  1373. {
  1374. // 冲正成功后,可以选择移除原记录
  1375. // transactionRecords.Remove(originalMessageId);
  1376. LogInfo($"冲正交易成功,原交易ID: {originalMessageId}");
  1377. }
  1378. }
  1379. catch (Exception ex)
  1380. {
  1381. result["success"] = false;
  1382. result["code"] = 1015;
  1383. result["message"] = $"冲正交易异常: {ex.Message}";
  1384. result["exception"] = ex.GetType().Name;
  1385. }
  1386. return result;
  1387. }
  1388. #endregion
  1389. }
  1390. }