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.ReceiveToScanModel;

namespace MediII.Adapter.BizComponent.ADT
{
    /// <summary>
    /// 
    /// </summary>
    public abstract class ADTHandler
    {
        static readonly string SEDING_APPLICATION = System.Configuration.ConfigurationManager.AppSettings["SedingApplication"];
        //数据库连接
        protected Database ctx;
        /// <summary>
        /// 
        /// </summary>
        public ADTHandler()
        {
            DatabaseProviderFactory factory = new DatabaseProviderFactory();
            ctx = 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": return new ADT_A01_Handler();// 住院患者
                    case "ADT^A02": return new ADT_A02_Handler();//住院更新
                    case "ADT^A05": return new ADT_A05_Handler();//门诊患者更新
                    case "ADT^A04": return new ADT_A04_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);

        #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);
        }

  







        /// <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 = ctx.DBGetSqlStringCommand(sql);
            ctx.AddInParameter(cmd, "VisitNo", DbType.String, visitNo);
            ctx.AddInParameter(cmd, "TaskType", DbType.String, type);
            var obj = int.Parse(StrHelepr.Obj2StrTrim(ctx.DBExecuteScalar(cmd)));
            return obj;
        }
    }
}
