using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using System.Data.Common;
using System.Transactions;
using System.Text.RegularExpressions;
using System.Management;
using IL.Common;
using MediII.Adapter.ReceiveToKCModel;

namespace MediII.Adapter.BizComponent.ADT
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class ADTHandler
    {
        static readonly string SEDING_APPLICATION = System.Configuration.ConfigurationManager.AppSettings["SedingApplication"];
        //数据库连接
        protected Database ctx;
        protected Database Scanctx;
        /// <summary>
        /// 
        /// </summary>
        public ADTHandler()
        {
            DatabaseProviderFactory factory = new DatabaseProviderFactory();
            ctx = factory.Create("HealthCare");
            Scanctx = factory.CreateDefault();
        }

        protected string GetZone(string value)
        {
            string sql = @"SELECT Zone FROM HealthCare.dbo.HisInfo WHERE HisZone = @HisZone";
            var command1 = ctx.GetSqlStringCommand(sql.ToString());
            ctx.AddInParameter(command1, "HisZone", System.Data.DbType.AnsiString, value);
            DataTable dt = ctx.ExecuteDataSet(command1).Tables[0];
            string ZONE = "";
            if (dt.Rows.Count > 0)
            {
                ZONE = dt.Rows[0]["Zone"].ToString();
            }
            return ZONE;
        }

        /// <summary>
        /// 根据事件类型获取不同的处理类
        /// </summary>
        /// <param name="evntType">消息类型</param>
        /// <returns>ADTHandler的子类</returns>
        public static ADTHandler GetHandler(string evntType)
        {
            try
            {
                switch (evntType)
                {
                    case "ADT^A01[B01]": return new ADT_A01B01_Handler();// 住院就诊信息登记、相关明细任务生成
                    case "ADT^A01[B02]": return new ADT_A01B02_Handler();// 住院处方单
                    case "ADT^A01[B03]": return new ADT_A01B03_Handler();// 住院收费明细
                    case "ADT^A01[B04]": return new ADT_A01B04_Handler();// 住院转科转床
                    case "ADT^A02[B01]": return new ADT_A02B01_Handler();// 住院就诊信息登记、判断是否出院并生成明细任务
                    //case "ADT^A02[B02]": return new ADT_A02B02_Handler();// 门诊收费明细更新
                    //case "ADT^A02[B03]": return new ADT_A02B03_Handler();// 门诊挂号更新
                    //case "A03": return new ADT_A03_Handler();//出院（ADT^A03）
                    case "ADT^A04[B01]": return new ADT_A04B01_Handler();//   门诊处方单
                    case "ADT^A04[B02]": return new ADT_A04B02_Handler();//门诊收费明细
                    case "ADT^A04[B03]": return new ADT_A04B03_Handler();//门诊挂号
                    //case "ADT^A05[B01]": return new ADT_A02B01_Handler();//住院就诊信息更新
                    //case "A08": return new ADT_A08_Handler();//患者信息修改：
                    //case "A10": return new ADT_A10_Handler();//入科
                    //case "A11": return new ADT_A11_Handler();//取消入院
                    //case "A13": return new ADT_A13_Handler();//取消出院（ADT^A13）
                    //case "A16": return new ADT_A16_Handler();//患者预出院
                    //case "A25": return new ADT_A25_Handler();//患者取消预出院
                    //case "A28": return new ADT_A28_Handler();//患者建档
                    //case "A31": return new ADT_A31_Handler();//患者基本信息修改（ADT^A31） 
                    //case "A29": return new ADT_A29_Handler();//删除婴儿信息(ADT^A29^ADT_A21)
                    //case "A54": return new ADT_A54_Handler();//修改主治医生
                    //case "A60": return new ADT_A60_Handler();//患者副作用信息修改




                    default: throw new NotImplementedException();
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(ex, LogCatagories.General);
                throw ex;
            }

        }



        /// <summary>
        /// 待实现的处理
        /// </summary>
        /// <param name="m">传入的消息结构</param>
        /// <returns>ACK</returns>
        public abstract void Handler(string m, string ID);

        #region 获取字典信息
        /// <summary>
        /// 获取字典信息
        /// </summary> 
        /// <returns></returns>
        protected DataTable GetDictionView(Database ctx, string viewName)
        {
            var ntb = new DataTable();
            var sql = string.Format("SELECT  CodeID,CodeName,HisCodeID,MedCodeID FROM  HealthCare.dbo.[{0}]  WHERE IsDel=0", viewName);
            var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);
            ntb.Load(SqlDataAccess.ExecuteReader(ctx, cmd));
            return ntb;
        }


        /// <summary>
        /// 获取本地Zone
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="hisZone"></param>
        /// <returns></returns>
        protected string GetZone(Database ctx, string hisZone)
        {
            var sql = string.Format("SELECT top 1 Zone FROM HealthCare.dbo.HisInfo WHERE  HisZone='{0}'", hisZone);
            var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);
            var val = StrHelepr.Obj2StrTrim(SqlDataAccess.ExecuteScalar(ctx, cmd));
            if (string.IsNullOrEmpty(val))
            {
                return hisZone;
            }
            return val;
        }
        #endregion

        #region 取序列
        ///<summary>
        /// 取序列
        /// </summary> 
        protected string GetSeq(Database ctx, string seqName)
        {
            string sql = string.Format("SELECT NEXT VALUE FOR {0}", seqName);
            var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);
            object obj = SqlDataAccess.ExecuteScalar(ctx, cmd);
            if (obj != null)
                return obj.ToString();
            else
                return "0";
        }
        #endregion

        #region 取服务器当前时间
        /// <summary>
        /// 获取当前时间
        /// </summary> 
        internal DateTime GetNow(Database ctx)
        {

            object obj = (DateTime)SqlDataAccess.ExecuteScalar(ctx, CommandType.Text, "select GETDATE()");
            if (obj != null)
                return Convert.ToDateTime(obj.ToString());
            else
                return DateTime.Now;
        }

        #endregion



        /// <summary>
        /// 添加床位日志
        /// </summary>
        /// <param name="ctx">数据库操作类</param>
        /// <param name="visitNo"></param>
        /// <param name="updateUser"></param>
        /// <param name="OperateTypeInstr"></param>
        /// <param name="remark"></param>
        /// <param name="oldMsg"></param>
        /// <param name="newMsg"></param>
        protected void AddNewWardLog(Database ctx, string visitNo, string updateUser, string OperateTypeInstr, string remark, string oldMsg, string newMsg)
        {
            var sql = @" INSERT INTO HealthCare.dbo.Log_WardOperateLog( VisitNo ,  UpdateUser ,  UpdateDateTime ,   OperateTypeInstr , IP ,  Mac ,   Remark ,   OldContent ,   NewContent) VALUES( @VisitNo ,  @UpdateUser ,  GETDATE() ,   @OperateTypeInstr , @IP , @Mac ,   @Remark ,   @OldContent ,   @NewContent) ";
            var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);

            SqlDataAccess.AddInParameter(ctx, cmd, "VisitNo", DbType.AnsiString, visitNo);
            SqlDataAccess.AddInParameter(ctx, cmd, "UpdateUser", DbType.AnsiString, updateUser);
            SqlDataAccess.AddInParameter(ctx, cmd, "OperateTypeInstr", DbType.AnsiString, OperateTypeInstr);
            SqlDataAccess.AddInParameter(ctx, cmd, "IP", DbType.AnsiString, NetHelper.GetIP());
            SqlDataAccess.AddInParameter(ctx, cmd, "Mac", DbType.AnsiString, NetHelper.GetMacAddress());
            SqlDataAccess.AddInParameter(ctx, cmd, "Remark", DbType.AnsiString, remark);
            SqlDataAccess.AddInParameter(ctx, cmd, "OldContent", DbType.AnsiString, oldMsg);
            SqlDataAccess.AddInParameter(ctx, cmd, "NewContent", DbType.AnsiString, newMsg);

            SqlDataAccess.ExecuteNonQuery(ctx, cmd);
        }

        #region "患者建档（ADT^A28）消息规范"

        /// <summary>
        /// 检查是否建档
        /// </summary>
        /// <param name="OptProfile"></param>
        /// <param name="chartNo"></param>
        /// <returns></returns>
        protected int HasPatient(string chartNo)
        {
            try
            {
                var sql = "  select count(1)    from HealthCare.dbo.Patient   where ChartNo=@ChartNo  ";
                var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);
                SqlDataAccess.AddInParameter(ctx, cmd, "ChartNo", DbType.AnsiString, chartNo);
                return int.Parse(StrHelepr.Obj2StrTrim(SqlDataAccess.ExecuteScalar(ctx, cmd)));  //病患是否建档 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 建档
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="m05"></param>
        /// <param name="m01"></param>
        //protected void AddNewPatient(Database ctx, ADT_A05 m05 = null, ADT_A01 m01 = null)
        //{

        //    PID pid = null;
        //    PV1 pv1 = null;
        //    NK1 nk1 = null;
        //    if (null != m05)
        //    {
        //        pid = m05.PID;
        //        pv1 = m05.PV1;
        //        nk1 = m05.GetNK1(0);
        //    }
        //    if (null != m01)
        //    {
        //        pid = m01.PID;
        //        pv1 = m01.PV1;
        //        nk1 = m01.GetNK1(0);
        //    }
        //    AddNewPatient(ctx, pid, pv1, nk1);
        //}
//        protected void AddNewPatient(Database ctx, PID pid, PV1 pv1, NK1 nk1)
//        {
//            DataRow rowTemp = null;
//            #region SQL

//            var sql1 = @"insert into HealthCare.dbo.Patient
//                        (ChartNo, LastNumber,PtName,BirthDay,IdNo,CardNo,Sex, UnBloodType, BloodType,PtType,
//                         DiscountType, EduLevel,JobType,BornFlag,Marriage, TakeMedInfo , SalaryInfo ,
//                         Tel1 , Tel2 , EMail, ConName , ConTel , ConTel1Area, ConTel1, ChartWhere,
//                         FirstVisitDate , FirstVisitDivNo, NoPromiseCnt , NoPromiseDate, Private, AgreeUse , BadRecord, 
//                         LastVisitDate, CheckUser, CheckTime, UpdateUser , UpdateTime ,NationNo, NationName, WorkplaceZipCode, 
//                         HomeZipCode, ConRelationshipNo, ConRelationshipName, ConZipCode, 
//                         UnitAdrDesc,AdrAreaName, AdrArea, AdrDesc, 
//                         NativeNo,NativeName, 
//                         BirthAreaNo,BirthAreaName, 
//                         Nationality , NationalityName ,IsSigned,IsBlackList,ConArea,GreenChannelFlag) 
//                         Values
//                        (@ChartNo , @LastNumber ,@PtName , @BirthDay , @IdNo , @CardNo , HealthCare.dbo.GetSexCodeIdByHisID(@Sex),
//                         @UnBloodType , @BloodType , @PtType ,
//                         @DiscountType, @EduLevel , @JobType ,  @BornFlag , 
//                         HealthCare.dbo.GetMarriageCodeIdByHisID(@Marriage), @TakeMedInfo ,@SalaryInfo , 
//                         @Tel1 , @Tel2 , @EMail,  @ConName , @ConTel , @ConTel1Area, @ConTel1, @ChartWhere, 
//                         GetDate() , @FirstVisitDivNo, @NoPromiseCnt , GetDate(), @Private, @AgreeUse , @BadRecord, 
//                         GetDate(), @CheckUser, GetDate(), @UpdateUser , GetDate() ,@NationNo, @NationName, @WorkplaceZipCode, 
//                         @HomeZipCode, @ConRelationshipNo, @ConRelationshipName, @ConZipCode,
//                         @UnitAdrDesc, HealthCare.dbo.GetNativeCodeName(HealthCare.dbo.GetMinNativeCodeID(@AdrDesc,5),@AdrDesc),HealthCare.dbo.GetMinNativeCodeID(@AdrDesc,5), @AdrDesc,
//                         HealthCare.dbo.GetMinNativeCodeID(@AdrDesc,5), HealthCare.dbo.GetNativeCodeName(HealthCare.dbo.GetMinNativeCodeID(@AdrDesc,5),@AdrDesc),
//                         HealthCare.dbo.GetMinNativeCodeID(@BirthAreaName,5), HealthCare.dbo.GetNativeCodeName(HealthCare.dbo.GetMinNativeCodeID(@BirthAreaName,5),@AdrDesc),
//                         @Nationality ,@NationalityName,@IsSigned,@IsBlackList,@ConArea,@GreenChannelFlag)";

//            #endregion

//            var command = SqlDataAccess.GetSqlStringCommand(ctx, sql1);
//            //就诊卡号
//            SqlDataAccess.AddInParameter(ctx, command, "ChartNo", DbType.AnsiString, pid.PatientID.ID.Value);
//            int LastNumberCount = pid.PatientID.ID.Value.Count();
//            //最后两码
//            if (LastNumberCount <= 2)
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "LastNumber", DbType.AnsiString, pid.PatientID.ID.Value);
//            }
//            else
//            {
//                string LastNumberSubString = pid.PatientID.ID.Value.Substring(LastNumberCount - 2);
//                SqlDataAccess.AddInParameter(ctx, command, "LastNumber", DbType.AnsiString, LastNumberSubString);
//            }


