using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHapi.Model.V24.Message;
using NHapi.Model.V24.Group;
using NHapi.Model.V24.Segment;
using System.Data.Common;
using System.Transactions;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
using IL.Common;
//using MediII.Adapter.Model.UE;


namespace MediII.Adapter.BizComponent.MFN
{
    /// <summary>
    /// 公用科室
    /// zengfan 2012-09-04
    /// </summary>
    /// <remarks></remarks>
    public class MFN_Z2B_GY_KESHI_ZS : MFNBase
    {
        //数据库连接
        //HealthCareContainer HealthCareContainer = new HealthCareContainer();
        private Database ctx = null;
        public MFN_Z2B_GY_KESHI_ZS(Database dbCtx)
        {
            ctx = dbCtx;
        }
        /// <summary>
        /// 消息处理，入库
        /// zengfan 2012-09-04
        /// </summary>
        /// <param name="message">转化过的强类型消息</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public override int Process(NHapi.Base.Model.IMessage message)
        {
            //IEnumerable<Employee> EmpList = HealthCareContainer.Employee;
            //取得消息类型 MAD新增 MUP更新 MDL删除 "MDC"作废 "MAC"恢复
            string strMsgType;

            MFN_Z2B msg = message as MFN_Z2B;

            using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                for (int i = 0; i < msg.MFRepetitionsUsed; i++)
                {
                    MFN_Z2B_Nofification group = msg.GetMF(i);
                    strMsgType = group.MFE.RecordLevelEventCode.Value;
                    //int KeShiLB;
                    var pkid = StrHelepr.ObjToStrTrim(group.Z2B.KeShiId.Value);
                        string qurysql = "select count(*) from HealthCare.dbo.Division where DivNo=@DivNo";
                        DbCommand command = ctx.GetSqlStringCommand(qurysql.ToString());
                        ctx.AddInParameter(command, "DivNo", System.Data.DbType.String, pkid);
                        int counts = Convert.ToInt32(ctx.ExecuteScalar(command));
                        if (counts == 0)
                        {
                            Division_SyncAdd(group, pkid);//增加
                        }
                        else
                        {
                            if ("MUP" == strMsgType || "MAD" == strMsgType)//修改
                            {
                                string sql2 = @"update HealthCare.dbo.Division 
                                                set  DivName=@DivName,
									                 DivEngName=@DivEngName,
									                 DeptNo=@DeptNo,
									                 UpdateUser=@UpdateUser,
									                 UpdateTime=GETDATE(),
									                 Keyword1=@Keyword1,
									                 Keyword2=@Keyword2,
									                 Keyword3=@Keyword3,
									                 IsIss=@IsIss,
									                 OpdUseType=@OpdUseType,
									                 InpUseType=@InpUseType,
                                                     Zone=@Zone,
                                                     EmgUseType=@EmgUseType,
                                                     DivCode=@DivCode,
                                                     IsVirtual=@IsVirtual,
                                                     IsConsultation=@IsConsultation,
                                                     DivType=@DivType
                                                where DivNo=@DivNo
									                                                ";
                                DbCommand command2 = ctx.GetSqlStringCommand(sql2.ToString());
                                ctx.AddInParameter(command2, "DivNo", System.Data.DbType.AnsiString, pkid);
                                SetDivisionEntity(group.Z2B, ctx, command2);
                                ctx.ExecuteNonQuery(command2);
                            }
                            if ("MDL" == strMsgType)
                            {
                                Division_SyncDel(pkid);
                            }
                        }
                }   
                scope.Complete();
            }
            return 1;
        }

