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.DFT
{
    public class BizComponent_DFT : BaseBizComponent, IBizComponent
    {
        const string Insert = "B01"; //增加个人纪录
        //const string Update = "B02"; //更新个人记录
        //const string Delete = "B03"; //删除个人记录


        //数据库连接
        protected Database ctx;
        protected Database Scanctx;
        public BizComponent_DFT()
        {
            DatabaseProviderFactory factory = new DatabaseProviderFactory();
            ctx = factory.Create("HealthCare");
            Scanctx = factory.CreateDefault();
        }
        ////HealthCareContainer HealthCareContainer = new HealthCareContainer();
        //private Database ctx = null;
        //public BizComponent_PMU(Database dbCtx)
        //{
        //    ctx = dbCtx;
        //}
        public override string DoProcess(string m, string msgType, string ID)
        {
            string strMsgType = null;
            var resultCode = string.Empty;
            var result = string.Empty;
            //try
            //{
            //try
            // {
            //取得消息类型 MAD新增 MUP更新 MDL删除 "MDC"作废 "MAC"恢复
            OperateXmlUtil helper = new OperateXmlUtil();
            WebService server = new WebService();
            string orgCode = System.Configuration.ConfigurationManager.AppSettings["orgCode"];
            var cert = System.Configuration.ConfigurationManager.AppSettings["cert"];
           
            var startTime="";
            var endTime = DateTime.Now.ToString("yyyy-MM-dd");
            var pageIndex="0";
            var pageSize = System.Configuration.ConfigurationManager.AppSettings["pageSize"];
            GetStartTime(ID,out startTime,out pageIndex);
            string msgBody = helper.GetMsgBody(orgCode, "startTime", startTime, "endTime", endTime, pageIndex, pageSize);
            string msgHead = helper.GetMsgHead("getChargeitem", cert);


            string rtnMsg = server.TestInterface(msgHead, msgHead);
            //存储访问记录
            MessageHelper.SaveSendMsg(Scanctx, ID, "DFT^B01[B01]", msgHead, msgBody, rtnMsg);
            //消息判断是否成功
            if (!helper.isSuccess(rtnMsg, ref resultCode, ref result))
            {
                throw new Exception(result);
            }

            XmlNodeList root = helper.XpathRead(rtnMsg, "//returnContents//returnContent");
            if (root.Count <= 0)
                return string.Empty;

            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                var usql = @"update item_his_original set yn_code=@yn_code,item_name=@item_name,fee_code=@fee_code,fee_name=@fee_code,spell_code=@spell_code,price=@price,status=@status,status_date=@status_date where item_code=@item_code";
                var sql = @"insert into item_his_original(item_code,yn_code,item_name,fee_code,fee_name,spell_code,price,status,status_date) Values(@item_code,@yn_code,@item_name,@fee_code,@fee_name,@spell_code,@price,@status,@status_date);";
                foreach (XmlElement xe in root)
                {
                    var iSet = GetDOCT(xe.SelectSingleNode("item_code").InnerText);
                    if (iSet <= 0)
                    {
                        var cmd = SqlDataAccess.GetSqlStringCommand(ctx, sql);
                        ctx.AddInParameter(cmd, "item_code", System.Data.DbType.String, xe.SelectSingleNode("ITEM_CODE").InnerText);
                        ctx.AddInParameter(cmd, "yn_code", System.Data.DbType.String, xe.SelectSingleNode("YN_CODE").InnerText);
                        ctx.AddInParameter(cmd, "item_name", System.Data.DbType.String, xe.SelectSingleNode("ITEM_NAME").InnerText);
                        ctx.AddInParameter(cmd, "fee_code", System.Data.DbType.String, xe.SelectSingleNode("FEE_CODE").InnerText);
                        ctx.AddInParameter(cmd, "fee_name", System.Data.DbType.String, xe.SelectSingleNode("FEE_NAME").InnerText);
                        ctx.AddInParameter(cmd, "spell_code", System.Data.DbType.String, xe.SelectSingleNode("SPELL_CODE").InnerText);
                        decimal price = 0;
                        try
                        {
                            decimal.TryParse(xe.SelectSingleNode("PRICE").InnerText, out price);
                            this.ctx.AddInParameter(cmd, "price", System.Data.DbType.Decimal, price);
                        }
                        catch
                        {
                            this.ctx.AddInParameter(cmd, "price", System.Data.DbType.Decimal, 0);
                        }
                        //ctx.AddInParameter(cmd, "price", System.Data.DbType.Decimal, xe.SelectSingleNode("PRICE").InnerText);

                        ctx.AddInParameter(cmd, "status", System.Data.DbType.String, xe.SelectSingleNode("STATUS").InnerText);
                        var date = xe.SelectSingleNode("STATUS_DATE").InnerText;
                        DateTime time = DateTime.Now;
                        if (!string.IsNullOrWhiteSpace(date))
                        {
                            if (!DateTime.TryParse(date, out time))
                            {
                                time = DateTime.Now;
                            }
                        }
                        ctx.AddInParameter(cmd, "status_date", System.Data.DbType.DateTime, time);
                        SqlDataAccess.DBExecuteNonQuery(ctx, cmd);
                    }
                    else
                    {
                        var cmd = SqlDataAccess.GetSqlStringCommand(ctx, usql);
                        ctx.AddInParameter(cmd, "item_code", System.Data.DbType.String, xe.SelectSingleNode("ITEM_CODE").InnerText);
                        ctx.AddInParameter(cmd, "yn_code", System.Data.DbType.String, xe.SelectSingleNode("YN_CODE").InnerText);
                        ctx.AddInParameter(cmd, "item_name", System.Data.DbType.String, xe.SelectSingleNode("ITEM_NAME").InnerText);
                        ctx.AddInParameter(cmd, "fee_code", System.Data.DbType.String, xe.SelectSingleNode("FEE_CODE").InnerText);
                        ctx.AddInParameter(cmd, "fee_name", System.Data.DbType.String, xe.SelectSingleNode("FEE_NAME").InnerText);
                        ctx.AddInParameter(cmd, "spell_code", System.Data.DbType.String, xe.SelectSingleNode("SPELL_CODE").InnerText);
                        decimal price = 0;
                        try
                        {
                            decimal.TryParse(xe.SelectSingleNode("PRICE").InnerText, out price);
                            this.ctx.AddInParameter(cmd, "price", System.Data.DbType.Decimal, price);
                        }
                        catch
                        {
                            this.ctx.AddInParameter(cmd, "price", System.Data.DbType.Decimal, 0);
                        }
                        //ctx.AddInParameter(cmd, "price", System.Data.DbType.Decimal, xe.SelectSingleNode("price").InnerText);
                        ctx.AddInParameter(cmd, "status", System.Data.DbType.String, xe.SelectSingleNode("STATUS").InnerText);
                        var date = xe.SelectSingleNode("STATUS_DATE").InnerText;
                        DateTime time = DateTime.Now;
                        if (!string.IsNullOrWhiteSpace(date))
                        {
                            if (!DateTime.TryParse(date, out time))
                            {
                                time = DateTime.Now;
                            }
                        }
                        ctx.AddInParameter(cmd, "status_date", System.Data.DbType.DateTime, time);
                        SqlDataAccess.DBExecuteNonQuery(ctx, cmd);
                    }
                }
                scope.Complete();
            }
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew))
			{
                var ScanSql = @"update HL7_Scan set OtherNo2=@OtherNo2 where ID=@ID";
                var ucmd = SqlDataAccess.GetSqlStringCommand(Scanctx, ScanSql);
                Scanctx.AddInParameter(ucmd, "ID", System.Data.DbType.String, ID);
                Scanctx.AddInParameter(ucmd, "OtherNo2", System.Data.DbType.String, pageIndex);
                SqlDataAccess.DBExecuteNonQuery(Scanctx, ucmd);
                transactionScope.Complete();
                
            }
            return string.Empty;
        }
        public void AddData(string message, string id)
        {
            #region 新增
            string sql = @"INSERT INTO dbo.his_doct
                                    ( DOCT_CODE ,
                                    DOCT_NAME ,
                                    HIS_DEPT_CODE ,
                                    HIS_DEPT_NAME ,
                                    status
                                    )
                            VALUES  ( @DOCT_CODE,
                                    @DOCT_NAME ,
                                    @HIS_DEPT_CODE ,
                                    @HIS_DEPT_NAME ,
                                    @status)";
            DbCommand command = ctx.GetSqlStringCommand(sql.ToString());

            SetEntity(message, command, id);
            SqlDataAccess.ExecuteNonQuery(ctx, command);
            #endregion
        }
        public void UpDateData(string message, string id)
        {
            #region 修改
            string sql1 = @"update dbo.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";
            DbCommand command1 = ctx.GetSqlStringCommand(sql1.ToString());

            SetEntity(message, command1, id);
            SqlDataAccess.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);
        }

        public int GetDOCT(string DOCT_Code)
        {
            var sql = "SELECT count(1) FROM dbo.item_his_original WITH(NOLOCK) WHERE item_code=@item_code";
            var cmd = ctx.DBGetSqlStringCommand(sql);
            ctx.AddInParameter(cmd, "item_code", DbType.String, DOCT_Code);
            var obj = int.Parse(StrHelepr.Obj2StrTrim(ctx.DBExecuteScalar(cmd)));
            return obj;
        }

        public void GetStartTime(string ID, out string startTime, out string pageIndex)
        {
            string text = "SELECT OtherNo1,OtherNo2 FROM dbo.HL7_Scan WITH(NOLOCK) where ID=@ID";
            System.Data.Common.DbCommand dbCommand = SqlDataAccess.DBGetSqlStringCommand(this.Scanctx, text);
            this.Scanctx.AddInParameter(dbCommand, "ID", System.Data.DbType.String, ID);
            System.Data.DataSet dataSet = this.Scanctx.ExecuteDataSet(dbCommand);
            startTime = dataSet.Tables[0].Rows[0][0].ToString();
            pageIndex = (int.Parse(dataSet.Tables[0].Rows[0][1].ToString()) + 1).ToString();
        }




    }

}