//            //姓名
//            SqlDataAccess.AddInParameter(ctx, command, "PtName", DbType.AnsiString, pid.GetPatientName(0).GivenName.Value);
//            string tmp = pid.DateTimeOfBirth.TimeOfAnEvent.GetAsDate().ToString();
//            //出生日期
//            SqlDataAccess.AddInParameter(ctx, command, "BirthDay", DbType.DateTime, pid.DateTimeOfBirth.TimeOfAnEvent.GetAsDate());
//            //性别
//            SqlDataAccess.AddInParameter(ctx, command, "Sex", DbType.AnsiString, pid.AdministrativeSex.Value);
//            //if (pid.AdministrativeSex.Value == "M")
//            //    SqlDataAccess.AddInParameter(ctx,command, "Sex", DbType.AnsiString, "1");
//            //else if (pid.AdministrativeSex.Value == "F")
//            //    SqlDataAccess.AddInParameter(ctx,command, "Sex", DbType.AnsiString, "2");
//            //else
//            //    SqlDataAccess.AddInParameter(ctx,command, "Sex", DbType.AnsiString, "");



//            SqlDataAccess.AddInParameter(ctx, command, "BirthAreaName", DbType.AnsiString, pid.BirthPlace.Value);
//            //SqlDataAccess.AddInParameter(ctx, command, "JobType", DbType.AnsiString, pid.GetCitizenship(0).Identifier.Value);his不发职业了
//            SqlDataAccess.AddInParameter(ctx, command, "UnBloodType", DbType.AnsiString, "");
//            SqlDataAccess.AddInParameter(ctx, command, "BloodType", DbType.AnsiString, "");
//            if (pv1.PatientType.Value == "01")
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "PtType", DbType.AnsiString, "1");
//            }
//            else
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "PtType", DbType.AnsiString, "2");
//            }
//            SqlDataAccess.AddInParameter(ctx, command, "DiscountType", DbType.Int32, 0);
//            SqlDataAccess.AddInParameter(ctx, command, "EduLevel", DbType.Int32, 0);
//            SqlDataAccess.AddInParameter(ctx, command, "JobType", DbType.Int32, 0);
//            SqlDataAccess.AddInParameter(ctx, command, "BornFlag", DbType.AnsiString, "N");
//            SqlDataAccess.AddInParameter(ctx, command, "TakeMedInfo", DbType.AnsiString, "");
//            SqlDataAccess.AddInParameter(ctx, command, "SalaryInfo", DbType.AnsiString, "");

//            #region "联系人"
//            var nName = nk1.GetName(0);
//            if (null != nName)
//                SqlDataAccess.AddInParameter(ctx, command, "ConName", DbType.AnsiString, nName.GivenName.Value);
//            else
//                SqlDataAccess.AddInParameter(ctx, command, "ConName", DbType.AnsiString, DBNull.Value);



//            var nPhone = nk1.GetPhoneNumber(0);
//            if (null != nPhone)
//                SqlDataAccess.AddInParameter(ctx, command, "ConTel", DbType.AnsiString, nPhone.PhoneNumber.Value);
//            else
//                SqlDataAccess.AddInParameter(ctx, command, "ConTel", DbType.AnsiString, DBNull.Value);
//            SqlDataAccess.AddInParameter(ctx, command, "ConTel1Area", DbType.AnsiString, "0");

//            var nPhone2 = nk1.GetPhoneNumber(1);
//            if (null != nPhone2)
//                SqlDataAccess.AddInParameter(ctx, command, "ConTel1", DbType.AnsiString, nPhone2.PhoneNumber.Value);
//            else
//                SqlDataAccess.AddInParameter(ctx, command, "ConTel1", DbType.AnsiString, DBNull.Value);







//            var nAddr = nk1.GetAddress(0);
//            if (null != nAddr)
//                SqlDataAccess.AddInParameter(ctx, command, "ConArea", DbType.AnsiString, nAddr.StreetAddress.StreetName.Value);
//            else
//                SqlDataAccess.AddInParameter(ctx, command, "ConArea", DbType.AnsiString, DBNull.Value);
//            #endregion

