using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using MediII.Adapter.BaseBiz;
using System.Data.Common;
using System.Transactions;
using Microsoft.Practices.EnterpriseLibrary.Data;
//using MediII.Adapter.Model.UE;
using System.Globalization;
using MediII.Adapter.BizComponent.Base;
using IL.Common;
using System.Xml;

namespace MediII.Adapter.BizComponent.PMU
{
    public class BizComponent_PMU : BaseBizComponent, IBizComponent
    {
        const string Insert = "B01"; //增加个人纪录
        //const string Update = "B02"; //更新个人记录
        //const string Delete = "B03"; //删除个人记录
        //数据库连接
        protected Database ctx
        {
            get { return base.HealthCarectx; }
        }
        public BizComponent_PMU()
        {

        }
        ////HealthCareContainer HealthCareContainer = new HealthCareContainer();
        //private Database ctx = null;
        //public BizComponent_PMU(Database dbCtx)
        //{
        //    ctx = dbCtx;
        //}
        public override string DoProcess(string m, string msgType)
        {
            string strMsgType = null;
            //try
            //{
            //try
            // {
            //取得消息类型 MAD新增 MUP更新 MDL删除 "MDC"作废 "MAC"恢复
            OperateXmlUtil helper = new OperateXmlUtil();
            string qurysql = "select count(*) from his_doct where DOCT_CODE=?DOCT_CODE";
            DbCommand command = ctx.GetSqlStringCommand(qurysql.ToString());
            string pkid = helper.XpathRead(m, "//*[@root='2.16.156.10011.1.4']", "extension");
            ctx.AddInParameter(command, "DOCT_CODE", System.Data.DbType.String, pkid);
            int counts = Convert.ToInt32(ctx.ExecuteScalar(command));


            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                //for (int i = 0; i < pmuB01.EDURepetitionsUsed; i++)
                //{ 
                if (counts == 0)
                {
                    //没有查询到记录则新增，否则修改
                    AddData(m, pkid);
                }
                else
                {
                    UpDateData(m, pkid);
                }



                scope.Complete();
            }
            return string.Empty;
        }
        public void AddData(string message, string id)
        {
            #region 新增
            string sql = @"INSERT INTO his_doct
                                    ( DOCT_CODE ,
                                    DOCT_NAME
                                    )
                            VALUES  ( ?DOCT_CODE,
                                    ?DOCT_NAME)";
            DbCommand command = ctx.GetSqlStringCommand(sql.ToString());

            SetEntity(message, command, id);
            MySqlDataAccess.ExecuteNonQuery(ctx, command);
            #endregion
        }
        public void UpDateData(string message, string id)
        {
            #region 修改
//            string sql1 = @"update his_doct set 
//                                    DOCT_NAME =?DOCT_NAME,
//                                    HIS_DEPT_CODE =?HIS_DEPT_CODE,
//                                    HIS_DEPT_NAME =?HIS_DEPT_NAME,
//                                    status=?status
//                                where DOCT_CODE=?DOCT_CODE";
            string sql1 = @"update his_doct set 
                                    DOCT_NAME =?DOCT_NAME
                                where DOCT_CODE=?DOCT_CODE";
            DbCommand command1 = ctx.GetSqlStringCommand(sql1.ToString());

            SetEntity(message, command1, id);
            MySqlDataAccess.ExecuteNonQuery(ctx, command1);
            #endregion
        }

