DicomServer/Desktop/Worklist SCP/Model/WorklistItemsProvider.cs

316 lines
14 KiB
C#
Raw Normal View History

2024-12-13 10:06:20 +08:00
// Copyright (c) 2012-2021 fo-dicom contributors.
// Licensed under the Microsoft Public License (MS-PL).
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;
namespace Worklist_SCP.Model
{
public class WorklistItemsProvider : IWorklistItemsSource
{
public NLog.Logger Nlogger = NLog.LogManager.GetCurrentClassLogger();
/// <summary>
/// 从his中查询指定日期的患者信息
/// </summary>
/// <param name="provider"></param>
/// <returns></returns>
FlyHisEcgDataModel getHisPatientData(string QueryDateStr,string inHisCode)
{
//获取福乐云HIS接口的token
string hisToken = getHisToken(ConfigurationManager.AppSettings["hisGetTokenUrl"], ConfigurationManager.AppSettings["hisAppkey"], ConfigurationManager.AppSettings["appsecret"]);
FlyHisEcgDataModel FHEDM = GetHisEcgData(ConfigurationManager.AppSettings["hisGetDataUrl"], inHisCode, QueryDateStr, hisToken);
return FHEDM;
}
public string GenerateId()
{
// 生成一个GUID字符串例如 "d2d26bd7-a438-4575-9052-52f991c56e2b"
string guidStr = Guid.NewGuid().ToString();
string newGuidStr = "";
for (int i = 0; i < guidStr.Length; i++)
{
string val1 = guidStr.Substring(i, 1);
if (val1 != "-")
{
try
{
int val2 = int.Parse(val1);
newGuidStr += val2.ToString();
}
catch
{
newGuidStr += ((new Random()).Next(1, 9));
}
}
else
newGuidStr += val1;
}
newGuidStr = newGuidStr.Replace("-", ".");
return newGuidStr;
}
string submitContrastData(string patientId,string orgId)
{
string FlyPacsContrastUrl = ConfigurationManager.AppSettings["FlyPacsContrastUrl"];
contrastDataModel cdm = new contrastDataModel();
cdm.regid = patientId;
cdm.orgid = orgId;
string jsonStr = JsonConvert.SerializeObject(cdm);
string returnStr=PostMoths(FlyPacsContrastUrl, jsonStr);
return returnStr;
}
public static string PostMoths(string url, string param)
{
string strURL = url;
HttpWebRequest request;
request = (HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
string paraUrlCoded = param;
byte[] payload;
payload = Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
/// <summary>
/// 查询患者信息
/// </summary>
public List<WorklistItem> GetAllCurrentWorklistItems(string ScheduledStationAETitle1)
{
List<WorklistItem> WLI = new List<WorklistItem>();
string clientAET1 = string.Empty;
string inHisCode = string.Empty;
string modality = string.Empty;
// Nlogger.Info(" | 客户端的ScheduledStationAETitle为: " + ScheduledStationAETitle1);
logger.LogWriter(" | 客户端的ScheduledStationAETitle为: " + ScheduledStationAETitle1);
if (ConfigurationManager.AppSettings["worklistModel"] =="0")//worklist工作模式0为本地模式 1为远程服务器模式
{
clientAET1 = ConfigurationManager.AppSettings["CurrentOrgInfo"].Split(',')[0];
ScheduledStationAETitle1 = clientAET1;
inHisCode = ConfigurationManager.AppSettings["CurrentOrgInfo"].Split(',')[3];
modality = ConfigurationManager.AppSettings["CurrentOrgInfo"].Split(',')[1];
}
if (ConfigurationManager.AppSettings["worklistModel"] == "1")//worklist工作模式0为本地模式 1为远程服务器模式
{
clientAET1 = ScheduledStationAETitle1;
inHisCode = ConfigurationManager.AppSettings[ScheduledStationAETitle1].Split(',')[3];
modality = ConfigurationManager.AppSettings[ScheduledStationAETitle1].Split(',')[1];
}
FlyHisEcgDataModel FHEDM;
if (ScheduledStationAETitle1.Trim().Length>0)
FHEDM = getHisPatientData(DateTime.Now.ToString("yyyy-MM-dd"), inHisCode);
else
FHEDM=new FlyHisEcgDataModel();
// MessageBox.Show(ScheduledStationAETitle1+" , "+ FHEDM.rows[0].name);
// File.WriteAllText("logs.txt", FHEDM.rows.Count.ToString());
for (int i = 0; i < FHEDM.rows.Count; i++)
{
if (modality != FHEDM.rows[i].projects[0].category)//如果检查类型 不是 DR DX CT等影像类别 则不加载数据
continue;
DateTime birthDate = DateTime.Now;
try
{
birthDate = DateTime.Parse(FHEDM.rows[i].birthdate);
}
catch { }
string JianChaDescribe = string.Empty;//检查描述
foreach (projectsInfo pji in FHEDM.rows[i].projects)
JianChaDescribe += (pji.jianchamingcheng + ",");
JianChaDescribe = JianChaDescribe.Trim(',');
var item1 = new WorklistItem
{
AccessionNumber = FHEDM.rows[i].jianchaid,//检查ID
DateOfBirth = birthDate,//出生日期CT会计算年龄
//PatientID = FHEDM.rows[i].patientCode,// 患者编号
PatientID = FHEDM.rows[i].jianchaid,// 检查ID 作为 患者编号
Surname = FHEDM.rows[i].name,//姓 直接把姓名都放在 姓 里
Forename = "",//名
Sex = FHEDM.rows[i].sex == "男" ? "M" : "F",//性别
Title = null,
Modality = modality,//检查类型
ExamDescription = JianChaDescribe,//ct里的检查描述检查部位描述
ExamRoom = "",//检查室
HospitalName = FHEDM.rows[i].yiyuanname,//医院名称
PerformingPhysician = null,//执行医师
ProcedureID = null,
ProcedureStepID = null,
//StudyUID = FHEDM.rows[i].jianchabh,//检查部位ID 用检查编号 代替 检查部位ID
StudyUID = GenerateId(),//检查部位ID
ScheduledAET = clientAET1,//检车设备里的 calling AET
ReferringPhysician = FHEDM.rows[i].resDoctorName,//转诊医生;转诊医师;咨询医生;转介医生
ExamDateAndTime = DateTime.Parse(FHEDM.rows[i].kaifangsj)//开方时间 这是检查日期 年月日时分秒
};
WLI.Add(item1);
string returnStr = submitContrastData(FHEDM.rows[i].jianchaid, inHisCode);//将patientid 和 his的orgid提交到 pacs系统的对照关联表里
// Nlogger.Info(FHEDM.rows[i].yiyuanname+ " worklist 患者信息:" + FHEDM.rows[i].name+",性别"+ FHEDM.rows[i].sex + " 患者ID"+ FHEDM.rows[i].jianchaid);
logger.LogWriter(FHEDM.rows[i].yiyuanname + " worklist 患者信息:" + FHEDM.rows[i].name + ",性别" + FHEDM.rows[i].sex + " 患者ID" + FHEDM.rows[i].jianchaid);
}
return WLI;
}
/// <summary>
/// 获取福乐云HIS系统的token
/// </summary>
/// <param name="username"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public string getHisToken(string url1, string appkey, string appsecret)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("appkey", appkey);
dic.Add("appsecret", appsecret);
string resultV = PostFile3(url1, dic);
FlyHisTokenMsgModel tm = JsonConvert.DeserializeObject<FlyHisTokenMsgModel>(resultV);
return tm.data.access_token;
}
/// <summary>
/// 获取福乐云HIS系统的患者基本信息
/// </summary>
/// <param name="username"></param>
/// <param name="pwd"></param>
/// <returns></returns>
public FlyHisEcgDataModel GetHisEcgData(string url1, string Yiyuanid, string kaifangsj, string token)
{
Dictionary<string, object> dic = new Dictionary<string, object>();
dic.Add("Yiyuanid", Yiyuanid);
dic.Add("kaifangsj", kaifangsj);
dic.Add("token", token);
string resultV = PostFile3(url1, dic);
FlyHisEcgDataModel tm = JsonConvert.DeserializeObject<FlyHisEcgDataModel>(resultV);
return tm;
}
/// <summary>
/// post form-data 参数
/// </summary>
/// <param name="url"></param>
/// <param name="items"></param>
/// <returns></returns>
public string PostFile3(string url, Dictionary<string, object> items)
{
string boundary = DateTime.Now.Ticks.ToString("x");
HttpWebRequest request = null;
//如果是发送HTTPS请求              
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
//处理HttpWebRequest访问https有安全证书的问题 请求被中止: 未能创建 SSL/TLS 安全通道。)
ServicePointManager.ServerCertificateValidationCallback += (s, cert, chain, sslPolicyErrors) => true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
//ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Method = "POST";
// request.Headers.Add("Authorization", "Bearer " + token);
// 最后的结束符
var endBoundary = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
//文件数据
string fileFormdataTemplate =
"--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +
"\r\nContent-Type: application/octet-stream" +
"\r\n\r\n";
//文本数据
string dataFormdataTemplate =
"\r\n--" + boundary +
"\r\nContent-Disposition: form-data; name=\"{0}\"" +
"\r\n\r\n{1}";
using (var postStream = new MemoryStream())
{
#region
foreach (KeyValuePair<string, object> key in items)
{
var p = string.Format(dataFormdataTemplate, key.Key, key.Value);
var bp = Encoding.UTF8.GetBytes(p);
postStream.Write(bp, 0, bp.Length);
}
#endregion
//写入结束边界
postStream.Write(endBoundary, 0, endBoundary.Length);
#region
request.ContentLength = postStream.Length;
postStream.Position = 0;
using (Stream ds = request.GetRequestStream())
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
{
ds.Write(buffer, 0, bytesRead);
}
}
#endregion
#region
string result = string.Empty;
using (HttpWebResponse rep = (HttpWebResponse)request.GetResponse())
{
using (Stream ds = rep.GetResponseStream())
{
using (StreamReader sr = new StreamReader(ds))
{
result = sr.ReadToEnd();
}
}
}
return result;
#endregion
}
}
}
}