//            SqlDataAccess.AddInParameter(ctx, command, "ChartWhere", DbType.AnsiString, "0");          //Todo
//            //SqlDataAccess.AddInParameter(ctx, command, "FirstVisitDate", DbType.DateTime, DateTime.Now);
//            SqlDataAccess.AddInParameter(ctx, command, "FirstVisitDivNo", DbType.Int32, "0");
//            SqlDataAccess.AddInParameter(ctx, command, "NoPromiseCnt", DbType.Int32, "0");
//            //SqlDataAccess.AddInParameter(ctx, command, "NoPromiseDate", DbType.DateTime, DateTime.Now);
//            SqlDataAccess.AddInParameter(ctx, command, "Private", DbType.AnsiString, "");
//            SqlDataAccess.AddInParameter(ctx, command, "AgreeUse", DbType.AnsiString, "");
//            SqlDataAccess.AddInParameter(ctx, command, "BadRecord", DbType.AnsiString, "");
//            //SqlDataAccess.AddInParameter(ctx, command, "LastVisitDate", DbType.DateTime, DateTime.Now);
//            SqlDataAccess.AddInParameter(ctx, command, "EMail", DbType.AnsiString, "");



//            //2016/01/14 杨燕要求Tel1为空时保存Tel2的数据进入Tel1中
//            //家庭电话 
//            var tel1 = pid.GetPhoneNumberHome(0).PhoneNumber.Value;
//            if (string.IsNullOrEmpty(tel1) || tel1.Equals("0"))
//                SqlDataAccess.AddInParameter(ctx, command, "Tel1", DbType.AnsiString, pid.GetPhoneNumberBusiness(0).PhoneNumber.Value);
//            else
//                SqlDataAccess.AddInParameter(ctx, command, "Tel1", DbType.AnsiString, pid.GetPhoneNumberHome(0).PhoneNumber.Value);
//            //单位电话
//            if (string.IsNullOrEmpty(pid.GetPhoneNumberBusiness(0).PhoneNumber.Value))
//                SqlDataAccess.AddInParameter(ctx, command, "Tel2", DbType.AnsiString, string.Empty);
//            else
//                SqlDataAccess.AddInParameter(ctx, command, "Tel2", DbType.AnsiString, pid.GetPhoneNumberBusiness(0).PhoneNumber.Value);


//            //婚姻代码
//            SqlDataAccess.AddInParameter(ctx, command, "Marriage", DbType.AnsiString, pid.MaritalStatus.Identifier.Value);


//            //医保卡号 
//            if (string.IsNullOrEmpty(pid.PatientAccountNumber.ID.Value))
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "CardNo", DbType.AnsiString, "0");
//            }
//            else
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "CardNo", DbType.AnsiString, pid.PatientAccountNumber.ID.Value);
//            }
//            //身分证号
//            SqlDataAccess.AddInParameter(ctx, command, "IdNo", DbType.AnsiString, pid.SSNNumberPatient.Value);


//            #region "地址"


//            var address = pid.GetPatientAddress(0);

//            //工作单位
//            SqlDataAccess.AddInParameter(ctx, command, "UnitAdrDesc", DbType.AnsiString, address.OtherDesignation.Value ?? string.Empty);

//            var Adrtmp = address.StreetAddress.StreetOrMailingAddress.Value;
//            if (string.IsNullOrWhiteSpace(Adrtmp))
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "AdrDesc", DbType.AnsiString, address.OtherDesignation.Value ?? string.Empty);

//            }
//            else
//            //家庭地址
//            SqlDataAccess.AddInParameter(ctx, command, "AdrDesc", DbType.AnsiString, address.StreetAddress.StreetOrMailingAddress.Value ?? string.Empty);


//            ////@家庭地址
//            //SqlDataAccess.AddInParameter(ctx, command, "AdrAreaName", DbType.AnsiString, address.StreetAddress.StreetOrMailingAddress.Value ?? string.Empty);

//            //#region
//            //var csd = pid.BirthPlace.Value;
//            ////出生地 BirthAreaName
//            //if (!string.IsNullOrEmpty(csd))
//            //{
//            //    SqlDataAccess.AddInParameter(ctx, command, "BirthAreaName", DbType.AnsiString, csd); //出生地名称
//            //}
//            //else
//            //{
//            //    SqlDataAccess.AddInParameter(ctx, command, "BirthAreaName", DbType.AnsiString, address.StreetAddress.StreetOrMailingAddress.Value ?? string.Empty); //出生地名称
//            //}

//            #endregion


//            SqlDataAccess.AddInParameter(ctx, command, "CheckUser", DbType.AnsiString, "0");//建档人
//            //SqlDataAccess.AddInParameter(ctx, command, "CheckTime", DbType.DateTime, DateTime.Now);//建档日期
//            SqlDataAccess.AddInParameter(ctx, command, "UpdateUser", DbType.AnsiString, "0");//修改人
//            //SqlDataAccess.AddInParameter(ctx, command, "UpdateTime", DbType.DateTime, DateTime.Now);//修改时间

//            var eg = pid.GetEthnicGroup(0);
//            #region "民族"
//            var mzcoid = eg.Identifier.Value;
//            var mzname = eg.Text.Value;

//            rowTemp = GetDictionView(ctx, "V_Nation").Rows.Cast<DataRow>().Where(n =>
//              StrHelepr.Obj2StrTrim(n["MedCodeID"]) == mzcoid ||
//              StrHelepr.Obj2StrTrim(n["CodeName"]) == mzname).FirstOrDefault();
//            //民族V_Nation
//            if (rowTemp != null)
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "NationNo", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"]));
//                mzname = StrHelepr.Obj2StrTrim(rowTemp["CodeName"]);
//            }
//            else
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "NationNo", DbType.AnsiString, DBNull.Value); //民族V_Nation
//            }

//            SqlDataAccess.AddInParameter(ctx, command, "NationName", DbType.AnsiString, mzname); //民族名称 
//            #endregion

//            SqlDataAccess.AddInParameter(ctx, command, "WorkplaceZipCode", DbType.AnsiString, DBNull.Value); //工作单位邮编




//            SqlDataAccess.AddInParameter(ctx, command, "HomeZipCode", DbType.AnsiString, address.ZipOrPostalCode.Value); //家庭邮编 

//            #region 关系人
//            var nkId = nk1.Relationship.Identifier.Value;
//            var nkText = nk1.Relationship.Text.Value;
//            rowTemp = GetDictionView(ctx, "V_Relationship").Rows.Cast<DataRow>().Where(n =>
//               StrHelepr.Obj2StrTrim(n["MedCodeID"]) == nkId ||
//               StrHelepr.Obj2StrTrim(n["CodeName"]) == nkText).FirstOrDefault();

//            if (rowTemp != null)
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "ConRelationshipNo", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"])); //关系人关系ID V_Relationship
//                nkText = StrHelepr.Obj2StrTrim(rowTemp["CodeName"]);
//            }
//            else
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "ConRelationshipNo", DbType.AnsiString, DBNull.Value); //关系人关系ID V_Relationship
//            }

//            SqlDataAccess.AddInParameter(ctx, command, "ConRelationshipName", DbType.AnsiString, nkText); //关系人关系名称 V_Relationship
//            var gadd = nk1.GetAddress(0);
//            SqlDataAccess.AddInParameter(ctx, command, "ConZipCode", DbType.AnsiString, gadd.ZipOrPostalCode.Value); //关系人邮编

//            #endregion

//            //#region "AdrArea"
//            //var area = address.ZipOrPostalCode.Value;
//            //SqlDataAccess.AddInParameter(ctx, command, "AdrArea", DbType.AnsiString, string.IsNullOrEmpty(address.ZipOrPostalCode.Value) ? "" : address.ZipOrPostalCode.Value);//邮编号
//            //#endregion

//            #region 国籍
//            var gj = pid.Nationality.Identifier.Value;
//            var gjmc = pid.Nationality.Text.Value;

//            rowTemp = GetDictionView(ctx, "V_Nationality").Rows.Cast<DataRow>().Where(n =>
//                StrHelepr.Obj2StrTrim(n["MedCodeID"]) == gj
//              || StrHelepr.Obj2StrTrim(n["CodeName"]) == gjmc).FirstOrDefault();
//            //国籍代码
//            if (rowTemp != null)
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "Nationality", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"]));
//                gjmc = StrHelepr.Obj2StrTrim(rowTemp["CodeName"]);
//            }
//            else
//            {
//                SqlDataAccess.AddInParameter(ctx, command, "Nationality", DbType.AnsiString, DBNull.Value);
//            }
//            //国籍名称 
//            SqlDataAccess.AddInParameter(ctx, command, "NationalityName", DbType.AnsiString, gjmc); //国籍名称

