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[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^A03": return new ADT_A03_Handler();//患者出院信息
                    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^A08[B01]": return new ADT_A08B01_Handler();//门急诊诊断信息
                    case "ADT^A08[B02]": return new ADT_A08B02_Handler();//住院诊断信息
                    case "ADT^A31": return new ADT_A31_Handler();//患者基本信息
                    case "ADT^A90": return new ADT_A90_Handler();//病案首页信息
                    case "ADT^A91": return new ADT_A91_Handler();//发票金额
                    case "ADT^A92": return new ADT_A92_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(TaskMessage 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 = MySqlDataAccess.GetSqlStringCommand(ctx, sql);
            ntb.Load(MySqlDataAccess.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 = MySqlDataAccess.GetSqlStringCommand(ctx, sql);
            var val = StrHelepr.Obj2StrTrim(MySqlDataAccess.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 = MySqlDataAccess.GetSqlStringCommand(ctx, sql);
            object obj = MySqlDataAccess.ExecuteScalar(ctx, cmd);
            if (obj != null)
                return obj.ToString();
            else
                return "0";
        }
        #endregion

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

            object obj = (DateTime)MySqlDataAccess.ExecuteScalar(ctx, CommandType.Text, "select SYSDATE()");
            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 = MySqlDataAccess.GetSqlStringCommand(ctx, sql);

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

            MySqlDataAccess.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 = MySqlDataAccess.GetSqlStringCommand(ctx, sql);
                var obj = MySqlDataAccess.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 HL7_Scan 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;
        }

        protected void SetNextTask(TaskMessage msg)
        {
            var sql = string.Format(@"INSERT INTO TaskMessage(TaskID, VisitNo, TaskType, TypeName, TaskStatus, Parameter1, Parameter2, Parameter3, ErrMsg, ErrNm, 
TaskTime, Reserve1, Reserve2, Reserve3) VALUES(MD5(UUID()),null,'{0}','{1}',1,'{2}','{3}','{4}',null,0,'{5}',null,null,'{6}')",
            msg.TaskType, msg.TypeName, msg.Parameter1, msg.Parameter2, int.Parse(msg.Parameter3) + 1, msg.TaskTime,
            msg.Reserve3);
            var cmd = ctx.DBGetSqlStringCommand(sql);
            ctx.DBExecuteNonQuery(cmd);
        }

        //protected void SetMsgType(int TaskStatus,string )
    }
}
