using CHEER.PresentationLayer;
using Microsoft.CodeDom.Providers.DotNetCompilerPlatform;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Utility;
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Services.Description;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace RMYY_CallCenter_Api.Controllers
{
    [AllowAnonymous]
    public class PatientController : BaseController
    {
      
       // private static string url = $"http://172.16.0.177:8081/winempi/webapi/";
      //  private static string url1 = "http://172.16.0.197:10045/winempi/webapi/";


        private string url = ConfigHelper.GetValue("PatientURL");
        private string wsdlURL = ConfigHelper.GetValue("wsdlURL");
        public class Patient
        {
            public string zsyh { set; get; }//主索引号
            public string hzxm { set; get; }//患者姓名
            public string csrq { set; get; }//出生日期
            public string xbdm { set; get; }//性别代码
            public string xbmc { set; get; }//性别名称
            public string hydm { set; get; }//婚姻代码
            public string hymc { set; get; }//婚姻名称
            public string zjhm { set; get; }//身份证号码
            public string zjlx { set; get; }//身份证类型
            public string lxdh { set; get; }//联系电话
            public string mz { set; get; }//民族
            public string gj { set; get; }//国籍
            public string jtdz { set; get; }//家庭地址
            public string cResult { set; get; }//返回结果描述
            public string ncount { set; get; }//符合查询的数量
        }
        private string  MODELLIST="{\"rows\":[{\"zsyh\":\"3000000003\",\"hzxm\":\"杨奕棉2\",\"csrq\":\"1998-11-12\",\"xbdm\":\"\",\"xbmc\":\"未知\",\"hydm\":\"\",\"hymc\":\"未知\",\"zjhm\":\"410724199811129577\",\"zjlx\":\"SN\",\"lxdh\":\"\",\"mz\":\"\",\"gj\":\"\",\"jtdz\":\"\",\"cResult\":\"成功\",\"ncount\":\"3\"},{\"zsyh\":\"4000000004\",\"hzxm\":\"余静\",\"csrq\":\"1974-06-11\",\"xbdm\":\"\",\"xbmc\":\"未知\",\"hydm\":\"\",\"hymc\":\"未知\",\"zjhm\":\"412322197406110926\",\"zjlx\":\"SN\",\"lxdh\":\"\",\"mz\":\"\",\"gj\":\"\",\"jtdz\":\"\",\"cResult\":\"成功\",\"ncount\":\"3\"},{\"zsyh\":\"P000000025\",\"hzxm\":\"任向阳\",\"csrq\":\"1965-02-14\",\"xbdm\":\"M\",\"xbmc\":\"男\",\"hydm\":\"\",\"hymc\":\"未知\",\"zjhm\":\"410102196502147013\",\"zjlx\":\"SN\",\"lxdh\":\"13673711561\",\"mz\":\"\",\"gj\":\"\",\"jtdz\":\"河南省郑州市金水区\",\"cResult\":\"成功\",\"ncount\":\"3\"}]}";
       
        public ActionResult GetModelList(string zsyh="",string hzxm="",string sfzh=""
            ,string zlkh="",string jzlx="",string jzh="",string lxdh="")
        {
        //return Content(MODELLIST);

            if (!string.IsNullOrEmpty(lxdh))
            {
                if (lxdh.Trim().Length > 11)
                    lxdh = lxdh.Substring(1, 11);
            }
            Dictionary<string, string> values = new Dictionary<string, string>();
            values.Add("zsyh", zsyh);//主索引号
            values.Add("hzxm", hzxm);//患者姓名
            values.Add("sfzh", sfzh);//身份证号
            values.Add("zlkh", zlkh);//诊疗卡号
            values.Add("jzlx", jzlx);//就诊类型
            values.Add("jzh", jzh);//就诊号
            values.Add("lxdh", lxdh);//联系电话
            try
            {
               
                try
                {
                    var responseString = HttpMethods.HttpPost(url + "QueryPatient", values.ToJson(), "application/json;charset=UTF-8");
                    LogHelper.Warn("responseString" + responseString);
                    List<Patient> jo = JsonConvert.DeserializeObject<List<Patient>>(responseString);
                    var obj = new
                    {
                        rows = jo
                    };
                    return Content(obj.ToJson());
                }
                catch
                {
                    var obj = new
                    {
                        rows = "" 
                    };
                    return Content(obj.ToJson());

                }
                
               
            }
            catch(Exception e)
            {
                return Error(e.Message);
            }


        }
        string SOAPAction = ConfigHelper.GetValue("SOAPAction");

        /// <summary>
        /// 把对象转换成xml
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string serialize(object o)
        {
            var xml = "";
            if (o == null)
            {
                return xml;
            }

            return serialize(o, o.GetType());
        }

        /// <summary>
        /// 把对象转换成xml
        /// </summary>
        /// <param name="o"></param>
        /// <param name="type">指定对象类型</param>
        /// <returns></returns>
        public static string serialize(object o, Type type)
        {
            var xml = "";
            if (o == null)
            {
                return xml;
            }

            //序列化对象
            XmlSerializer serializer = new XmlSerializer(type);
            // 输出
            Stream stream = new MemoryStream();
            serializer.Serialize(stream, o);
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            xml = sr.ReadToEnd();
            sr.Dispose();
            sr.Close();

            stream.Dispose();
            stream.Close();

            return xml;
        }

        /// <summary>
        /// 反序化xml为对象
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object deserialize(string xml, Type type)
        {
            try
            {
                using (StringReader sr = new StringReader(xml))
                {
                    XmlSerializer serializer = new XmlSerializer(type);
                    return serializer.Deserialize(sr);
                }
            }
            catch (Exception e)
            {
                return null;
            }

        }
        private string rc = "{\"QueryPatientVisitByIDResponse\":{\"Ack\":{\"ResultCode\":\"AA\"},\"VisitCount\":\"2\",\"GlobalPID\":\"000011" +
            "5272\",\"PatientIDs\":{\"PatientID\":[{\"CardID\":\"0000092787\",\"DomainCode\":\"YNKH\",\"Facility\":\"41604745\"},{\"CardID\":\"10" +
            "5019092521499\",\"DomainCode\":\"YNKH\",\"Facility\":\"41604745\"},{\"CardID\":\"105019092521499\",\"DomainCode\":\"PATID_O\",\"Faci" +
            "lity\":\"41604745\"},{\"CardID\":\"105019092521499\",\"DomainCode\":\"BLH_O\",\"Facility\":\"41604745\"},{\"CardID\":\"411381198309" +
            "022020\",\"DomainCode\":\"SN\",\"Facility\":\"41604745\"}]},\"SourcePatient\":{\"FamilyName\":\"阮静\",\"GivenName\":null,\"Middle" +
            "Name\":null,\"DateTimeOfBirth\":\"1983-09-02\",\"Sex\":\"F\"},\"patientVisits\":{\"patientVisit\":[{\"VisitNumber\":{\"CardID\":\"113" +
            "578348\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityName\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatien" +
            "tLocation\":\"\",\"AttendingDoctor\":{\"FamilyName\":\"王云霞\",\"CardID\":\"0736\"},\"AdmittingDoctor\":{\"FamilyName\":\"王云霞\",\"Ca" +
            "rdID\":\"0736\"},\"AdmitDateTime\":\"2019-11-14 09:51:54\",\"Diagnosis\":\"\"},{\"VisitNumber\":{\"CardID\":\"113578312\",\"Domain" +
            "Code\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityName\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatientLoc" +
            "ation\":\"\",\"AttendingDoctor\":{\"FamilyName\":\"孟彤\",\"CardID\":\"0528\"},\"AdmittingDoctor\":{\"FamilyName\":\"孟彤\",\"Ca" +
            "rdID\":\"0528\"},\"AdmitDateTime\":\"2019-11-14 09:29:45\",\"Diagnosis\":\"\"}]},\"patientPhones\":{\"PatientPhone\":{\"AddressTy" +
            "pe\":\"H\",\"EquipmentType\":\"PH\",\"CountryCode\":null,\"AreaCode\":null,\"PhoneNumber\":\"1383" +
            "8393405\",\"Extension\":null,\"Email\":null}}}}";
        private string ic = "{\"QueryPatientVisitByIDResponse\":{\"Ack\":{\"ResultCode\":\"AA\"},\"VisitCount\":\"1\",\"Glob" +
            "alPID\":\"0000117036\",\"PatientIDs\":{\"PatientID\":[{\"CardID\":\"1012839\",\"DomainCode\":\"BLH_I\",\"Facili" +
            "ty\":\"41604745\"},{\"CardID\":\"1012839\",\"DomainCode\":\"PATID_I\",\"Facility\":\"41604745\"},{\"CardID\":\"105" +
            "019111710114\",\"DomainCode\":\"YNKH\",\"Facility\":\"41604745\"},{\"CardID\":\"105019111710114\",\"DomainC" +
            "ode\":\"PATID_O\",\"Facility\":\"41604745\"},{\"CardID\":\"105019111710114\",\"DomainCode\":\"BLH_O\",\"Facili" +
            "ty\":\"41604745\"},{\"CardID\":\"130203196206182417\",\"DomainCode\":\"SN\",\"Facility\":\"41604745\"}]},\"SourceP" +
            "atient\":{\"FamilyName\":\"易安德\",\"GivenName\":null,\"MiddleName\":null,\"DateTimeOfBirth\":\"1962-06-18\",\"Se" +
            "x\":\"M\"},\"patientVisits\":{\"patientVisit\":{\"VisitNumber\":{\"CardID\":\"113580531\",\"DomainCode\":\"JZH" +
            "_E\",\"Facility\":\"41604745\",\"FacilityName\":\"郑州人民医院\"},\"PatientClass\":\"E\",\"AssignedPatientLocati" +
            "on\":{\"PointOfCare\":\"11276\",\"Bed\":\"0\",\"PointOfCareName\":\"急诊科(东)\"},\"AttendingDoctor\":{\"Family" +
            "Name\":\"刘文政\",\"CardID\":\"13189\"},\"AdmittingDoctor\":{\"FamilyName\":\"刘文政\",\"CardID\":\"13189\"},\"Adm" +
            "itDateTime\":\"2019-11-17 00:00:00\",\"Diagnosis\":{\"Name\":\"腹痛待查\"}}},\"patientPhones\":{\"PatientPhon" +
            "e\":{\"AddressType\":\"H\",\"EquipmentType\":\"PH\",\"CountryCode\":null,\"AreaCode\":null,\"PhoneNumb" +
            "er\":\"-\",\"Extension\":null,\"Email\":null}}}}";
        public string tc = "{\"QueryPatientVisitByIDResponse\":{\"Ack\":{\"ResultCode\":\"AA\"},\"VisitCount\":\"7\",\"Global" +
            "PID\":\"0000118548\",\"PatientIDs\":{\"PatientID\":[{\"CardID\":\"105019092523123\",\"DomainCode\":\"YNKH\",\"Facility\":\"41" +
            "604745\"},{\"CardID\":\"105019092523123\",\"DomainCode\":\"PATID_O\",\"Facility\":\"41604745\"},{\"CardID\":\"1050190925" +
            "23123\",\"DomainCode\":\"BLH_O\",\"Facility\":\"41604745\"},{\"CardID\":\"0000090582\",\"DomainCode\":\"YNKH\",\"Facility\":\"4" +
            "1604745\"},{\"CardID\":\"410122197402162021\",\"DomainCode\":\"SN\",\"Facility\":\"41604745\"}]},\"SourcePatient\":{\"Fami" +
            "lyName\":\"道彦玲\",\"GivenName\":null,\"MiddleName\":null,\"DateTimeOfBirth\":\"1974-02-16\",\"Sex\":\"F\"},\"patientVis" +
            "its\":{\"patientVisit\":[{\"VisitNumber\":{\"CardID\":\"119080743\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"Fac" +
            "ilityName\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatientLocation\":{\"PointOfCare\":\"11218\",\"PointOfCareNa" +
            "me\":\"医学美容中心整形门诊(东)\"},\"AttendingDoctor\":{\"FamilyName\":\"李正斌\",\"CardID\":\"0369\",\"DomainCode\":\"BL" +
            "H_O\"},\"AdmittingDoctor\":\"\",\"AdmitDateTime\":\"2021-10-03 10:38:14\",\"Diagnosis\":\"\"},{\"VisitNumber\":{\"CardID\":\"1" +
            "19079254\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityName\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"Assi" +
            "gnedPatientLocation\":{\"PointOfCare\":\"11218\",\"PointOfCareName\":\"医学美容中心整形门诊(东)\"},\"AttendingDoctor\":{\"Fa" +
            "milyName\":\"张会\",\"DomainCode\":\"BLH_O\"},\"AdmittingDoctor\":\"\",\"AdmitDateTime\":\"2021-10-03 00:00:00\",\"Diagno" +
            "sis\":\"\"},{\"VisitNumber\":{\"CardID\":\"118939978\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityName\":\"郑" +
            "州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatientLocation\":{\"PointOfCare\":\"11266\",\"PointOfCareName\":\"妇科门" +
            "诊(东)\"},\"AttendingDoctor\":{\"FamilyName\":\"苏倩倩\",\"CardID\":\"3577\",\"DomainCode\":\"BLH_O\"},\"AdmittingDoct" +
            "or\":\"\",\"AdmitDateTime\":\"2021-09-19 11:27:49\",\"Diagnosis\":{\"Code\":\"N92.603;N73.902;\",\"Name\":\"月经紊乱;盆腔炎;宫" +
            "颈息肉\"}},{\"VisitNumber\":{\"CardID\":\"118939134\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityN" +
            "ame\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatientLocation\":{\"PointOfCare\":\"11218\",\"PointOfCareName\":\"医" +
            "学美容中心整形门诊(东)\"},\"AttendingDoctor\":{\"FamilyName\":\"李正斌\",\"CardID\":\"0369\",\"DomainCode\":\"BLH_O\"},\"Admit" +
            "tingDoctor\":\"\",\"AdmitDateTime\":\"2021-09-19 09:32:02\",\"Diagnosis\":{\"Code\":\"R22.903\",\"Name\":\"皮肤肿物\"}},{\"Vis" +
            "itNumber\":{\"CardID\":\"113582421\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityName\":\"郑州人民医院\"},\"P" +
            "atientClass\":\"O\",\"AssignedPatientLocation\":\"\",\"AttendingDoctor\":{\"FamilyName\":\"武永娟\",\"CardID\":\"2945\"},\"Adm" +
            "ittingDoctor\":{\"FamilyName\":\"武永娟\",\"CardID\":\"2945\"},\"AdmitDateTime\":\"2019-11-20 15:00:08\",\"Diagnos" +
            "is\":\"\"},{\"VisitNumber\":{\"CardID\":\"118938833\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"Facil" +
            "ityName\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatientLocation\":{\"PointOfCare\":\"11258\",\"PointOfCareNa" +
            "me\":\"普通外科门诊(东)\"},\"AttendingDoctor\":{\"FamilyName\":\"季节\",\"CardID\":\"12290\"},\"AdmittingDoctor\":\"\",\"Dia" +
            "gnosis\":\"\"},{\"VisitNumber\":{\"CardID\":\"118938982\",\"DomainCode\":\"JZH_O\",\"Facility\":\"41604745\",\"FacilityNam" +
            "e\":\"郑州人民医院\"},\"PatientClass\":\"O\",\"AssignedPatientLocation\":{\"PointOfCare\":\"11218\",\"PointOfCareName\":\"医学" +
            "美容中心整形门诊(东)\"},\"AttendingDoctor\":{\"FamilyName\":\"李正斌\",\"CardID\":\"13549\"},\"AdmittingDoctor\":\"\",\"Diag" +
            "nosis\":\"\"}]},\"patientPhones\":{\"PatientPhone\":{\"AddressType\":\"H\",\"EquipmentType\":\"PH\",\"CountryCode\":null,\"Are" +
            "aCode\":null,\"PhoneNumber\":\"15838202349\",\"Extension\":null,\"Email\":null}}}}";

       

       public class QueryPatientVisitByIDResponse
        {
            //AA-成功，NF-不存在，AE-错误，AR-拒绝
            public Ack Ack { set; get; }
            //就诊记录总数
            public string VisitCount { set; get; }
            //患者主索引号
            public string GlobalPID { set; get; }
            public SourcePatient SourcePatient { set; get; }
            public patientPhones patientPhones { set; get; }
            public PatientIDs PatientIDs { set; get; }
            public patientVisits patientVisits { set; get; }
        }
        public class PatientIDs
        {
            public List <PatientID> PatientID { set; get; }
        }
        public class PatientID
        {
            /// <summary>
            /// 标识符
            /// </summary>
            public string CardID { set; get; }
            /// <summary>
            /// 标识符类型（SN身份证号）
            /// </summary>
            public string DomainCode { set; get; }
            /// <summary>
            /// 院区代码
            /// </summary>
            public string Facility { set; get; }
        }
        public class Ack
        {
            public string ResultCode { set; get; }
        }

        public class patientPhones
        {
            public PatientPhone PatientPhone { set; get; }
        }
        public class patientlistPhones
        {
            public List <PatientPhone> PatientPhone { set; get; }
        }
        public class PatientPhone
        {
            /// <summary>
            /// 电话号码
            /// </summary>
            public string PhoneNumber { set; get; }
        }
        public class patientVisits
        {
            public patientVisit  patientVisit { set; get;  }
        }
        public class patientlistVisits
        {
            public List<patientVisit> patientVisit { set; get; }
        }
        public class patientVisit
        {
            public VisitNumber VisitNumber { set; get; }
            /// <summary>
            /// I-入院，O-门诊，E-急诊
            /// </summary>
            public string PatientClass { set; get; }
            /// <summary>
            /// 医疗点
            /// </summary>
            public AssignedPatientLocation AssignedPatientLocation { set; get; }
            /// <summary>
            /// 接诊医生
            /// </summary>
            public AttendingDoctor AttendingDoctor { set; get; }
            /// <summary>
            /// 入院医生
            /// </summary>
            public AdmittingDoctor AdmittingDoctor { set; get; }
            /// <summary>
            /// 门诊就诊日期，入院日期
            /// </summary>
            public string AdmitDateTime { set; get; }
            public Diagnosis Diagnosis { set; get; }
        }
        public class Diagnosis
        {
            /// <summary>
            /// 诊断代码
            /// </summary>
            public string Code { set; get; }
            /// <summary>
            /// 诊断名称
            /// </summary>
            public string Name { set; get; }
        }
        public class AdmittingDoctor
        {
            /// <summary>
            /// 入院医生姓名
            /// </summary>
            public string FamilyName { set; get; }
            /// <summary>
            /// 入院医生工号
            /// </summary>
            public string CardID { set; get; }
        }
        public class AttendingDoctor
        {
            /// <summary>
            ///接诊医生姓名
            /// </summary>
            public string FamilyName { set; get; }
            /// <summary>
            /// 接诊医生工号
            /// </summary>
            public string CardID { set; get; }
        }
        public class AssignedPatientLocation
        {
            /// <summary>
            /// 医疗点，科室代码
            /// </summary>
            public string  PointOfCare { set; get; }
            /// <summary>
            /// 科室名称
            /// </summary>
            public string PointOfCareName { set; get; }
        }
        public class VisitNumber
        {
            /// <summary>
            /// 就诊号
            /// </summary>
            public string CardID { set; get; }
            /// <summary>
            /// 就诊号类型
            /// </summary>
            public string DomainCode { set; get; }
            /// <summary>
            /// 医疗机构代码
            /// </summary>
            public string Facility { set; get; }
            /// <summary>
            /// 医疗机构名称
            /// </summary>
            public string FacilityName { set; get; }
        }
        public class SourcePatient
        {
            public string FamilyName { set; get; }//姓名
            public string DateTimeOfBirth { set; get; }//出生日期
            public string Sex { set; get; }//性别F女性M男性U未知
        }

        public  ActionResult GetRcord(string starttime, string endtime, string PatientClass, string GlobalPID, string Facility)
        {
            //string str = "";
            //if (PatientClass == "O")
            //    str = rc;
            //else if (PatientClass == "I")
            //    str = ic;
            //else
            //    str = tc;
            //return Content(str);


            HandlePatient service = new HandlePatient();
              string xmlText = LoadXmls(starttime, endtime, PatientClass, GlobalPID, Facility);
            var obj=   service.Controller("QueryPatientVisitByID", xmlText);
              string xml = serialize(obj);
           var value = xml.Replace("\r\n", "");
            XDocument doc = XDocument.Parse(deserialize(value, value.GetType()).ToString  ());
            var xmlDocument = new XmlDocument();
            using (var xmlReader = doc.CreateReader())
            {
                xmlDocument.Load(xmlReader);
            }
            var model = Newtonsoft.Json.JsonConvert.SerializeXmlNode(xmlDocument);

            Task.Run(() =>
            {
                var jo = (JObject)JsonConvert.DeserializeObject(model);
                var QueryPatientVisitByIDResponse = (JObject)JsonConvert.DeserializeObject(jo["QueryPatientVisitByIDResponse"]
                    .ToString());
                var Ack = JsonConvert.DeserializeObject<Ack>(QueryPatientVisitByIDResponse["Ack"].ToString());
                if (Ack.ResultCode == "AA" && int.Parse(QueryPatientVisitByIDResponse["VisitCount"].ToString()) > 0)
                {
                    string F_GlobalPID = QueryPatientVisitByIDResponse["GlobalPID"].ToString();//患者主索引号
                    string F_CardID = ""; string F_PhoneNumber = "";
                    string F_FamilyName = ""; string F_DateTimeOfBirth = ""; string F_Sex = "";

                    if (QueryPatientVisitByIDResponse["patientVisits"].ToString() != "")
                    {
                        if (QueryPatientVisitByIDResponse["PatientIDs"].ToString() != "")
                        {
                            var PatientIDs = JsonConvert.DeserializeObject<PatientIDs>(QueryPatientVisitByIDResponse["PatientIDs"].ToString());
                            if (PatientIDs.PatientID != null && PatientIDs.PatientID.Count > 0)
                            {
                                foreach (var it in PatientIDs.PatientID)
                                {
                                    if (it.DomainCode == "SN")
                                    {
                                        F_CardID = it.CardID;//患者身份证号
                                        continue;
                                    }
                                }
                            }
                            if (F_CardID != "")
                            {
                                if (QueryPatientVisitByIDResponse["patientPhones"].ToString() != "")
                                {
                                    try
                                    {
                                        var patientPhones = JsonConvert.DeserializeObject<patientPhones>(QueryPatientVisitByIDResponse["patientPhones"].ToString());
                                        if (patientPhones.PatientPhone != null)
                                        {
                                            F_PhoneNumber = patientPhones.PatientPhone.PhoneNumber;//患者电话号码
                                        }
                                    }
                                    catch
                                    {
                                        var patientPhones = JsonConvert.DeserializeObject<patientlistPhones>(QueryPatientVisitByIDResponse["patientPhones"].ToString());
                                        if (patientPhones.PatientPhone != null && patientPhones.PatientPhone.Count
                                            > 0)
                                        {
                                            foreach (var it in patientPhones.PatientPhone)
                                            {
                                                if (!string.IsNullOrEmpty(it.PhoneNumber))
                                                {
                                                    F_PhoneNumber = it.PhoneNumber;//患者电话号码
                                                    continue;
                                                }
                                            }
                                        }
                                    }

                                }
                                if (QueryPatientVisitByIDResponse["SourcePatient"].ToString() != "")
                                {
                                    var SourcePatient = JsonConvert.DeserializeObject<SourcePatient>(QueryPatientVisitByIDResponse["SourcePatient"].ToString());
                                    F_FamilyName = SourcePatient.FamilyName;//患者姓名
                                    F_DateTimeOfBirth = SourcePatient.DateTimeOfBirth;//患者出生日期
                                                                                      //性别F女性M男性U未知
                                    if (SourcePatient.Sex == "M")//性别
                                    {
                                        F_Sex = "男";
                                    }
                                    else if (SourcePatient.Sex == "F")
                                    {
                                        F_Sex = "女";
                                    }
                                    else
                                    {
                                        F_Sex = "未知";
                                    }

                                }


                                if (int.Parse(QueryPatientVisitByIDResponse["VisitCount"].ToString()) > 1)
                                {
                                    var patientVisits = JsonConvert.DeserializeObject<patientlistVisits>(QueryPatientVisitByIDResponse["patientVisits"].ToString());
                                    foreach (var it in patientVisits.patientVisit)
                                    {
                                        Model.T_Wo_MedicalRecord record = new Model.T_Wo_MedicalRecord();
                                        var sql = $"select count(1) from T_Wo_MedicalRecord where F_JZH='{it.VisitNumber.CardID }'";
                                        var count = Int32.Parse(DbHelperSQL.GetSingle(sql).ToString());
                                        if (count > 0)
                                            continue;
                                        else
                                        {
                                            record.F_GlobalPID = F_GlobalPID;//患者主索引号
                                            record.F_CardID = F_CardID;//身份证号
                                            record.F_PhoneNumber = F_PhoneNumber;//电话号码
                                            record.F_FamilyName = F_FamilyName;//患者姓名
                                            record.F_DateTimeOfBirth = F_DateTimeOfBirth;//出生日期
                                            record.F_Sex = F_Sex;//性别
                                            if (it.PatientClass == "I")//就诊类别
                                                record.F_PatientClass = "入院";
                                            else if (it.PatientClass == "O")
                                                record.F_PatientClass = "门诊";
                                            else if (it.PatientClass == "E")
                                                record.F_PatientClass = "急诊";
                                            else if (it.PatientClass == "P")
                                                record.F_PatientClass = "体检";
                                            record.F_FacilityName = it.VisitNumber.FacilityName;//院区
                                            record.F_JZH = it.VisitNumber.CardID;//就诊号
                                            if (it.AssignedPatientLocation != null && it.AssignedPatientLocation.ToString() != "")
                                                record.F_PointOfCareName = it.AssignedPatientLocation.PointOfCareName;//科室名称
                                            if (it.AttendingDoctor != null && it.AttendingDoctor.ToString() != "")
                                            {
                                                record.F_AttendingDoctor = it.AttendingDoctor.FamilyName;//接诊医生姓名
                                                record.F_AttendingDoctorCode = it.AttendingDoctor.CardID;//接诊医生工号
                                            }
                                            if (it.AdmittingDoctor != null && it.AdmittingDoctor.ToString() != "")
                                            {
                                                record.F_AdmittingDoctor = it.AttendingDoctor.FamilyName;//接诊医生姓名
                                                record.F_AdmittingDoctorCode = it.AttendingDoctor.CardID;//接诊医生工号
                                            }
                                            record.F_AdmitDateTime = it.AdmitDateTime;//门诊就诊日期，入院日期
                                            if (it.Diagnosis != null && it.Diagnosis.ToString() != "")
                                            {
                                                record.F_DiagnosisName = it.Diagnosis.Name;//诊断名称
                                                record.F_DiagnosisCode = it.Diagnosis.Code;//诊断代码
                                            }
                                            new Bll.T_Wo_MedicalRecord().Add(record);
                                        }

                                    }
                                }
                                else
                                {
                                    var patientVisits = JsonConvert.DeserializeObject<patientVisits>(QueryPatientVisitByIDResponse["patientVisits"].ToString());
                                    Model.T_Wo_MedicalRecord record = new Model.T_Wo_MedicalRecord();
                                    if (patientVisits.patientVisit != null)
                                    {
                                        var it = patientVisits.patientVisit;
                                        var sql = $"select count(1) from T_Wo_MedicalRecord where F_JZH='{it.VisitNumber.CardID }'";
                                        var count = Int32.Parse(DbHelperSQL.GetSingle(sql).ToString());
                                        if (count <= 0)
                                        {
                                            record.F_GlobalPID = F_GlobalPID;//患者主索引号
                                            record.F_CardID = F_CardID;//身份证号
                                            record.F_PhoneNumber = F_PhoneNumber;//电话号码
                                            record.F_FamilyName = F_FamilyName;//患者姓名
                                            record.F_DateTimeOfBirth = F_DateTimeOfBirth;//出生日期
                                            record.F_Sex = F_Sex;//性别
                                            if (it.PatientClass == "I")//就诊类别
                                                record.F_PatientClass = "入院";
                                            else if (it.PatientClass == "O")
                                                record.F_PatientClass = "门诊";
                                            else if (it.PatientClass == "E")
                                                record.F_PatientClass = "急诊";
                                            else if (it.PatientClass == "P")
                                                record.F_PatientClass = "体检";
                                            record.F_FacilityName = it.VisitNumber.FacilityName;//院区
                                            record.F_JZH = it.VisitNumber.CardID;//就诊号
                                            if (it.AssignedPatientLocation != null && it.AssignedPatientLocation.ToString() != "")
                                                record.F_PointOfCareName = it.AssignedPatientLocation.PointOfCareName;//科室名称
                                            if (it.AttendingDoctor != null && it.AttendingDoctor.ToString() != "")
                                            {
                                                record.F_AttendingDoctor = it.AttendingDoctor.FamilyName;//接诊医生姓名
                                                record.F_AttendingDoctorCode = it.AttendingDoctor.CardID;//接诊医生工号
                                            }
                                            if (it.AdmittingDoctor != null && it.AdmittingDoctor.ToString() != "")
                                            {
                                                record.F_AdmittingDoctor = it.AttendingDoctor.FamilyName;//接诊医生姓名
                                                record.F_AdmittingDoctorCode = it.AttendingDoctor.CardID;//接诊医生工号
                                            }
                                            record.F_AdmitDateTime = it.AdmitDateTime;//门诊就诊日期，入院日期
                                            if (it.Diagnosis != null && it.Diagnosis.ToString() != "")
                                            {
                                                record.F_DiagnosisName = it.Diagnosis.Name;//诊断名称
                                                record.F_DiagnosisCode = it.Diagnosis.Code;//诊断代码
                                            }
                                            record.F_CreatTime = DateTime.Now;
                                            new Bll.T_Wo_MedicalRecord().Add(record);

                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            });
            return Content(model);
        }

        /// <summary>
        /// 接口入参拼接PatientClassI-入院，O-门诊，E-急诊
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string LoadXmls(string starttime,string endtime,string  PatientClass,string GlobalPID,string Facility)
        {
           
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append(@"<?xml version='1.0' encoding='UTF-8'?>");
            //  < !-- 查询患者标识符 -->
            stringBuilder.Append($"<QueryPatientVisitByIDRequest>");
              stringBuilder.Append($"<ConfigHeader><Facility>41604745</Facility><Application>BZZX</Application></ConfigHeader>");
            stringBuilder.Append($"<QueryParameter>");
            stringBuilder.Append($"<FromLimit></FromLimit><ToLimit></ToLimit>");
            stringBuilder.Append($"<FromDateTime>{starttime}</FromDateTime><ToDateTime>{endtime}</ToDateTime>");
            stringBuilder.Append($"<PatientClass>{PatientClass}</PatientClass>");//PatientClassI-入院，O-门诊，E-急诊
            stringBuilder.Append($"<PatientIDs>");
            stringBuilder.Append($"<PatientID>");
            stringBuilder.Append($"<CardID></CardID>");
            stringBuilder.Append($"<DomainCode></DomainCode>");
            stringBuilder.Append($"<Facility>{Facility}</Facility>");//院区代码
            stringBuilder.Append($"</PatientID>");
            stringBuilder.Append($"</PatientIDs>");
            stringBuilder.Append($"<GlobalPID>{GlobalPID}</GlobalPID>");//患者主索引号
            stringBuilder.Append(@"<VisitNumbers>");
            stringBuilder.Append(@"<VisitNumber>");
            stringBuilder.Append($"<DomainCode></DomainCode>");
            stringBuilder.Append($"<Facility>{Facility}</Facility>");//院区代码
            stringBuilder.Append(@"</VisitNumber>");
            stringBuilder.Append(@"</VisitNumbers>");
            stringBuilder.Append($"</QueryParameter>");
            stringBuilder.Append($"</QueryPatientVisitByIDRequest>") ;
            return stringBuilder.ToString();
        }

    
       public ActionResult GetMedicalRecord()
        {
            DataTable dt = new DataTable();
            string CardID = HttpUtility.UrlDecode(RequestString.GetQueryString("CardID"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = string.Empty;
          
            if (CardID.Trim() != "")
            {
                sql += " and F_CardID = '" + CardID + "'";
            }
            else
            {
                var obj1 = new
                {
                    state = "success",
                    message = "成功",
                    rows = dt,
                    total = 0
                };
                return Content(obj1.ToJson());
            }
            
           
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                    "T_Wo_MedicalRecord",
                    "F_ID",
                    "*",
                    sql,
                    "ORDER BY F_ID desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 实例化WebServices
        /// </summary>
        /// <param name="url">WebServices地址</param>
        /// <param name="methodname">调用的方法</param>
        /// <param name="args">把webservices里需要的参数按顺序放到这个object[]里</param>
        public static object InvokeWebService(string url, string methodname, object[] args)
            {
                //这里的namespace是需引用的webservices的命名空间，我没有改过，也可以使用。也可以加一个参数从外面传进来。
                string @namespace = "client";

                try
                {
                    //获取WSDL
                    WebClient wc = new WebClient();
                    Stream stream = wc.OpenRead(url);
                    ServiceDescription sd = ServiceDescription.Read(stream);
                    string classname = sd.Services[0].Name;
                    ServiceDescriptionImporter sdi = new ServiceDescriptionImporter();
                    sdi.AddServiceDescription(sd, "", "");
                    CodeNamespace cn = new CodeNamespace(@namespace);

                    //生成客户端代理类代码
                    CodeCompileUnit ccu = new CodeCompileUnit();
                    ccu.Namespaces.Add(cn);
                    sdi.Import(cn, ccu);
                    CSharpCodeProvider csc = new CSharpCodeProvider();
                    //ICodeCompiler icc = csc.CreateCompiler();

                    //设定编译参数
                    CompilerParameters cplist = new CompilerParameters();
                    cplist.GenerateExecutable = false; //动态编译后的程序集不生成可执行文件
                    cplist.GenerateInMemory = true; //动态编译后的程序集只存在于内存中，不在硬盘的文件上
                    cplist.ReferencedAssemblies.Add("System.dll");
                    cplist.ReferencedAssemblies.Add("System.XML.dll");
                    cplist.ReferencedAssemblies.Add("System.Web.Services.dll");
                    cplist.ReferencedAssemblies.Add("System.Data.dll");

                    //编译代理类
                    CompilerResults cr = csc.CompileAssemblyFromDom(cplist, ccu);
                    if (true == cr.Errors.HasErrors)
                    {
                        StringBuilder sb = new StringBuilder();
                        foreach (CompilerError ce in cr.Errors)
                        {
                            sb.Append(ce.ToString());
                            sb.Append(Environment.NewLine);
                        }

                        throw new Exception(sb.ToString());
                    }

                    //生成代理实例，并调用方法
                    Assembly assembly = cr.CompiledAssembly;
                    Type t = assembly.GetType(@namespace + "." + classname, true, true);
                    object obj = Activator.CreateInstance(t);
                    MethodInfo mi = t.GetMethod(methodname);

                    //注：method.Invoke(o, null)返回的是一个Object,如果你服务端返回的是DataSet,这里也是用(DataSet)method.Invoke(o, null)转一下就行了,method.Invoke(0,null)这里的null可以传调用方法需要的参数,string[]形式的
                    return mi.Invoke(obj, args);
                }
                catch (Exception e)
                {
                    return e ;
                }
            }



        public  string GetSOAPReSource(string url, string datastr)
        {
            try
            {
                //request
                Uri uri = new Uri(url);
                WebRequest webRequest = WebRequest.Create(uri);
                //webRequest.ContentType = "application/soap+xml; charset=utf-8";
                webRequest.ContentType = "text/xml;charset=utf-8";
                webRequest.Method = "POST";
                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    byte[] paramBytes = Encoding.UTF8.GetBytes(datastr.ToString());
                    requestStream.Write(paramBytes, 0, paramBytes.Length);
                }
                //response
                WebResponse webResponse = webRequest.GetResponse();
                using (StreamReader myStreamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                {
                    string result = "";
                    return result = myStreamReader.ReadToEnd();
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


        /// <summary>
        /// 调用soap协议接口   webservice    wsdl   
        /// </summary>
        /// <param name="url"></param>
        /// <param name="method"></param>
        /// <param name="contenttype"></param>
        /// <param name="header"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Http(string url, string method = "post", string contenttype = "text/xml;charset=utf-8", Hashtable header = null, string data = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = string.IsNullOrEmpty(method) ? "post" : method;
            request.ContentType = string.IsNullOrEmpty(contenttype) ? "text/xml;charset=utf-8" : contenttype;
            if (header != null)
            {
                foreach (var i in header.Keys)
                {
                    request.Headers.Add(i.ToString(), header[i].ToString());
                }
            }
            if (!string.IsNullOrEmpty(data))
            {
                Stream RequestStream = request.GetRequestStream();
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                RequestStream.Write(bytes, 0, bytes.Length);
                RequestStream.Close();
            }
            HttpWebResponse response;
            try
            {
                 response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
          
            Stream ResponseStream = response.GetResponseStream();
            StreamReader StreamReader = new StreamReader(ResponseStream, Encoding.GetEncoding("utf-8"));
            string re = StreamReader.ReadToEnd();
            StreamReader.Close();
            ResponseStream.Close();
            return re;
        }

    }
}