//            #endregion

//            SqlDataAccess.AddInParameter(ctx, command, "IsSigned", System.Data.DbType.String, pid.PatientID.CheckDigit.Value ?? "0");//a05.PID.PatientID.CheckDigit.Value);//是否签约
//            SqlDataAccess.AddInParameter(ctx, command, "IsBlackList", System.Data.DbType.String, pid.GetIdentityReliabilityCode(0).Value); //a05.PID.GetIdentityReliabilityCode(0).Value);//是否为黑名单

//            SqlDataAccess.AddInParameter(ctx, command, "GreenChannelFlag", System.Data.DbType.Int32, pid.PatientID.IdentifierTypeCode.Value ?? "0");

//            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
//            {
//                SqlDataAccess.ExecuteNonQuery(ctx, command);
//                scope.Complete();
//            }

//            #region 家庭地址和工作单位

//            //住院先不处理
//            if (pv1.PatientClass.Value == "I")
//            {

//            }
//            else
//            {
//                try
//                {
//                    var sqlCode = @"SELECT CodeID,Str4 FROM HealthCare.dbo.PublicCode WHERE TypeID = '1008'";
//                    var cmdCode = ctx.DBGetSqlStringCommand(sqlCode);
//                    DataTable dtCode = new DataTable();
//                    dtCode.Load(ctx.DBExecuteReader(cmdCode));

//                    //Patient
//                    var sqlUpdPatient = @" UPDATE  HealthCare.dbo.Patient
//                                    SET    HomeProCode = @HomeProCode ,
//                                           HomeCityCode = @HomeCityCode ,
//                                           HomeDistrictCode = @HomeDistrictCode ,
//                                           HomeAddress = @HomeAddress,
//                                           AdrDesc = @HomeAddress
//                                    WHERE  ChartNo = @ChartNo ";
//                    var cmdPatientUpd = SqlDataAccess.GetSqlStringCommand(ctx, sqlUpdPatient);

//                    var homeAddress = string.Empty;

//                    for (int i = 0; i < pid.PatientAddressRepetitionsUsed; i++)
//                    {
//                        var add = pid.GetPatientAddress(i);
//                        if (add.AddressType.Value == "H") //现住址
//                        {
//                            var pro = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.StateOrProvince.Value));
//                            var city = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.City.Value));
//                            var district = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.OtherDesignation.Value));
//                            homeAddress = add.StreetAddress.StreetOrMailingAddress.Value;

//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeProCode", DbType.AnsiString, pro == null ? string.Empty : StrHelepr.ObjToStr(pro["CodeID"])); //省编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeCityCode", DbType.AnsiString, city == null ? string.Empty : StrHelepr.ObjToStr(city["CodeID"]));//市编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeDistrictCode", DbType.AnsiString, district == null ? string.Empty : StrHelepr.ObjToStr(district["CodeID"])); //县区编码
//                            if (!string.IsNullOrEmpty(homeAddress))
//                            {
//                                SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeAddress", DbType.AnsiString, homeAddress); //详细地址信息
//                            }
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "ChartNo", DbType.AnsiString, pid.PatientID.ID.Value); //ChartNo
//                        }
//                    }

//                    //家庭地址如果为空，则填入工作单位名称 PID-11(n)-8
//                    if (string.IsNullOrEmpty(homeAddress))
//                    {
//                        for (int i = 0; i < pid.PatientAddressRepetitionsUsed; i++)
//                        {
//                            var add = pid.GetPatientAddress(i);
//                            if (add.AddressType.Value == "W") //工作地址
//                            {
//                                homeAddress = add.OtherGeographicDesignation.Value;
//                                SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeAddress", DbType.AnsiString, homeAddress); //详细地址信息
//                            }
//                        }
//                    }
//                    SqlDataAccess.ExecuteNonQuery(ctx, cmdPatientUpd);
//                }
//                catch (Exception ex)
//                {
//                    LogHelper.LogError("更新门诊现住址失败！" + ex.Message + Environment.NewLine + ex.StackTrace);
//                }
//            }

//            #endregion
//        }

        #endregion

        /// <summary>
        /// 修改黑名单和签约
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="m05"></param>
        /// <param name="m01"></param>
//        protected void UpdatePatientBlackListAndSigned(Database ctx, ADT_A05 m05 = null, ADT_A01 m01 = null)
//        {
//            PID pid = null;
//            PV1 pv1 = null;
//            NK1 nk1 = null;
//            if (null != m05)
//            {
//                pid = m05.PID;
//                pv1 = m05.PV1;
//                nk1 = m05.GetNK1(0);
//            }
//            if (null != m01)
//            {
//                pid = m01.PID;
//                pv1 = m01.PV1;
//                nk1 = m01.GetNK1(0);
//            }

//            var sqlPatient = @"     update HealthCare.dbo.Patient  set  
//                                    IsSigned = @IsSigned ,   
//                                    IsBlackList= @IsBlackList       
//                                    where ChartNo=@ChartNo     ";
//            var cmd = ctx.GetSqlStringCommand(sqlPatient);
//            SqlDataAccess.AddInParameter(ctx, cmd, "IsSigned", System.Data.DbType.String, pid.PatientID.CheckDigit.Value ?? "0"); //是否签约
//            SqlDataAccess.AddInParameter(ctx, cmd, "IsBlackList", System.Data.DbType.String, pid.GetIdentityReliabilityCode(0).Value);//是否为黑名单
//            SqlDataAccess.AddInParameter(ctx, cmd, "ChartNo", System.Data.DbType.String, pid.PatientID.ID.Value); //ChartNo
//            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
//            {
//                SqlDataAccess.ExecuteNonQuery(ctx, cmd);
//                scope.Complete();
//            }
//        }


        #region "患者基本信息修改（ADT^A31）"


//        internal void EditNewPatient(Database ctx, PID pid, PV1 pv1, NK1 nk1)
//        {
//            DataRow rowTemp = null;
//            StringBuilder sql2 = new StringBuilder();
//            sql2.AppendLine(" update HealthCare.dbo.Patient set ");
//            var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql2.ToString());

//            #region LastNumber
//            int LastNumberCount = pid.PatientID.ID.Value.Length;
//            sql2.AppendLine(" LastNumber=@LastNumber, ");
//            if (LastNumberCount <= 2)
//            {
//                SqlDataAccess.AddInParameter(ctx, cmd, "LastNumber", DbType.AnsiString, pid.PatientID.ID.Value);
//            }
//            else
//            {
//                string LastNumberSubString = pid.PatientID.ID.Value.Substring(LastNumberCount - 2);
//                SqlDataAccess.AddInParameter(ctx, cmd, "LastNumber", DbType.AnsiString, LastNumberSubString);
//            }
//            #endregion

//            #region "BirthDay"
//            sql2.AppendLine(" BirthDay=@BirthDay, ");
//            //出生日期
//            SqlDataAccess.AddInParameter(ctx, cmd, "BirthDay", DbType.DateTime, pid.DateTimeOfBirth.TimeOfAnEvent.GetAsDate());
//            #endregion

//            #region "Sex"
//            var sex = pid.AdministrativeSex.Value;
//            if (!string.IsNullOrEmpty(sex))
//            {
//                sql2.AppendLine(" Sex=HealthCare.dbo.GetSexCodeIdByHisID(@Sex), ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "Sex", DbType.AnsiString, sex);
//            }
//            #endregion

//            #region "PtType"
//            var PtType = pv1.PatientType.Value; // 费用类别
//            if (!string.IsNullOrEmpty(PtType))
//            {
//                sql2.AppendLine(" PtType=@PtType, ");
//                if (PtType == "01") { PtType = "1"; }
//                else { PtType = "2"; }
//                SqlDataAccess.AddInParameter(ctx, cmd, "PtType", DbType.AnsiString, PtType);
//            }
//            #endregion
//            #region "BirthAreaName"
//            var BirthAreaName = pid.BirthPlace.Value;//出生地
//            if (!string.IsNullOrEmpty(BirthAreaName))
//            {
//                sql2.AppendLine("BirthAreaName=@BirthAreaName,");
//                SqlDataAccess.AddInParameter(ctx, cmd, "BirthAreaName", DbType.AnsiString, BirthAreaName);
//            }

//            #endregion

//            #region "Marriage"

//            var marr = pid.MaritalStatus.Identifier.Value;
//            if (!string.IsNullOrEmpty(marr))
//            {
//                sql2.AppendLine(" Marriage= HealthCare.dbo.GetMarriageCodeIdByHisID(@Marriage), ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "Marriage", DbType.AnsiString, pid.MaritalStatus.Identifier.Value);
//            }