        public void SetEntity(string message, DbCommand command, string id)
        {
            string value = string.Empty;
            OperateXmlUtil xmlHelper = new OperateXmlUtil();

            ctx.AddInParameter(command, "DOCT_CODE", System.Data.DbType.String, id);
            var valueNode = xmlHelper.XpathRead(message, "//*[name()='healthCarePrincipalPerson']").Item(0);

            foreach (XmlNode xe in valueNode.ChildNodes)
            {
                if (xe.Name == "name")
                {
                    value = xe.LastChild.LastChild.Attributes["value"].Value;
                    ctx.AddInParameter(command, "DOCT_NAME", System.Data.DbType.String, value);

                    break;
                }
            }

            value = xmlHelper.XpathRead(message, "//*[@root='2.16.156.10011.1.26']", "extension");
            ctx.AddInParameter(command, "HIS_DEPT_CODE", System.Data.DbType.AnsiString, value);

            valueNode = xmlHelper.XpathRead(message, "//*[name()='affiliatedPrincipalOrganization']").Item(0);
            foreach (XmlNode xe in valueNode.ChildNodes)
            {
                if (xe.Name == "name")
                {
                    value = xe.LastChild.LastChild.Attributes["value"].Value;
                    ctx.AddInParameter(command, "HIS_DEPT_NAME", System.Data.DbType.String, value);

                    break;
                }
            }
            ctx.AddInParameter(command, "status", System.Data.DbType.String, "在用");
            //ctx.ExecuteNonQuery(command);
        }
      





        ///// <summary>
        ///// 获取当前时间
        ///// </summary> 
        //internal DateTime GetNow(Database ctx)
        //{ 
        //    object obj = (DateTime)MySqlDataAccess.ExecuteScalar(ctx, CommandType.Text, "select GETDATE()");
        //    if (obj != null)
        //        return Convert.ToDateTime(obj.ToString());
        //    else
        //        return DateTime.Now;
        //}

