You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

570 lines
23 KiB

3 weeks ago
  1. using Dapper;
  2. using Microsoft.Extensions.Configuration;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Converters;
  5. using Npgsql;
  6. using Shentun.Peis.ImportLisResults;
  7. using Shentun.Peis.ImportPacsResults;
  8. using Shentun.Peis.PlugIns.Extensions.ChargeRequests.YinHai;
  9. using Shentun.Peis.PlugIns.Extensions.ChargeRequests.YinHai.FeeBacks;
  10. using Shentun.Peis.PlugIns.Extensions.ImportLisResults.YinHai;
  11. using Shentun.Peis.PlugIns.Extensions.ImportLisResults.YinHai.ResultCalls;
  12. using Shentun.Peis.PlugIns.Extensions.ImportPacsResults.YinHai.ResultCalls;
  13. using Shentun.Peis.PlugIns.Extensions.LisRequests.YinHai;
  14. using Shentun.Peis.PlugIns.PatientRegisters;
  15. using Shentun.Peis.ThirdInterfaces;
  16. using Shentun.Utilities;
  17. using System;
  18. using System.Collections.Generic;
  19. using System.Data.Common;
  20. using System.IdentityModel.Tokens.Jwt;
  21. using System.Linq;
  22. using System.Net.Http.Headers;
  23. using System.Text;
  24. using System.Threading.Tasks;
  25. using System.Xml;
  26. namespace Shentun.Peis.PlugIns.Extensions.ImportPacsResults.YinHai
  27. {
  28. public class ImportPacsResultPlugInsYinHai
  29. {
  30. protected IConfiguration? AppConfig;
  31. private readonly string AppConnctionStr;
  32. private readonly IConfiguration? InterfaceConfig;
  33. private readonly ThirdInterfaceDto? _thirdInterfaceDto;
  34. private readonly PluginLogger _logger; // 添加日志实例
  35. private string? _appBaseAddress;
  36. private static string? _accesToken;
  37. protected string? AppUser;
  38. protected string? AppPassword;
  39. static ImportPacsResultPlugInsYinHai()
  40. {
  41. Dapper.DefaultTypeMap.MatchNamesWithUnderscores = true;
  42. }
  43. public ImportPacsResultPlugInsYinHai(Guid thirdInterfaceId)
  44. {
  45. _logger = new PluginLogger();
  46. AppConfig = new ConfigurationBuilder()
  47. .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录
  48. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  49. .Build();
  50. AppConnctionStr = AppConfig.GetSection("ConnectionStrings")
  51. .GetSection("Default").Value;
  52. using (DbConnection conn = new NpgsqlConnection(AppConnctionStr))
  53. {
  54. string sql;
  55. sql = @"
  56. SELECT *
  57. from third_interface
  58. where id =@ThirdInterfaceId
  59. ";
  60. _thirdInterfaceDto = (conn.Query<ThirdInterfaceDto>(sql,
  61. new { ThirdInterfaceId = thirdInterfaceId })).Single();
  62. }
  63. var configurationBuilder = new ConfigurationBuilder()
  64. .AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(_thirdInterfaceDto.ParmValue)));
  65. InterfaceConfig = configurationBuilder.Build();
  66. _appBaseAddress = AppConfig.GetSection("App")
  67. .GetSection("SelfUrl").Value;
  68. AppUser = AppConfig.GetSection("App")
  69. .GetSection("SelfUser").Value;
  70. AppPassword = AppConfig.GetSection("App")
  71. .GetSection("SelfPassword").Value;
  72. }
  73. public ImportPacsResultPlugInsYinHai(string parmValue)
  74. {
  75. _logger = new PluginLogger();
  76. AppConfig = new ConfigurationBuilder()
  77. .SetBasePath(DirectoryHelper.GetAppDirectory()) // 设置基础路径为当前目录
  78. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  79. .Build();
  80. AppConnctionStr = AppConfig.GetSection("ConnectionStrings")
  81. .GetSection("Default").Value;
  82. var configurationBuilder = new ConfigurationBuilder()
  83. .AddJsonStream(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(parmValue)));
  84. InterfaceConfig = configurationBuilder.Build();
  85. _appBaseAddress = AppConfig.GetSection("App")
  86. .GetSection("SelfUrl").Value;
  87. AppUser = AppConfig.GetSection("App")
  88. .GetSection("SelfUser").Value;
  89. AppPassword = AppConfig.GetSection("App")
  90. .GetSection("SelfPassword").Value;
  91. }
  92. /// <summary>
  93. /// 接收Pacs检查结果
  94. /// </summary>
  95. /// <param name="input"></param>
  96. /// <returns></returns>
  97. /// <exception cref="Exception"></exception>
  98. public async Task<CallBussinessResponseDetailDto> SendResultRequestAsync(InferfaceXmlDataDto input)
  99. {
  100. var res = new CallBussinessResponseDetailDto
  101. {
  102. msg = "失败",
  103. status_code = "-1"
  104. };
  105. #region 解析xml
  106. var pacsResultCallRequestData = GetPacsResultCallRequestData(input.message);
  107. #endregion
  108. _logger.LogResult("银海接收pacs检查结果", $"请求数据:{input.message}");
  109. try
  110. {
  111. var execDoctorUser = InterfaceConfig.GetValue("Interface:ExecDoctorUser", "");
  112. // var commonTableTypeId = InterfaceConfig.GetValue("Interface:CommonTableTypeId", "");
  113. var execOrganizationUnitId = InterfaceConfig.GetValue("Interface:ExecOrganizationUnitId", "");
  114. var checkDoctorName = InterfaceConfig.GetValue("Interface:CheckDoctorName", "");
  115. string actionName = "result_call";
  116. string codeName = "pacs_server";
  117. var bodyData = pacsResultCallRequestData.body.data.request_details;
  118. if (bodyData.detail.Any())
  119. {
  120. foreach (var item in bodyData.detail)
  121. {
  122. var createImportPacsResultDto = new CreateImportPacsResultDto()
  123. {
  124. CheckRequestNo = item.request_no,
  125. PatientName = GetPatientNameByCheckRequsetNo(item.request_no).GetAwaiter().GetResult(),
  126. Result = item.diag_result,
  127. Summary = item.diag_result,
  128. Suggestion = item.diag_suggest,
  129. //CheckDate = checkDate,
  130. CheckDoctorName = checkDoctorName,
  131. Files = new List<CreateImportPacsResultPictureDto>()
  132. {
  133. new CreateImportPacsResultPictureDto()
  134. {
  135. IsPrint = 'Y',
  136. FileTransMode = "1",//0-json,1-url
  137. FileName = item.image_address,
  138. FileFormat = "0",//0-图片,1-pdf
  139. FileUrl = item.image_address
  140. //FileBase64 = Shentun.Utilities.FileHelper.ToBase64(firstData.reportUrl)
  141. }
  142. }
  143. };
  144. var callResult = await CallAppServiceAsync<CreateImportPacsResultDto, object>("api/app/ImportPacsResult/ImportResult", createImportPacsResultDto);
  145. _logger.LogResult("银海接收pacs检查结果", $"处理成功,pacs申请单号【{item.request_no}】");
  146. var yinHaiSendInterfaceLogDto = new YinHaiSendInterfaceLogDto
  147. {
  148. LogName = "接收pacs检查结果",
  149. ExecDoctorUser = Guid.Parse(execDoctorUser),
  150. InterfaceName = $"{codeName}_{actionName}",
  151. ParaValue = input.message,
  152. RequestNo = item.request_no,
  153. ReturnParaValue = ""
  154. };
  155. await AddSendLog(yinHaiSendInterfaceLogDto);
  156. }
  157. }
  158. else
  159. {
  160. throw new Exception("无结果数据");
  161. }
  162. res = new CallBussinessResponseDetailDto
  163. {
  164. status_code = "1",
  165. msg = "成功"
  166. };
  167. }
  168. catch (Exception ex)
  169. {
  170. _logger.LogResult("银海接收pacs检查结果", ex, $"接收pacs检查结果异常");
  171. }
  172. return res;
  173. }
  174. /// <summary>
  175. /// 根据检查单号获取病人姓名
  176. /// </summary>
  177. /// <param name="checkRequestNo"></param>
  178. /// <returns></returns>
  179. private async Task<string> GetPatientNameByCheckRequsetNo(string checkRequestNo)
  180. {
  181. string msg = "";
  182. using (DbConnection conn = new NpgsqlConnection(AppConnctionStr))
  183. {
  184. string sql;
  185. sql = $@"select a.patient_name from patient_register as a
  186. left join register_check as b on a.id=b.patient_register_id
  187. where b.check_request_no=@checkRequestNo ";
  188. msg = await conn.QueryFirstOrDefaultAsync<string>(sql, new
  189. {
  190. checkRequestNo = checkRequestNo
  191. });
  192. }
  193. return msg;
  194. }
  195. /// <summary>
  196. /// 添加日志
  197. /// </summary>
  198. /// <param name="input"></param>
  199. /// <returns></returns>
  200. private async Task AddSendLog(YinHaiSendInterfaceLogDto input)
  201. {
  202. using (DbConnection conn = new NpgsqlConnection(AppConnctionStr))
  203. {
  204. string sql;
  205. sql = $@" insert into interface_send_log (id,log_name,request_no,interface_name,para_value,return_para_value,concurrency_stamp,
  206. creation_time,creator_id,last_modification_time,last_modifier_id) values
  207. (@id,@log_name,@request_no,@interface_name,@para_value,@return_para_value,@concurrency_stamp,
  208. @creation_time,@creator_id,@last_modification_time,@last_modifier_id)
  209. ";
  210. await conn.ExecuteAsync(sql,
  211. new
  212. {
  213. id = Guid.NewGuid(),
  214. log_name = input.LogName,
  215. request_no = input.RequestNo,
  216. interface_name = input.InterfaceName,
  217. para_value = input.ParaValue,
  218. return_para_value = input.ReturnParaValue,
  219. concurrency_stamp = Guid.NewGuid().ToString("N"),
  220. creation_time = DateTime.Now,
  221. creator_id = input.ExecDoctorUser,
  222. last_modification_time = DateTime.Now,
  223. last_modifier_id = input.ExecDoctorUser
  224. });
  225. }
  226. }
  227. #region 解析xml
  228. private PacsResultCallRequestDto GetPacsResultCallRequestData(string message)
  229. {
  230. try
  231. {
  232. var doc = new XmlDocument();
  233. doc.LoadXml(message);
  234. var request = new PacsResultCallRequestDto();
  235. var root = doc.DocumentElement;
  236. if (root == null) return null;
  237. // 解析 head
  238. var headNode = root.SelectSingleNode("head");
  239. if (headNode != null)
  240. {
  241. request.head = new CallBussinessRequestHeadDto
  242. {
  243. version = GetNodeValue(headNode, "version"),
  244. timestamp = GetNodeValue(headNode, "timestamp"),
  245. sign = GetNodeValue(headNode, "sign"),
  246. request_id = GetNodeValue(headNode, "request_id"),
  247. source_system = GetNodeValue(headNode, "source_system"),
  248. object_system = GetNodeValue(headNode, "object_system"),
  249. action = GetNodeValue(headNode, "action"),
  250. code = GetNodeValue(headNode, "code")
  251. };
  252. }
  253. // 解析 body
  254. var bodyNode = root.SelectSingleNode("body");
  255. if (bodyNode != null)
  256. {
  257. request.body = new PacsResultCallRequestBodyDto();
  258. var dataNode = bodyNode.SelectSingleNode("data");
  259. if (dataNode != null)
  260. {
  261. request.body.data = new PacsResultCallRequestBodyDataDto();
  262. var requestDetailsNode = dataNode.SelectSingleNode("request_details");
  263. if (requestDetailsNode != null)
  264. {
  265. // 创建 detail 列表
  266. request.body.data.request_details = new PacsResultCallRequestBodyDataRequestDetails
  267. {
  268. detail = new List<PacsResultCallRequestBodyDataRequestDetail>()
  269. };
  270. // 获取所有 detail 节点
  271. var detailNodes = requestDetailsNode.SelectNodes("detail");
  272. if (detailNodes != null)
  273. {
  274. foreach (XmlNode detailNode in detailNodes)
  275. {
  276. var detail = new PacsResultCallRequestBodyDataRequestDetail
  277. {
  278. hos_id = GetNodeValue(detailNode, "hos_id"),
  279. request_no = GetNodeValue(detailNode, "request_no"),
  280. patient_type = GetNodeValue(detailNode, "patient_type"),
  281. report_serial_no = GetNodeValue(detailNode, "report_serial_no"),
  282. org_code = GetNodeValue(detailNode, "org_code"),
  283. system_source = GetNodeValue(detailNode, "system_source"),
  284. org_name = GetNodeValue(detailNode, "org_name"),
  285. patient_id = GetNodeValue(detailNode, "patient_id"),
  286. visit_id = GetNodeValue(detailNode, "visit_id"),
  287. order_id = GetNodeValue(detailNode, "order_id"),
  288. remark = GetNodeValue(detailNode, "remark"),
  289. check_no = GetNodeValue(detailNode, "check_no"),
  290. conform_reality = GetNodeValue(detailNode, "conform_reality"),
  291. diag_result = GetNodeValue(detailNode, "diag_result"),
  292. diag_suggest = GetNodeValue(detailNode, "diag_suggest"),
  293. image_address = GetNodeValue(detailNode, "image_address"),
  294. image_generation_time = GetNodeValue(detailNode, "image_generation_time"),
  295. image_report_index = GetNodeValue(detailNode, "image_report_index"),
  296. item_serial_no = GetNodeValue(detailNode, "item_serial_no"),
  297. positive_flag = GetNodeValue(detailNode, "positive_flag"),
  298. report_quality = GetNodeValue(detailNode, "report_quality"),
  299. study_uuid = GetNodeValue(detailNode, "study_uuid")
  300. };
  301. request.body.data.request_details.detail.Add(detail);
  302. }
  303. }
  304. }
  305. }
  306. }
  307. return request;
  308. }
  309. catch (Exception ex)
  310. {
  311. //_logger.LogError(ex, "解析 XML 失败");
  312. return null;
  313. }
  314. }
  315. private string GetNodeValue(XmlNode parent, string nodeName)
  316. {
  317. var node = parent.SelectSingleNode(nodeName);
  318. return node?.InnerText ?? "";
  319. }
  320. #endregion
  321. /// <summary>
  322. /// 发起api请求
  323. /// </summary>
  324. /// <typeparam name="TInput"></typeparam>
  325. /// <typeparam name="TOut"></typeparam>
  326. /// <param name="url"></param>
  327. /// <param name="data"></param>
  328. /// <param name="method"></param>
  329. /// <returns></returns>
  330. /// <exception cref="Exception"></exception>
  331. private async Task<TOut> CallAppServiceAsync<TInput, TOut>(string url, TInput data, string method = "post")
  332. {
  333. if (string.IsNullOrWhiteSpace(_appBaseAddress))
  334. {
  335. throw new Exception("_appBaseAddress不能为空");
  336. }
  337. string baseAddress = _appBaseAddress;
  338. await CheckLoginAsync();
  339. using (var httpClientHandler = new HttpClientHandler())
  340. {
  341. using (var httpClient = new HttpClient(httpClientHandler))
  342. {
  343. httpClient.BaseAddress = new Uri(baseAddress);
  344. httpClient.DefaultRequestHeaders.Accept.Add(
  345. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  346. httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _accesToken);
  347. IsoDateTimeConverter timeFormat = new IsoDateTimeConverter();
  348. timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  349. var sendData = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented, timeFormat);
  350. using (HttpContent httpContent = new StringContent(sendData))
  351. {
  352. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  353. HttpResponseMessage response = null;
  354. if (method == "post")
  355. {
  356. response = await httpClient.PostAsync(url, httpContent);
  357. }
  358. else
  359. {
  360. response = await httpClient.GetAsync(url);
  361. }
  362. string result;
  363. if (!response.IsSuccessStatusCode)
  364. {
  365. result = response.Content.ReadAsStringAsync().Result;
  366. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  367. }
  368. result = await response.Content.ReadAsStringAsync();
  369. var resultDto = JsonConvert.DeserializeObject<WebApiOutDto<TOut>>(result);
  370. if (resultDto.Code == -1)
  371. {
  372. throw new Exception($"调用WebApi失败,返回-1,消息:" + resultDto.Message);
  373. }
  374. return resultDto.Data;
  375. }
  376. }
  377. }
  378. }
  379. #region 获取token
  380. private async Task<WebApiOutDto<LoginOutDataDto>> LoginAsync(string userId, string password)
  381. {
  382. if (string.IsNullOrWhiteSpace(userId))
  383. {
  384. throw new Exception("用户ID不能为空");
  385. }
  386. if (string.IsNullOrWhiteSpace(password))
  387. {
  388. throw new Exception("密码不能为空");
  389. }
  390. using (var httpClientHandler = new HttpClientHandler())
  391. {
  392. using (var httpClient = new HttpClient(httpClientHandler))
  393. {
  394. httpClient.BaseAddress = new Uri(_appBaseAddress);
  395. httpClient.DefaultRequestHeaders.Accept.Add(
  396. new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型
  397. var url = "api/identity/users/login";
  398. var loginUser = new LoginInputDto()
  399. {
  400. UserName = userId,
  401. Password = password
  402. };
  403. var sendData = JsonConvert.SerializeObject(loginUser);
  404. using (HttpContent httpContent = new StringContent(sendData))
  405. {
  406. httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
  407. HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
  408. string result;
  409. if (!response.IsSuccessStatusCode)
  410. {
  411. result = response.Content.ReadAsStringAsync().Result;
  412. throw new Exception("http通信错误:" + response.StatusCode + ",结果:" + result);
  413. }
  414. result = await response.Content.ReadAsStringAsync();
  415. var restultDto = JsonConvert.DeserializeObject<WebApiOutDto<LoginOutDataDto>>(result);
  416. if (restultDto == null)
  417. {
  418. throw new Exception("返回结果是空");
  419. }
  420. if (restultDto.Code != 1)
  421. {
  422. throw new Exception($"登录失败{restultDto.Message}");
  423. }
  424. _accesToken = restultDto.Data.access_token;
  425. return restultDto;
  426. }
  427. }
  428. }
  429. }
  430. private async Task CheckLoginAsync()
  431. {
  432. if (string.IsNullOrWhiteSpace(_accesToken))
  433. {
  434. await LoginAsync();
  435. }
  436. else
  437. {
  438. var handler = new JwtSecurityTokenHandler();
  439. var payload = handler.ReadJwtToken(_accesToken).Payload;
  440. var claims = payload.Claims;
  441. var exp = claims.First(claim => claim.Type == "exp").Value;
  442. if (exp == null)
  443. {
  444. await LoginAsync();
  445. }
  446. else
  447. {
  448. if (long.TryParse(exp, out var expires))
  449. {
  450. var expireTime = DateTimeOffset.FromUnixTimeSeconds(expires).LocalDateTime;
  451. if (expireTime <= DateTime.Now)
  452. {
  453. await LoginAsync();
  454. }
  455. }
  456. else
  457. {
  458. await LoginAsync();
  459. }
  460. }
  461. }
  462. }
  463. private async Task<WebApiOutDto<LoginOutDataDto>> LoginAsync()
  464. {
  465. if (string.IsNullOrWhiteSpace(AppUser))
  466. {
  467. throw new Exception("SelfUser不能为空");
  468. }
  469. if (string.IsNullOrWhiteSpace(AppPassword))
  470. {
  471. throw new Exception("SelfPassword不能为空");
  472. }
  473. var relult = await LoginAsync(AppUser, AppPassword);
  474. return relult;
  475. }
  476. #endregion
  477. }
  478. }