//            #endregion

//            #region "Tel1"

//            var tel1 = pid.GetPhoneNumberHome(0).PhoneNumber.Value;
//            if (!string.IsNullOrEmpty(tel1))
//            {
//                sql2.AppendLine(" Tel1=@Tel1, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "Tel1", DbType.AnsiString, tel1);//家庭电话
//            }
//            #endregion

//            #region "Tel2"
//            var tel2 = pid.GetPhoneNumberBusiness(0).PhoneNumber.Value;
//            if (!string.IsNullOrEmpty(tel2))
//            {
//                sql2.AppendLine("  Tel2=@Tel2, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "Tel2", DbType.AnsiString, tel2);//单位电话
//            }
//            #endregion

//            var address = pid.GetPatientAddress(0);

//            #region "AdrDesc"
//            var addr = address.StreetAddress.StreetOrMailingAddress.Value;
//            if (!string.IsNullOrEmpty(addr))
//            {
//                sql2.AppendLine(" AdrDesc=@AdrDesc, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "AdrDesc", DbType.AnsiString, addr);//家庭地址
//            }
//            else
//            {
//                addr = address.OtherDesignation.Value;//工作单位
//                if (!string.IsNullOrEmpty(addr))
//                {
//                    sql2.AppendLine(" AdrDesc=@AdrDesc, ");
//                    SqlDataAccess.AddInParameter(ctx, cmd, "AdrDesc", DbType.AnsiString, addr);//家庭地址
//                }
//            }

//            #endregion

//            #region "UnitAdrDesc"
//            sql2.AppendLine("UnitAdrDesc=@UnitAdrDesc,");
//            SqlDataAccess.AddInParameter(ctx, cmd, "UnitAdrDesc", DbType.AnsiString, address.OtherDesignation.Value ?? string.Empty);//工作单位
//            #endregion

//            //加入病人姓名 杨燕要求的
//            var ptName = pid.GetPatientName(0).GivenName.Value;
//            if (!string.IsNullOrEmpty(ptName))
//            {
//                sql2.AppendLine("  PtName=@PtName, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "PtName", DbType.AnsiString, ptName);//病人姓名
//            }

//            //#region "AdrArea"
//            //var area = address.ZipOrPostalCode.Value;
//            //if (!string.IsNullOrEmpty(address.ZipOrPostalCode.Value))
//            //{
//            //    sql2.AppendLine("  AdrArea=@AdrArea, ");
//            //    SqlDataAccess.AddInParameter(ctx, cmd, "AdrArea", DbType.Int32, address.ZipOrPostalCode.Value);//邮编号
//            //    //SqlDataAccess.AddInParameter(ctx, command, "AdrArea", DbType.AnsiString, string.IsNullOrEmpty(address.ZipOrPostalCode.Value) ? "" : address.ZipOrPostalCode.Value);//邮编号
//            //}
//            //#endregion

//            #region "CardNo"
//            var cardNo = pid.PatientAccountNumber.ID.Value;
//            if (!string.IsNullOrEmpty(cardNo))
//            {
//                sql2.AppendLine("  CardNo=@CardNo, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "CardNo", DbType.AnsiString, cardNo);//医保卡号
//            }
//            #endregion

//            #region "idNo"
//            var idNo = pid.SSNNumberPatient.Value;
//            if (!string.IsNullOrEmpty(idNo))
//            {
//                sql2.AppendLine("  IdNo=@IdNo, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "IdNo", DbType.AnsiString, idNo);//身分证号 
//            }
//            #endregion



//            //SqlDataAccess.AddInParameter(ctx,command, "FirstVisitDate", DbType.DateTime, DateTime.Now);
//            //SqlDataAccess.AddInParameter(ctx,command, "FirstVisitDivNo", DbType.Int32, "0");
//            //SqlDataAccess.AddInParameter(ctx,command, "NoPromiseCnt", DbType.Int32, "0");
//            //SqlDataAccess.AddInParameter(ctx,command, "NoPromiseDate", DbType.DateTime, DateTime.Now);
//            //SqlDataAccess.AddInParameter(ctx,command, "Private", DbType.AnsiString, "");
//            //SqlDataAccess.AddInParameter(ctx,command, "AgreeUse", DbType.AnsiString, "");
//            //SqlDataAccess.AddInParameter(ctx,command, "BadRecord", DbType.AnsiString, "");

//            sql2.AppendLine("  LastVisitDate=GetDate(), ");
//            //SqlDataAccess.AddInParameter(ctx, cmd, "LastVisitDate", DbType.DateTime, DateTime.Now);

//            #region "民族"
//            var eg = pid.GetEthnicGroup(0);
//            var mzcoid = eg.Identifier.Value;
//            var mzname = eg.Text.Value;
//            if (!string.IsNullOrEmpty(mzcoid) || !string.IsNullOrEmpty(mzname))
//            {
//                rowTemp = GetDictionView(ctx, "V_Nation").Rows.Cast<DataRow>().Where(n =>
//                                                          StrHelepr.Obj2StrTrim(n["MedCodeID"]) == mzcoid ||
//                                                          StrHelepr.Obj2StrTrim(n["CodeName"]) == mzname).FirstOrDefault();
//                //民族V_Nation
//                if (rowTemp != null)
//                {
//                    sql2.AppendLine("  NationNo=@NationNo, ");
//                    SqlDataAccess.AddInParameter(ctx, cmd, "NationNo", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"]));
//                    mzname = StrHelepr.Obj2StrTrim(rowTemp["CodeName"]);
//                }
//                else
//                {
//                    SqlDataAccess.AddInParameter(ctx, cmd, "NationNo", DbType.AnsiString, DBNull.Value); //民族V_Nation
//                }

//                sql2.AppendLine("  NationName=@NationName, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "NationName", DbType.AnsiString, mzname); //民族名称 
//            }

//            #endregion

//            #region 籍贯
//            var sheng = address.StateOrProvince.Value;
//            if (!string.IsNullOrEmpty(sheng))
//            {
//                rowTemp = GetDictionView(ctx, "V_Native").Rows.Cast<DataRow>().Where(n =>
//             StrHelepr.Obj2StrTrim(n["CodeName"]) == sheng).FirstOrDefault();
//                if (rowTemp != null)
//                {
//                    sql2.AppendLine("  NativeNo=@NativeNo, ");
//                    SqlDataAccess.AddInParameter(ctx, cmd, "NativeNo", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"])); //籍贯ID V_Native
//                }
//                sql2.AppendLine("  NativeName=@NativeName, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "NativeName", DbType.AnsiString, sheng); //籍贯名称
//            }

//            #endregion

//            #region "ziocode"
//            var zipcode = address.ZipOrPostalCode.Value;
//            if (!string.IsNullOrEmpty(zipcode))
//            {
//                sql2.AppendLine("  HomeZipCode=@HomeZipCode, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "HomeZipCode", DbType.AnsiString, zipcode); //家庭邮编 
//            }

//            #endregion

//            #region 关系人
//            var nkId = nk1.Relationship.Identifier.Value;
//            var nkText = nk1.Relationship.Text.Value;
//            if (!string.IsNullOrEmpty(nkId) || !string.IsNullOrEmpty(nkText))
//            {
//                rowTemp = GetDictionView(ctx, "V_Relationship").Rows.Cast<DataRow>().Where(n =>
//               StrHelepr.Obj2StrTrim(n["MedCodeID"]) == nkId ||
//               StrHelepr.Obj2StrTrim(n["CodeName"]) == nkText).FirstOrDefault();

//                if (rowTemp != null)
//                {
//                    sql2.AppendLine("  ConRelationshipNo=@ConRelationshipNo, ");
//                    SqlDataAccess.AddInParameter(ctx, cmd, "ConRelationshipNo", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"])); //关系人关系ID V_Relationship
//                    nkText = StrHelepr.Obj2StrTrim(rowTemp["CodeName"]);
//                }
//                sql2.AppendLine("  ConRelationshipName=@ConRelationshipName, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "ConRelationshipName", DbType.AnsiString, nkText); //关系人关系名称 V_Relationship
//            }

//            var gadd = nk1.GetAddress(0);
//            var gzode = gadd.ZipOrPostalCode.Value;
//            if (!string.IsNullOrEmpty(gzode))
//            {
//                sql2.AppendLine("  ConZipCode=@ConZipCode, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "ConZipCode", DbType.AnsiString, gzode); //关系人邮编
//            }


//            #endregion