        //获取性别，转化
        public string GetSex(string value)
        {
            string sex = "0";
            switch (value)
            {
                case "F":
                    sex = "1";//男
                    break;
                case "男":
                    sex = "1";//男
                    break;
                case "M":
                    sex = "2";//女
                    break;
                case "女":
                    sex = "2";//女
                    break;
                default:
                    sex = "9";//不定
                    break;
            }
            return sex;
        }
        public string GetYsdj(string hiscodeid)
        {
            var sql = "SELECT CodeID FROM HealthCare.dbo.V_UserLevel WHERE HisCodeID=@HisCodeID";
            var cmd = MySqlDataAccess.GetSqlStringCommand(ctx, sql);
            MySqlDataAccess.AddInParameter(ctx, cmd, "HisCodeID", DbType.AnsiString, hiscodeid);
            string codeid = StrHelepr.Obj2StrTrim(MySqlDataAccess.DBExecuteScalar(ctx, cmd));
            if (codeid != null)
            {
                return codeid;
            }
            else
            {
                throw new Exception("V_UserLevel没有找到对应的医生等级");
            }

        }
        public string GetEmpType(string value)
        {
            string emptype = "";
            switch (value) // 员工分类
            {
                case "1"://1	医生
                    emptype = "1";
                    break;
                case "2"://2	护士
                    emptype = "2";
                    break;
                case "3"://3	财务人员
                    emptype = "3";
                    break;
                case "4"://4	药剂人员
                    emptype = "4";
                    break;
                case "5"://5	技师（检验）
                    emptype = "5";
                    break;
                case "6"://6	技师（影像）
                    emptype = "6";
                    break;
                case "7"://7	管理人员
                    emptype = "7";
                    break;
                case "8"://8	其他卫生技术人员
                    emptype = "8";
                    break;
                case "9"://9	其他人员
                    emptype = "9";
                    break;
            }
            return emptype;
        }

    }

}
#region 此为老版本代码
/*
Employee Module_Employee = new Employee();

strMsgType = pmuB01.EVN.EventTypeCode.Value;

#region STG
STF stf = pmuB01.STF;

Module_Employee.EmpNo = Convert.ToInt16(stf.PrimaryKeyValueSTF.Identifier.Value);// 员工代号
Module_Employee.EmpCode = stf.GetStaffIDCode(0).ID.Value;// 员工代码
Module_Employee.EmpName = stf.GetStaffName(0).GivenName.Value;// 姓名
Module_Employee.EngName = stf.GetStaffName(0).GivenName.Value;// 英文姓名
Module_Employee.IdNo = stf.DriverSLicenseNumberStaff.DriverSLicenseNumber.Value.Trim() ;// 身份证号 <<<<<<<<<<<<<<<<<<<<<< 目前ISNULL

#region 性别转换
// 1:男 2:女
Module_Employee.Sex = His.MediIITransfer.MediII2Ue.GetSex(stf.AdministrativeSex.Value);
#endregion

Module_Employee.Birthday = His.Time.TryParseExact(stf.DateTimeOfBirth.TimeOfAnEvent.Value, "yyyyMMddhhmmss");

#region 婚姻状况
// 婚姻状况 (0:未婚,1:已婚,2:离婚)
switch (stf.MaritalStatus.Text.Value)
{
    case "S"://S	独身
    case "P"://P	同性恋
    case "G"://G	同居
    case "B"://B	未婚
    case "U"://U	未知
    case "O"://O	其他
    case "T"://T	未报告
        Module_Employee.MaritalStatus = "0";
        break;
    case "M"://M	结婚
    case "A":  //A	分居
    case "W"://W	丧偶
    case "R"://R	已登记同性恋
    case "E"://E	合法分居
    // case "C"://C	普通法律
    case "I"://I	诉讼中
        Module_Employee.MaritalStatus = "1";
        break;

    case "D"://D	离婚
        Module_Employee.MaritalStatus = "2";
        break;
    default:
        Module_Employee.MaritalStatus = "0";
        break;
}
#endregion

Module_Employee.HomeAdrArea = 0;// 住处区域代码 <<<<<<<<<<<<<<<<<<<<<<<<<<<
Module_Employee.HomeAdrDesc = stf.GetOfficeHomeAddress(0).StreetAddress.StreetOrMailingAddress.Value;// 住处地址
Module_Employee.HomeTel1 = stf.GetPhone(0).PhoneNumber.Value;// 住处电话1
Module_Employee.HomeTel2 = "0"; // 住处电话2(不同步)

Module_Employee.MobilePhone = stf.GetPhone(0).PhoneNumber.Value; // 移动电话

Module_Employee.NativeAdrArea = 0;// 户籍区域代码(不同步)
Module_Employee.NativeAdrDesc = "";// 户籍地址(不同步)
Module_Employee.NativeTel = "";// 户籍电话(不同步)

Module_Employee.ConName = "";// 联系人姓名（不同步）
Module_Employee.ConTel1 = "";// 络人电话（不同步）
Module_Employee.ConTel2 = "";// 络人电话（不同步）

Module_Employee.ConAdrArea = 0;// 联系人区域代码（不同步）
Module_Employee.ConAdrDesc = "";// 联系人地址（不同步）

Module_Employee.Affiliation = "";// 与联系人关系(不同步)

try
{
     string sHireDate =stf.GetInstitutionActivationDate(0).Date.TimeOfAnEvent.Value;
    DateTime dtHireDate = His.Time.TryParseExact(sHireDate, "yyyyMMddhhmmss");

    Module_Employee.HireDate = dtHireDate == His.Time.MaxDateTime ? Convert.ToDateTime("1911-01-01 00:00:00") : dtHireDate; // 到职日期

}
catch
{
    Module_Employee.HireDate = Convert.ToDateTime("1911-01-01 00:00:00");
}
               
Module_Employee.Zone = "A";// 归属院区(联众会开栏位**********)<<<<<<<<<<<<<<<<<<<<<<

string tmp = stf.GetDepartment(0).Identifier.Value;

try
{
    string sDepartNo = His.MediIITransfer.MediII2Ue.GetDepartNo(stf.GetDepartment(0).Identifier.Value);
    Module_Employee.DepartNo = Convert.ToInt16(sDepartNo);// 部门代码
}
catch (Exception ex)
{
    Module_Employee.DepartNo = -1;
}

Module_Employee.EmpType = stf.GetStaffType(0).Value;

#region 员工分类

switch (stf.GetStaffType(0).Value) // 员工分类
{
    case "1"://1	医生
        Module_Employee.EmpType = "1";
        break;
    case "2"://2	护士
        Module_Employee.EmpType = "2";
        break;
    case "3"://3	财务人员
        Module_Employee.EmpType = "3";
        break;
    case "4"://4	药剂人员
        Module_Employee.EmpType = "4";
        break;
    case "5"://5	技师（检验）
    case "6"://6	技师（影像）
    case "7"://7	管理人员
    case "8"://8	其他卫生技术人员
    case "9"://9	其他人员
        Module_Employee.EmpType = "0";
        break;
}
#endregion
string tmp2 = stf.JobCodeClass.JobCode.Value;

try
{
    Module_Employee.Title = Convert.ToInt16(stf.JobCodeClass.JobCode.Value);// 职称
}
catch (Exception ex)
{
    Module_Employee.Title = -1;
}


Module_Employee.ChiefNo = Convert.ToInt16(stf.GetHospitalService(0).Identifier.Value);// 职位
string tmp3 = stf.GetDepartment(0).Identifier.Value;

try
{
    string sWorkDepartNo = His.MediIITransfer.MediII2Ue.GetDepartNo(stf.GetDepartment(0).Identifier.Value);
    Module_Employee.WorkDepartNo = Convert.ToInt16(sWorkDepartNo);// 工作单位代号  <<<<<<<<<<<<<

}
catch
{
    Module_Employee.WorkDepartNo = -1;
}

Module_Employee.SimpleTel = stf.GetPhone(0).PhoneNumber.Value;// 速拨码
Module_Employee.SubTel = stf.GetPhone(0).PhoneNumber.Value;// 分机

string sPassword = stf.GetBackupPersonID(0).Identifier.Value;

Module_Employee.Password = sPassword == null ? "" : sPassword;
Module_Employee.PasswordTime = DateTime.Now; // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Module_Employee.PressCard = 0;// 工作卡号(暫時不填)


string  sActiveInactiveFlag = stf.ActiveInactiveFlag.Value; // A,在职;I,离职
Module_Employee.ResignDate = sActiveInactiveFlag == "A" ? His.Time.MaxDateTime : His.Time.MaxDateTime; 

int iIntParse;
int.TryParse(stf.PreferredMethodOfContact.Identifier.Value, out iIntParse);
if (iIntParse != 0)
{
    Module_Employee.UpdateUser = Convert.ToInt16(iIntParse);// 最后修改人
}

Module_Employee.UpdateTime = DateTime.Now;

Module_Employee.EMail = "";// 电子信箱(不同步)

Module_Employee.Remark = "";// 备注说明(不同步)

Module_Employee.Team = 0;// 组别

#endregion

#region 測試

string sErrMsg;
if (string.IsNullOrEmpty(Module_Employee.IdNo))
{
    sErrMsg = "【身份证】无法为空";
    SetACK(m, "ACK", strMsgType, "ACK", sErrMsg);
}

if (string.IsNullOrEmpty(Module_Employee.HomeAdrDesc))
{
    Module_Employee.HomeAdrDesc = "";
}

if (string.IsNullOrEmpty(Module_Employee.HomeTel1))
{
    Module_Employee.HomeTel1 = "";
}

if (string.IsNullOrEmpty(Module_Employee.HomeTel1))
{
    Module_Employee.HomeTel1 = ""; // 住处电话1
}

if (string.IsNullOrEmpty(Module_Employee.MobilePhone))
{
    Module_Employee.MobilePhone = ""; // 移动电话1
}

if (string.IsNullOrEmpty(Module_Employee.MobilePhone))
{
    Module_Employee.MobilePhone = ""; // 移动电话1
}


//Module_Employee.HireDate = His.Time.TryParseExact(sHireDate, "yyyyMMdd"); // 到职日期
//Module_Employee.Title = Convert.ToInt16(stf.JobCodeClass.JobCode.Value);// 职称

//Module_Employee.ChiefNo = Convert.ToInt16(stf.GetHospitalService(0).Identifier.Value);// 职位

if (string.IsNullOrEmpty(Module_Employee.MobilePhone))
{
    Module_Employee.SimpleTel = "";// 速拨码
}

if (string.IsNullOrEmpty(Module_Employee.MobilePhone))
{
    Module_Employee.SubTel = "";// 分机
}

if (string.IsNullOrEmpty(Module_Employee.Password))
{
    sErrMsg = "【密碼】无法为空";
    SetACK(m, "ACK", strMsgType, "ACK", sErrMsg);
}

//if (Module_Employee.HireDate == DateTime.MinValue)
//{
//    Module_Employee.HireDate = His.Time.MaxDateTime;
//}
if (Module_Employee.PasswordTime == DateTime.MinValue)
{
    Module_Employee.PasswordTime = His.Time.MaxDateTime;
}
if (Module_Employee.UpdateTime == DateTime.MinValue)
{
    Module_Employee.UpdateTime = His.Time.MaxDateTime;
}

if (Module_Employee.ResignDate == DateTime.MinValue)
{
    Module_Employee.ResignDate = His.Time.MaxDateTime;
}


//Module_Employee.ResignDate = His.Time.TryParseExact(sResignDate, "yyyyMMdd"); // 离职日期
#endregion


// 開始存入資料庫
int iEmpNo = Convert.ToInt16(stf.PrimaryKeyValueSTF.Identifier.Value);// 员工代号
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
    switch (strMsgType)
    {
        case Insert:
        case Update:
            EmployeeDelete(iEmpNo, ref HealthCareContainer, scope, ref Module_Employee);
            EmployeeInsert(iEmpNo, ref HealthCareContainer, scope, ref Module_Employee);
            break;
        case Delete:
            EmployeeDelete(iEmpNo, ref HealthCareContainer, scope, ref Module_Employee);
            break;
    }

    #region 存入資料庫

    try
    {
        HealthCareContainer.SaveChanges();
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
    {
        scope.Dispose();
        throw ex;
    }
    #endregion

    scope.Complete();


}
*/
//        return string.Empty;

