JiangSuWorkInjuryBusiness.cs 66 KB

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