//            #region "联系人"
//            var lNameP = nk1.GetName(0);
//            var lname = lNameP.GivenName.Value;
//            if (!string.IsNullOrEmpty(lname))
//            {
//                sql2.AppendLine("  ConName=@ConName, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "ConName", DbType.AnsiString, lname);
//            }

//            var lphone = nk1.GetPhoneNumber(0).PhoneNumber.Value;
//            if (!string.IsNullOrEmpty(lphone))
//            {
//                sql2.AppendLine("  ConTel=@ConTel, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "ConTel", DbType.AnsiString, lphone);
//            }


//            var nAddr = nk1.GetAddress(0);
//            if (!string.IsNullOrEmpty(nAddr.StreetAddress.StreetName.Value))
//            {
//                sql2.AppendLine("  ConArea=@ConArea, ");
//                SqlDataAccess.AddInParameter(ctx, cmd, "ConArea", DbType.AnsiString, nAddr.StreetAddress.StreetName.Value);
//            }

//            #endregion


//            #region 国籍
//            var gj = pid.Nationality.Identifier.Value;
//            var gjmc = pid.Nationality.Text.Value;
//            if (!string.IsNullOrEmpty(gj) || !string.IsNullOrEmpty(gjmc))
//            {
//                rowTemp = GetDictionView(ctx, "V_Nationality").Rows.Cast<DataRow>().Where(n =>
//                    StrHelepr.Obj2StrTrim(n["MedCodeID"]) == gj
//                  || StrHelepr.Obj2StrTrim(n["CodeName"]) == gjmc).FirstOrDefault();
//                //国籍代码
//                if (rowTemp != null)
//                {
//                    sql2.AppendLine("  Nationality=@Nationality, ");
//                    SqlDataAccess.AddInParameter(ctx, cmd, "Nationality", DbType.AnsiString, StrHelepr.Obj2StrTrim(rowTemp["CodeID"]));
//                    gjmc = StrHelepr.Obj2StrTrim(rowTemp["CodeName"]);
//                }
//                sql2.AppendLine("  NationalityName=@NationalityName, ");
//                //国籍名称 
//                SqlDataAccess.AddInParameter(ctx, cmd, "NationalityName", DbType.AnsiString, gjmc); //国籍名称
//            }
//            #endregion

//            sql2.AppendLine(" IsSigned=@IsSigned, ");
//            SqlDataAccess.AddInParameter(ctx, cmd, "IsSigned", System.Data.DbType.String, pid.PatientID.CheckDigit.Value ?? "0");//a05.PID.PatientID.CheckDigit.Value);//是否签约
//            sql2.AppendLine(" IsBlackList=@IsBlackList, ");
//            SqlDataAccess.AddInParameter(ctx, cmd, "IsBlackList", System.Data.DbType.String, pid.GetIdentityReliabilityCode(0).Value); //a05.PID.GetIdentityReliabilityCode(0).Value);//是否为黑名单

//            sql2.AppendLine(" GreenChannelFlag=@GreenChannelFlag, ");
//            SqlDataAccess.AddInParameter(ctx, cmd, "GreenChannelFlag", System.Data.DbType.String, string.IsNullOrWhiteSpace(pid.PatientID.IdentifierTypeCode.Value) ? "0" : pid.PatientID.IdentifierTypeCode.Value);//pid.PatientID.IdentifierTypeCode.Value ?? "0");
//            sql2.AppendLine("  UpdateUser=@UpdateUser, ");
//            var UpdateUserID = pv1.GetOtherHealthcareProvider(0).IDNumber.Value; //操作者工号
//            SqlDataAccess.AddInParameter(ctx, cmd, "UpdateUser", DbType.AnsiString, UpdateUserID);//修改人
//            sql2.AppendLine("  UpdateTime=GetDate() ");
//            //SqlDataAccess.AddInParameter(ctx, cmd, "UpdateTime", DbType.DateTime, DateTime.Now);//修改时间


//            #region "ChartNo"
//            sql2.Append("where ChartNo=@ChartNo");
//            SqlDataAccess.AddInParameter(ctx, cmd, "ChartNo", DbType.AnsiString, pid.PatientID.ID.Value); //就诊卡号
//            #endregion

//            cmd.CommandText = sql2.ToString();
//            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
//            {
//                SqlDataAccess.ExecuteNonQuery(ctx, cmd);
//                scope.Complete();
//            }

//            #region 病案首页现住址

//            #region 住院

//            if (pv1.PatientClass.Value == "I")
//            {
//                try
//                {
//                    var sqlCode = @"SELECT CodeID,Str4 FROM HealthCare.dbo.PublicCode WHERE TypeID = '1008'";
//                    var cmdCode = ctx.DBGetSqlStringCommand(sqlCode);
//                    DataTable dtCode = new DataTable();
//                    dtCode.Load(ctx.DBExecuteReader(cmdCode));

//                    //更新病案首页
//                    var sqlUpdAddress = @" UPDATE  HealthCare.dbo.BASY_病人基本信息
//                                    SET    现住址编号_省 = @现住址编号_省 ,
//                                           现住址编号_市 = @现住址编号_市 ,
//                                           现住址编号_县 = @现住址编号_县 ,
//                                           现住址 = @现住址
//                                    WHERE  就诊ID = @就诊ID ";
//                    var cmdAddressUpd = SqlDataAccess.GetSqlStringCommand(ctx, sqlUpdAddress);

//                    //Patient
//                    var sqlUpdPatient = @" UPDATE  HealthCare.dbo.Patient
//                                    SET    HomeProCode = @HomeProCode ,
//                                           HomeCityCode = @HomeCityCode ,
//                                           HomeDistrictCode = @HomeDistrictCode ,
//                                           HomeAddress = @HomeAddress
//                                    WHERE  ChartNo = @ChartNo ";
//                    var cmdPatientUpd = SqlDataAccess.GetSqlStringCommand(ctx, sqlUpdPatient);

//                    for (int i = 0; i < pid.PatientAddressRepetitionsUsed; i++)
//                    {
//                        var add = pid.GetPatientAddress(i);
//                        if (add.AddressType.Value == "H") //现住址
//                        {
//                            var pro = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.StateOrProvince.Value));
//                            var city = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.City.Value));
//                            var district = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.OtherDesignation.Value));

//                            SqlDataAccess.AddInParameter(ctx, cmdAddressUpd, "现住址编号_省", DbType.AnsiString, pro == null ? string.Empty : StrHelepr.ObjToStr(pro["CodeID"])); //省编码
//                            SqlDataAccess.AddInParameter(ctx, cmdAddressUpd, "现住址编号_市", DbType.AnsiString, city == null ? string.Empty : StrHelepr.ObjToStr(city["CodeID"]));//市编码
//                            SqlDataAccess.AddInParameter(ctx, cmdAddressUpd, "现住址编号_县", DbType.AnsiString, district == null ? string.Empty : StrHelepr.ObjToStr(district["CodeID"])); //县区编码
//                            SqlDataAccess.AddInParameter(ctx, cmdAddressUpd, "现住址", DbType.AnsiString, add.StreetAddress.StreetOrMailingAddress.Value); //详细地址信息
//                            SqlDataAccess.AddInParameter(ctx, cmdAddressUpd, "就诊ID", DbType.AnsiString, pv1.VisitNumber.ID.Value); //VisitNo

//                            if (SqlDataAccess.ExecuteNonQuery(ctx, cmdAddressUpd) == 0)
//                            {
//                                #region 旧的调用存储过程的方法，会经常导致超时

//                                //var db = DatabaseFactory.CreateDatabase("HealthCare");
//                                //var conn = db.CreateConnection();
//                                //conn.Open();

//                                //DbCommand cmdAddressInsert = db.GetStoredProcCommand("dbo.AddPtBaseInfoToBASY");
//                                //cmdAddressInsert.Connection = conn;

//                                //var para = cmdAddressInsert.CreateParameter();
//                                //para.ParameterName = "@VisitNo";
//                                //para.DbType = DbType.String;
//                                //para.Value = pv1.VisitNumber.ID.Value;
//                                //cmdAddressInsert.Parameters.Add(para);

//                                //if (cmdAddressInsert.ExecuteNonQuery() > 0)
//                                //{
//                                //    SqlDataAccess.ExecuteNonQuery(ctx, cmdAddressUpd);
//                                //}
//                                //conn.Close();

//                                #endregion

//                                #region SQL