        /// <summary>
        /// 科室新增
        /// </summary> 
        public void Division_SyncAdd(MFN_Z2B_Nofification group, string pkid)
        {
            string sql = @"insert into HealthCare.dbo.Division(DivNo,
                                                                DivCode,
									                            DivName,
									                            DivEngName,
									                            DeptNo,
									                            IsVirtual,
									                            IsConsultation,
									                            DivType,
									                            UpdateUser,
									                            UpdateTime,
									                            Keyword1,
									                            Keyword2,
									                            Keyword3,
									                            IsIss,
									                            OpdUseType,
									                            InpUseType,
									                            EmgUseType,
                                                                 Zone)
							                            VALUES(@DivNo,
                                                                @DivCode,
									                            @DivName,
									                            @DivEngName,
									                            @DeptNo,
									                            @IsVirtual,
									                            @IsConsultation,
									                            @DivType,
									                            @UpdateUser,
									                            GETDATE(),
									                            @Keyword1,
									                            @Keyword2,
									                            @Keyword3,
									                            @IsIss,
									                            @OpdUseType,
									                            @InpUseType,
									                            @EmgUseType,
                                                                @Zone)";
            DbCommand command = ctx.GetSqlStringCommand(sql.ToString());
            ctx.AddInParameter(command, "DivNo", System.Data.DbType.AnsiString, pkid);//部门代号
            SetDivisionEntity(group.Z2B, ctx, command);
            ctx.ExecuteNonQuery(command);
        }
        public void SetDivisionEntity(Z2B seg, Database ctx, DbCommand command)
        {
            //string sql = @"SELECT Zone FROM HealthCare.dbo.HisInfo WHERE HisZone = @HisZone";
            //DbCommand command1 = ctx.GetSqlStringCommand(sql.ToString());
            //ctx.AddInParameter(command1, "HisZone", System.Data.DbType.AnsiString, seg.YuanQu.Identifier.Value);
            //DataTable dt = ctx.ExecuteDataSet(command1).Tables[0];
            //string ZONE = "";
            //if (dt.Rows.Count > 0)
            //{
            //    ZONE = dt.Rows[0]["Zone"].ToString();
            //}

            ctx.AddInParameter(command, "Zone", System.Data.DbType.AnsiString, GetZone(seg.YuanQu.Identifier.Value));

            //ctx.AddInParameter(command, "keshiid", System.Data.DbType.AnsiString, seg.  KeShiId.Value);
            ctx.AddInParameter(command, "DivCode", System.Data.DbType.AnsiString, seg.KeShiBm.Value);              //科别代码
            ctx.AddInParameter(command, "DeptNo", System.Data.DbType.AnsiString, "");//seg.ShangJiKs.Identifier.Value);  //科别代号
            ctx.AddInParameter(command, "DivName", System.Data.DbType.AnsiString, seg.KeShiMc.Value);              //科别名称
            //ctx.AddInParameter(command, "keshibm", System.Data.DbType.AnsiString, seg.KeShiBm.Value);
            //ctx.AddInParameter(command, "weizhism", System.Data.DbType.AnsiString, seg.WeiZhiSm.Value);
            //wuchengwu 0904 不再更新renshiks数据
            ctx.AddInParameter(command, "DivEngName", System.Data.DbType.AnsiString, seg.YingWenMing.Value);    //英文名
            ctx.AddInParameter(command, "IsVirtual", System.Data.DbType.Int16, 0);                             //是否为虚拟科别
            ctx.AddInParameter(command, "IsConsultation", System.Data.DbType.Int16, 1);                          //是否可会诊
            ctx.AddInParameter(command, "DivType", System.Data.DbType.Int16, seg.KeShiLB.Value);                 //科别类型
            //ctx.AddInParameter(command, "lianxidh", System.Data.DbType.AnsiString, seg.LianXiDh.PhoneNumber.Value);
            //ctx.AddInParameter(command, "hesuanks", System.Data.DbType.AnsiString, seg.HeSuanKs.Identifier.Value);
            //ctx.AddInParameter(command, "chengbenks", System.Data.DbType.AnsiString, seg.ChengBenKs.Identifier.Value);
            //wuchengwu 0904 不再更新renshiks数据
            //ctx.AddInParameter(command, "renshiks", System.Data.DbType.AnsiString, seg.RenShiKs.Identifier.Value);
            ctx.AddInParameter(command, "EmgUseType", System.Data.DbType.Int16, seg.JiZhenSyBz.Value == "1" ? (short)1 : (short)0); //11.04

            //根据Division表的急诊标志，修改HealthCare.dbo.OpdRoomSet表的LocArea标志

            int _EmgUseType = seg.JiZhenSyBz.Value == "1" ? (short)1 : (short)0;
            string _SQL = "select LocArea from HealthCare.dbo.OpdRoomSet where DivNo = @_DivNo";
            DbCommand comd = ctx.GetSqlStringCommand(_SQL.ToString());
            ctx.AddInParameter(comd, "_DivNo", System.Data.DbType.AnsiString, seg.KeShiId.Value);
            DataTable dt2 = ctx.ExecuteDataSet(comd).Tables[0];
            string _LocArea = "";
            if (dt2.Rows.Count > 0)
            {
                _LocArea = dt2.Rows[0]["LocArea"].ToString();

                if (1 == _EmgUseType)
                {
                    string _LocArea2 = "E00";
                    if (_LocArea != "E00")
                    { AlertLocArea(_LocArea2, seg.KeShiId.Value); }
                }
                else if (0 == _EmgUseType)
                {
                    string _LocArea2 = "O00";
                    if (_LocArea != "O00")
                    { AlertLocArea(_LocArea2, seg.KeShiId.Value); }
                }
            }

            ctx.AddInParameter(command, "OpdUseType", System.Data.DbType.Int16, seg.MenZhenSyBz.Value == "1" ? (short)1 : (short)0);
            ctx.AddInParameter(command, "InpUseType", System.Data.DbType.Int16, seg.ZhuYuanSyBz.Value == "1" ? (short)1 : (short)0);
            //wuchengwu 0904 不再更新jizhenbz数据
            //ctx.AddInParameter(command, "jizhenbz", System.Data.DbType.Int16, seg.JiZhenSyBz.Value == "1" ? (short)1 : (short)0);

            ctx.AddInParameter(command, "IsIss", System.Data.DbType.Int16, 0);//seg.ZuoFeiBZ.Value == "1" ? (short)1 : (short)0);  //是否IIS分数（病人注记中）
            //ctx.AddInParameter(command, "shangjiywks", System.Data.DbType.AnsiString, seg.ShangJiKs.Identifier.Value);

            string SHURUMA1 = string.Empty;
            string SHURUMA2 = string.Empty;
            string SHURUMA3 = string.Empty;
            for (int i = 0; i < seg.ShuRuMaRepetitionsUsed; i++)
            {
                NHapi.Model.V24.Datatype.CE shuRuMa = seg.GetShuRuMa(i);
                if (SHURUMA1 == string.Empty)
                {
                    SHURUMA1 = string.IsNullOrEmpty(shuRuMa.Text.Value) ? MFNBase.GetInputCode(0, seg.KeShiMc.Value) : shuRuMa.Text.Value;
                    continue;
                }
                if (SHURUMA2 == string.Empty)
                {
                    SHURUMA2 = string.IsNullOrEmpty(shuRuMa.Text.Value) ? MFNBase.GetInputCode(1, seg.KeShiMc.Value) : shuRuMa.Text.Value;
                    continue;
                }
                if (SHURUMA3 == string.Empty)
                {
                    SHURUMA3 = shuRuMa.Text.Value;
                    continue;
                }
            }
            ctx.AddInParameter(command, "Keyword1", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA1) ? MFNBase.GetInputCode(0, seg.KeShiMc.Value) : SHURUMA1.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "Keyword2", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA2) ? MFNBase.GetInputCode(1, seg.KeShiMc.Value) : SHURUMA2.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "Keyword3", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA3) ? "" : SHURUMA3.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "UpdateUser", System.Data.DbType.AnsiString, seg.XiuGaiRen.IDNumber.Value);
            ctx.AddInParameter(command, "UpdateTime", System.Data.DbType.DateTime, seg.XiuGaiSJ.TimeOfAnEvent.GetAsDate());
        }



        /// <summary>
        /// 部门新增
        /// </summary>
        /// <param name="seg"></param>
        /// <param name="HealthCareContainer"></param>
        /// <param name="scope"></param>

       


        /// <summary>
        /// 科室删除
        /// </summary>
        /// <param name="seg">传入资料</param>
        /// <param name="HealthCareContainer">连线</param>
        /// <param name="scope">交易</param>
        public void Division_SyncDel(string pkid)
        {
            //string sql4 = "update HealthCare.dbo.Division set IsIss=1 where DivNo=@DivNo";
            string sql4 = "delete from HealthCare.dbo.Division where DivNo=@DivNo";
            DbCommand command4 = ctx.GetSqlStringCommand(sql4.ToString());
            ctx.AddInParameter(command4, "DivNo", System.Data.DbType.AnsiString, pkid);
            ctx.ExecuteNonQuery(command4);
        }


      
        public void AlertLocArea(string LocArea, string KeShiID)
        {
            if (!string.IsNullOrEmpty(LocArea) && !string.IsNullOrEmpty(KeShiID))
            {
                string sql = "update HealthCare.dbo.OpdRoomSet set LocArea = @LocArea where DivNo=@Loc_DivNo";
                DbCommand command = ctx.GetSqlStringCommand(sql.ToString());
                ctx.AddInParameter(command, "LocArea", System.Data.DbType.AnsiString, LocArea);
                ctx.AddInParameter(command, "Loc_DivNo", System.Data.DbType.AnsiString, KeShiID);
                ctx.ExecuteNonQuery(command);
            }
        }


        private string GetZone(string value)
        {
            string sql = @"SELECT Zone FROM HealthCare.dbo.HisInfo WHERE HisZone = @HisZone";
            DbCommand 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;
        }

    }
}