//    }
//    catch (Exception ex)
//    {
//        string errMsg = string.Empty;
//        if (ex.InnerException == null)
//        {
//            errMsg = ex.Message + "\r\n" + ex.StackTrace;
//        }
//        else
//        {
//            errMsg = ex.Message + "\r\n" + ex.InnerException.Message + "\r\n" + ex.InnerException.StackTrace;
//        }
//        return errMsg;
//    }
//}
// catch (System.Data.Entity.Validation.DbEntityValidationException ex)
//{
//var tmp = ex.EntityValidationErrors.FirstOrDefault().ValidationErrors;
//string errString = "";
//foreach (var item in tmp)
//{
//    errString += item.ErrorMessage;
//}
//string ack = SetACK(m, "ACK", mType, "ACK", ex.EntityValidationErrors.ToString());
//throw new Exception(string.Format("{0}\r\n{1}", ex.EntityValidationErrors.ToString()));

//return ex.Message;
//}
//}


/*

public void EmployeeInsert(int iEmpNo, ref HealthCareContainer HealthCareContainer, TransactionScope scope, ref Employee Module_Employee)
{
    try
    {
        HealthCareContainer.Employee.Add(Module_Employee);

    }
    catch (Exception ex)
    {
        scope.Dispose();
        throw ex;
    }
}

public void EmployeeDelete(int iEmpNo, ref HealthCareContainer HealthCareContainer, TransactionScope scope, ref Employee Module_Employee)
{
    try
    {
        IEnumerable<Employee> EmployeeList = HealthCareContainer.Employee.Where(x => x.EmpNo == iEmpNo);
        if (EmployeeList.Count() != 0)
        {
            Employee Module_Employee_Del = EmployeeList.FirstOrDefault();
            HealthCareContainer.Employee.Remove(Module_Employee_Del);
            HealthCareContainer.SaveChanges();
        }

    }
    catch (Exception ex)
    {
        scope.Dispose();
        throw ex;
    }
}
*/
// }
//}
#endregion