//                                var sqlInsertBASY = @"INSERT  INTO dbo.BASY_病人基本信息
//            ( 病人姓名 ,
//			  住院次数,
//              性别 ,
//              出生日期 ,
//              年龄 ,
//              婚姻 ,
//              职业 ,
//              民族 ,
//              国籍 ,
//              身份证 ,
//              血型 ,
//              工作单位 ,
//              单位电话 ,
//              单位邮编 ,
//              关系人姓名 ,
//              关系 ,
//              关系人地址 ,
//              关系人电话 ,
//              出生地_省市县 ,
//              籍贯省市县 ,
//              现住址 ,
//              现住址电话 ,
//              现住址邮编 ,
//              病历号 ,
//              就诊ID ,
//              院区ID ,
//              主任医生ID ,
//              主治医生ID ,
//              住院医生ID ,
//              实习医生ID ,
//              入院科室 ,
//              入院日期 ,
//              入院床位 ,
//              出院床位 ,
//              出院科室 ,
//              出院日期 ,
//              住院天数 ,
//              当前科室 ,
//              婴儿标志 ,
//              当前病区 ,
//              当前床位 ,
//              身高 ,
//              体重 ,
//              责任护士ID ,
//              责任护士姓名 ,
//			  出生地编号_省,
//			  出生地编号_市,
//			  出生地编号_县,
//			  籍贯编号_省,
//			  籍贯编号_市,
//			  籍贯编号_县, 
//			  现住址编号_省,
//			  现住址编号_市,
//			  现住址编号_县 , 
//			   现住址省市县,
//			  户口地址编号_省,
//			  户口地址编号_市,
//			  户口地址编号_县, 
//			  户口地址省市县,
//			  医生组编号,
//			  户口地址
//            )
//            SELECT  a.PtName ,
//			        b.HospTimes,
//                    a.Sex ,
//                    a.BirthDay ,
//                    dbo.Fun_GetAge(a.BirthDay, b.AdmitTime, b.VisitNo) age ,
//                    a.Marriage ,
//                    a.JobType ,
//                    a.NationNo ,
//                    a.Nationality ,
//                    SUBSTRING(a.IdNo,1,18) ,
//                    CASE WHEN a.BloodType = 'A型' THEN 1
//                         WHEN a.BloodType = 'B型' THEN 2
//                         WHEN a.BloodType = 'O型' THEN 3
//                         WHEN a.BloodType = 'AB型' THEN 4
//                         ELSE 5
//                    END BloodType ,
//                    a.UnitAdrDesc ,
//                    a.Tel2 ,
//                    a.WorkplaceZipCode ,
//                    a.ConName ,
//                    a.ConRelationshipName ,
//                    a.ConArea ,
//                    a.ConTel ,
//                    dbo.GetAddrName(a.BirthAreaNo ) ,
//                   dbo.GetAddrName(a.NativeNo ) ,
//                    a.AdrDesc ,
//                    a.Tel1 ,
//                    a.HomeZipCode ,
//                    a.ChartNo ,
//                    b.VisitNo ,
//                    ISNULL(c.VisitZone, ( SELECT    Zone
//                                          FROM      Employee
//                                          WHERE     EmpNo = b.UpdateUser
//                                        )) Zone ,
//                    b.ChiefDrNo ,
//                    b.DrNo1 ,
//                    b.DrNo3 ,
//                    b.DrNo4 ,
//                    b.AdmissDivNo ,
//                    ( CASE ( SELECT ParamValue
//                             FROM   dbo.SiteParamCtrl
//                             WHERE  SiteNo = '0000'
//                                    AND ParamID = '病案首页_入院日期取入科日期'
//                           )
//                        WHEN 1 THEN (SELECT MIN(ipd.DynamicTime) FROM dbo.InPatientDynamic ipd WHERE ipd.VisitNo = b.VisitNo AND ipd.DynamicType=13)
//                        ELSE AdmitTime
//                      END ) AS AdmitTime ,
//                    AdmissBed ,
//                    ( CASE b.InHospitalStatus
//                        WHEN 0 THEN ''
//                        ELSE  b.BedNo
//                      END ) LeaveBedNo ,
//                    ( CASE b.InHospitalStatus
//                        WHEN 0 THEN ''
//                        ELSE b.DivNo
//                      END ) LeaveDivNo ,
//                    ( CASE ( SELECT ParamValue
//                             FROM   dbo.SiteParamCtrl
//                             WHERE  SiteNo = '0000'
//                                    AND ParamID = '病案首页_出院日期启用预出院日期时间'
//                           )
//                        WHEN 1 THEN b.PreDischargeTime
//                        ELSE DischargeTime
//                      END ) AS LeaveDate ,
//                    b.AdmitDays ,
//                    b.DivNo ,
//                    b.InfantFlag ,
//                    b.DepartNo ,
//                    b.BedNo ,
//                    b.PtHeight ,
//                    b.PtWeight ,
//                    b.DrNo2 , 
//                    dbo.GetEmpName(b.DrNo2),
//					 dbo.GetAddrCode(a.BirthAreaNo,1)  ,
//					 dbo.GetAddrCode(a.BirthAreaNo,2) , 
//					 dbo.GetAddrCode(a.BirthAreaNo,3)  ,
//					 dbo.GetAddrCode(a.NativeNo,1)  ,
//					 dbo.GetAddrCode(a.NativeNo,2) , 
//					 dbo.GetAddrCode(a.NativeNo,3)  ,
//					 dbo.GetAddrCode(a.AdrArea,1)  ,
//					 dbo.GetAddrCode(a.AdrArea,2) , 
//					  dbo.GetAddrCode(a.AdrArea,3)   ,
//					 dbo.GetAddrName(a.AdrArea ),
//					  dbo.GetAddrCode(a.AdrArea,1)  ,
//					 dbo.GetAddrCode(a.AdrArea,2) , 
//					 dbo.GetAddrCode(a.AdrArea,3)  ,
//					 dbo.GetAddrName(a.AdrArea ),
//					 b.MedicalGroupNo,
//					 AdrDesc
//            FROM    dbo.Patient a ,
//                    dbo.InPatient b ,
//                    dbo.VisitRecord c
//            WHERE   a.ChartNo = c.ChartNo
//                    AND b.VisitNo = c.VisitNo
//                    AND b.VisitNo = @VisitNo";

//                                #endregion

//                                var cmdBASY = SqlDataAccess.GetSqlStringCommand(ctx, sqlInsertBASY);
//                                SqlDataAccess.AddInParameter(ctx, cmdBASY, "VisitNo", DbType.AnsiString, pv1.VisitNumber.ID.Value); //VisitNo
//                                SqlDataAccess.ExecuteNonQuery(ctx, cmdBASY);
//                            }

//                            //更新Patient表
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeProCode", DbType.AnsiString, pro == null ? string.Empty : StrHelepr.ObjToStr(pro["CodeID"])); //省编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeCityCode", DbType.AnsiString, city == null ? string.Empty : StrHelepr.ObjToStr(city["CodeID"]));//市编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeDistrictCode", DbType.AnsiString, district == null ? string.Empty : StrHelepr.ObjToStr(district["CodeID"])); //县区编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeAddress", DbType.AnsiString, add.StreetAddress.StreetOrMailingAddress.Value); //详细地址信息
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "ChartNo", DbType.AnsiString, pid.PatientID.ID.Value); //ChartNo
//                            SqlDataAccess.ExecuteNonQuery(ctx, cmdPatientUpd);
//                        }
//                    }
//                }
//                catch (Exception ex)
//                {
//                    LogHelper.LogError("更新现住址失败！" + ex.Message + Environment.NewLine + ex.StackTrace);
//                }
//            }

//            #endregion

//            #region 门急诊

//            else
//            {
//                try
//                {
//                    var sqlCode = @"SELECT CodeID,Str4 FROM HealthCare.dbo.PublicCode WHERE TypeID = '1008'";
//                    var cmdCode = ctx.DBGetSqlStringCommand(sqlCode);
//                    DataTable dtCode = new DataTable();
//                    dtCode.Load(ctx.DBExecuteReader(cmdCode));

//                    //Patient
//                    var sqlUpdPatient = @" UPDATE  HealthCare.dbo.Patient
//                                    SET    HomeProCode = @HomeProCode ,
//                                           HomeCityCode = @HomeCityCode ,
//                                           HomeDistrictCode = @HomeDistrictCode ,
//                                           HomeAddress = @HomeAddress,
//                                           AdrDesc = @HomeAddress
//                                    WHERE  ChartNo = @ChartNo ";
//                    var cmdPatientUpd = SqlDataAccess.GetSqlStringCommand(ctx, sqlUpdPatient);

//                    var homeAddress = string.Empty;

//                    for (int i = 0; i < pid.PatientAddressRepetitionsUsed; i++)
//                    {
//                        var add = pid.GetPatientAddress(i);
//                        if (add.AddressType.Value == "H") //现住址
//                        {
//                            var pro = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.StateOrProvince.Value));
//                            var city = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.City.Value));
//                            var district = dtCode.AsEnumerable().FirstOrDefault(row => StrHelepr.ObjToStr(row["Str4"]) == StrHelepr.ObjToStr(add.OtherDesignation.Value));
//                            homeAddress = add.StreetAddress.StreetOrMailingAddress.Value;

//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeProCode", DbType.AnsiString, pro == null ? string.Empty : StrHelepr.ObjToStr(pro["CodeID"])); //省编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeCityCode", DbType.AnsiString, city == null ? string.Empty : StrHelepr.ObjToStr(city["CodeID"]));//市编码
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeDistrictCode", DbType.AnsiString, district == null ? string.Empty : StrHelepr.ObjToStr(district["CodeID"])); //县区编码
//                            if (!string.IsNullOrEmpty(homeAddress))
//                            {
//                                SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeAddress", DbType.AnsiString, homeAddress); //详细地址信息
//                            }
//                            SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "ChartNo", DbType.AnsiString, pid.PatientID.ID.Value); //ChartNo
//                        }
//                    }

//                    //家庭地址如果为空，则填入工作单位名称 PID-11(n)-8
//                    if (string.IsNullOrEmpty(homeAddress))
//                    {
//                        for (int i = 0; i < pid.PatientAddressRepetitionsUsed; i++)
//                        {
//                            var add = pid.GetPatientAddress(i);
//                            if (add.AddressType.Value == "W") //工作地址
//                            {
//                                homeAddress = add.OtherGeographicDesignation.Value;
//                                SqlDataAccess.AddInParameter(ctx, cmdPatientUpd, "HomeAddress", DbType.AnsiString, homeAddress); //详细地址信息
//                            }
//                        }
//                    }
//                    SqlDataAccess.ExecuteNonQuery(ctx, cmdPatientUpd);
//                }
//                catch (Exception ex)
//                {
//                    LogHelper.LogError("更新门诊现住址失败！" + ex.Message + Environment.NewLine + ex.StackTrace);
//                }
//            }

//            #endregion

//            #endregion

//        }
        //protected void EditNewPatient(Database ctx, ADT_A05 a05)
        //{


        //    PID pid = a05.PID;
        //    PV1 pv1 = a05.PV1;
        //    NK1 nk1 = a05.GetNK1(0);

        //    EditNewPatient(ctx, pid, pv1, nk1);

        //}
        #endregion


        /// <summary>
        /// 获取员工信息
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="empCode"></param>
        /// <returns></returns>
        //protected EmployeeEntity GetEmpNo(Database ctx, string empCode)
        //{
        //    var sql = string.Format("SELECT EmpNo,EmpCode,EmpName,PhoneticName,EngName,IdNo,Sex,Birthday,MobilePhone,Email,HireDate,Zone,DepartNo,WorkDepartNo,EmpType,Title,ChiefNo,SubTel,SimpleTel,Password,PasswordTime,PressCard,ResignDate,Remark,UpdateUser,UpdateTime,Keyword1,Keyword2,Keyword3,UserLevelId,InputCode FROM HealthCare.dbo.Employee WHERE EmpCode='{0}'", empCode);
        //    return SqlDataAccess.ExecuteSqlStringAccessor<EmployeeEntity>(ctx, sql).FirstOrDefault();
        //}



        /// <summary>
        /// 获取参数
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string GetParam(Database ctx, string key)
        {
            try
            {
                var sql = string.Format("SELECT ParamValue FROM  HealthCare.dbo.SiteParamCtrl WHERE SiteNo='0000' AND ParamID='{0}' AND IsDel=0", key);
                var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);
                var obj = SqlDataAccess.ExecuteScalar(ctx, cmd);
                return StrHelepr.Obj2StrTrim(obj);
            }
            catch (Exception ex)
            {
                IL.Common.LogHelper.LogError(string.Format("获取参数错误:{0}  {1}\r\n{2}", key, ex.Message, ex.StackTrace), LogCatagories.MQAccess);
                return string.Empty;
            }

        }

        protected int GetScanTaskCount(string visitNo, string type)
        {
            var sql = "SELECT count(1) FROM dbo.HL7_Scan WITH(NOLOCK) WHERE VisitNo=@VisitNo and TaskType=@TaskType and TaskStatus=1 and UpdateTime>'2023-01-01'";
            var cmd = Scanctx.DBGetSqlStringCommand(sql);
            Scanctx.AddInParameter(cmd, "VisitNo", DbType.String, visitNo);
            Scanctx.AddInParameter(cmd, "TaskType", DbType.String, type);
            var obj = int.Parse(StrHelepr.Obj2StrTrim(Scanctx.DBExecuteScalar(cmd)));
            return obj;
        }

        protected int GetOriginalCount(string VisitNo)
        {
            var sql = "SELECT count(1) FROM dbo.zhuyuan_original WITH(NOLOCK) WHERE patient_zyh=@VisitNo ";
            var cmd = ctx.DBGetSqlStringCommand(sql);
            ctx.AddInParameter(cmd, "VisitNo", DbType.String, VisitNo);
            var obj = int.Parse(StrHelepr.Obj2StrTrim(ctx.DBExecuteScalar(cmd)));
            return obj;
        }
        /// <summary>
        /// 获取急诊病人床位
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="visitNo"></param>
        /// <returns></returns>
        //protected BedEntity GetBed(Database ctx, string roombed, string ward)
        //{
        //    if (string.IsNullOrWhiteSpace(roombed))
        //        return null;

        //    var sql = string.Format("SELECT BedNo,RoomBed,Ward,Zone,DepartNo,StockLoc,OwnDivNo,BedLevel,BedType,LocArea,SexCtrl,IsQuery,IsTaint,IsICU,ChartNo,PtName,VisitNo,UDDTime,ExpandStatus,ReserveNo,BedStatue,Printer1,Printer2,BedItemCode,AddItemCode,InpItemCode,NurseItemCode,DrugItemCode,IsDelete,UpdateUser,UpdateTime,PatientType,RoomNo,BedUseStatus FROM HealthCare.dbo.Bed WHERE RoomBed='{0}' and  Ward='{1}'", roombed, ward);
        //    return SqlDataAccess.ExecuteSqlStringAccessor<BedEntity>(ctx, sql).FirstOrDefault();
        //}
        /// <summary>
        /// 获取床位
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="roomBed"></param>
        /// <returns></returns>
        //protected BedEntity GetBed(Database ctx, string roomBed)
        //{
        //    var sql = string.Format("SELECT BedNo,RoomBed,Ward,Zone,DepartNo,StockLoc,OwnDivNo,BedLevel,BedType,LocArea,SexCtrl,IsQuery,IsTaint,IsICU,ChartNo,PtName,VisitNo,UDDTime,ExpandStatus,ReserveNo,BedStatue,Printer1,Printer2,BedItemCode,AddItemCode,InpItemCode,NurseItemCode,DrugItemCode,IsDelete,UpdateUser,UpdateTime,PatientType,RoomNo,BedUseStatus FROM dbo.Bed WHERE RoomBed='{0}'", roomBed);
        //    return SqlDataAccess.ExecuteSqlStringAccessor<BedEntity>(ctx, sql).FirstOrDefault();
        //}


        //protected InPatientEntity GetInPatient(Database ctx, string visitNo)
        //{
        //    var sql = string.Format("SELECT VisitNo,AdmitTime,CheckInTime,CheckInFlag,Source,LastPtWeight,PtWeight,PtHeight,BMI,WBLoss,IntakeCondition,IsVisit,IsHighRiskFall,IsIllness,NutritionCare,RtnReason,BedNo,DivNo,DepartNo,Diag,DrNo1,DrNo2,DrNo3,DrNo4,PrePayment,LastReportTime,IsPlanDischarge,PreDischargeTime,DischargeTime,DischargeReason,MbdDocNo,DischargeBillNo,NhiAmt,GenAmt,AdmitDays,LinkNo,ChargeStatus,PtMark,PtSourceNo,ChargeUser,ChargeTime,UpdateUser,UpdateTime,RegisterTime,MedicalGroupNo,InHospitalStatus,AdmissDivNo,AdmissDepartNo,AdmissBed,MotherVisitNo,InfantFlag,ChiefDrNo,AdmittedDrNo,HospTimes,OutDirection,OutDiagNo1,OutDiagNo3,OutDiagName3,OutDiagNo2,OutDiagName2,OutDiagName1,DisputeFlag,OldPreDischargeTime FROM HealthCare.dbo.InPatient WHERE VisitNo='{0}'", visitNo);
        //    return SqlDataAccess.ExecuteSqlStringAccessor<InPatientEntity>(ctx, sql).FirstOrDefault();
        //}

    }
}
