using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using NHapi.Model.V24.Segment;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Transactions;
using NHapi.Model.V24.Message;
using NHapi.Model.V24.Group;

namespace MediII.Adapter.BizComponent.MFN
{
    /// <summary>
    /// Z3H(药品分类)
    /// wuchengwu 2014-05-23
    /// </summary>
    public class MFN_Z3H_GY_YAOPINFL : MFNBase
    {
        //数据库连接
        private Database ctx = null;
        public MFN_Z3H_GY_YAOPINFL(Database dbCtx)
        {
            ctx = dbCtx;
        }

        #region 消息处理
        /// <summary>
        /// 消息处理
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public override int Process(NHapi.Base.Model.IMessage message)
        {
            //取得消息类型 MAD新增 MUP更新 MDL删除 "MDC"作废 "MAC"恢复
            string strMsgType;

            MFN_Z3H msg = message as MFN_Z3H;

           
                for (int i = 0; i < msg.MFRepetitionsUsed; i++)
                {
                    MFN_Z3H_Nofification group = msg.GetMF(i);
                    strMsgType = group.MFE.RecordLevelEventCode.Value;

                    string pkid = group.Z3H.YaoPinFlId.Value;
                     string qurysql = "select count(*) from HealthCare.dbo.MedWaySet where WayNo=@WayNo";
                    DbCommand command = ctx.GetSqlStringCommand(qurysql.ToString());
                    ctx.AddInParameter(command, "WayNo", System.Data.DbType.String, pkid);
                    int counts = Convert.ToInt32(ctx.ExecuteScalar(command));

 using (TransactionScope scope = new TransactionScope(TransactionScopeOption.RequiresNew))
            {
                    if (counts == 0)
                    {
                    //switch (strMsgType)
                    //{
                        //case MAD:
                            #region 新增
                            AddData(group, pkid);
                            #endregion
                            //break;
                    }
                    else
                    { 
                        //case MUP:
                        if ("MUP" == strMsgType || "MAD" == strMsgType)
                        {
                            #region 修改
                            StringBuilder sql1 = new StringBuilder();

                            #region wuchengwu 20140911 modi 去掉顺序号（shunxuhao）的更新
                            /*MediIIB-242(205628):Modified By ZhangM.Y.@2014-09-03:发送过来的修改消息不要去同步MoJiBZ，因为这个字段是在Z3A_YAOPINXX里面处理。去掉（mojibz=:mojibz,）*/
                            //                            sql1.AppendFormat(@" UPDATE gy_yaopinfl 
                            //                                                 SET shangjifl=:shangjifl,
                            //                                                     fenleimc =:fenleimc,
                            //                                                     biaozhunbm =:biaozhunbm,
                            //                                                     yaopinlx=:yaopinlx,
                            //                                                     shunxuhao=:shunxuhao,
                            //                                                     xiugairen=:xiugairen,
                            //                                                     xiugaisj=:xiugaisj,
                            //                                                     fenleilb=:fenleilb,
                            //                                                     zuofeibz=:zuofeibz,
                            //                                                     shuruma1=:shuruma1,
                            //                                                     shuruma2=:shuruma2,
                            //                                                     shuruma3=:shuruma3
                            //                                                 WHERE yaopinflid=:yaopinflid ");
                            sql1.AppendFormat(@" UPDATE gy_yaopinfl 
                                                 SET shangjifl=:shangjifl,
                                                     fenleimc =:fenleimc,
                                                     biaozhunbm =:biaozhunbm,
                                                     yaopinlx=:yaopinlx,
                                                     xiugairen=:xiugairen,
                                                     xiugaisj=:xiugaisj,
                                                     fenleilb=:fenleilb,
                                                     zuofeibz=:zuofeibz,
                                                     shuruma1=:shuruma1,
                                                     shuruma2=:shuruma2,
                                                     shuruma3=:shuruma3
                                                 WHERE yaopinflid=:yaopinflid ");
                            #endregion
                            DbCommand command1 = ctx.GetSqlStringCommand(sql1.ToString());
                            SetEntityForUpdating(group.Z3H, ctx, command1);
                            ctx.AddInParameter(command1, "yaopinflid", System.Data.DbType.AnsiString, pkid);
                            int affectedRecords = ctx.ExecuteNonQuery(command1);
                            if (affectedRecords == 0)
                            {
                                //更新数据时，当返回受影响行数为0时，则跳转到新增数据操作
                                AddData(group, pkid);
                            }
                            #endregion
                            //break;
                        }
                        if ("MDL" == strMsgType)
                        {
                            //case MDL:
                            #region 删除/作废
                            StringBuilder sql2 = new StringBuilder();
                            sql2.Append(" UPDATE GY_YAOPINFL SET ZUOFEIBZ = 1 WHERE YAOPINFLID = :YAOPINFLID ");
                            DbCommand command2 = ctx.GetSqlStringCommand(sql2.ToString());
                            ctx.AddInParameter(command2, "yaopinflid", System.Data.DbType.AnsiString, pkid);
                            ctx.ExecuteNonQuery(command2);
                            #endregion
                            //break;
                        }
                    //}
                    }
scope.Complete();
                }
                
            }
            return 1;
        } 
        #endregion

        #region 新增数据
        /// <summary>
        /// 新增数据
        /// </summary>
        /// <param name="group"></param>
        /// <param name="pkid">主键</param>
        private void AddData(MFN_Z3H_Nofification group, string pkid)
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendFormat(@"insert into gy_yaopinfl(
                                                      yaopinflid,
                                                      shangjifl,
                                                      fenleimc,
                                                      biaozhunbm,
                                                      yaopinlx,
                                                      shunxuhao,
                                                      xiugairen,
                                                      xiugaisj,
                                                      fenleilb,
                                                      zuofeibz,
                                                      shuruma1,
                                                      shuruma2,
                                                      shuruma3,
                                                      mojibz)
                                               values(
                                                      :yaopinflid,
                                                      :shangjifl,
                                                      :fenleimc,
                                                      :biaozhunbm,
                                                      :yaopinlx,
                                                      :shunxuhao,
                                                      :xiugairen,
                                                      :xiugaisj,
                                                      :fenleilb,
                                                      :zuofeibz,
                                                      :shuruma1,
                                                      :shuruma2,
                                                      :shuruma3,
                                                      :mojibz )");
            DbCommand command0 = ctx.GetSqlStringCommand(sql.ToString());
            ctx.AddInParameter(command0, "yaopinflid", System.Data.DbType.AnsiString, pkid);
            SetEntity(group.Z3H, ctx, command0);
            ctx.AddInParameter(command0, "mojibz", System.Data.DbType.Int16, group.Z3H.MoJiBz.Value == "1" ? (short)1 : (short)0);
            ctx.ExecuteNonQuery(command0);
        } 
        #endregion

        #region 实体参数（新增数据）
        /// <summary>
        /// 对Entity进行赋值
        /// wuchengwu 2014-05-23
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="zaa">The zaa.</param>
        /// <param name="daiMaLb">The dai ma lb.</param>
        /// <remarks></remarks>
        public void SetEntity(Z3H seg, Database ctx, DbCommand command)
        {
            ctx.AddInParameter(command, "shangjifl", System.Data.DbType.AnsiString, seg.FuLeiId.Value);
            ctx.AddInParameter(command, "fenleimc", System.Data.DbType.AnsiString, seg.YaoPinFlMc.Value);
            ctx.AddInParameter(command, "biaozhunbm", System.Data.DbType.AnsiString, seg.BiaoZhunBm.Value);
            ctx.AddInParameter(command, "yaopinlx", System.Data.DbType.Int16, seg.YaoPinLx.Value);
            ctx.AddInParameter(command, "shunxuhao", System.Data.DbType.Int32, MFNBase.GetSortNum(ctx, "gy_yaopinfl"));
            ctx.AddInParameter(command, "xiugairen", System.Data.DbType.AnsiString, seg.XiuGaiRen.IDNumber.Value);
            ctx.AddInParameter(command, "xiugaisj", System.Data.DbType.DateTime, seg.XiuGaiSJ.TimeOfAnEvent.GetAsDate());
            ctx.AddInParameter(command, "fenleilb", System.Data.DbType.Int16, 1);//分类类别待定
            ctx.AddInParameter(command, "zuofeibz", System.Data.DbType.Int16, seg.ZuoFeiBz.Value == "1" ? (short)1 : (short)0);
            #region 获取输入码
            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.YaoPinFlMc.Value) : shuRuMa.Text.Value;
                    continue;
                }
                if (SHURUMA2 == string.Empty)
                {
                    SHURUMA2 = string.IsNullOrEmpty(shuRuMa.Text.Value) ? MFNBase.GetInputCode(1, seg.YaoPinFlMc.Value) : shuRuMa.Text.Value;
                    continue;
                }
                if (SHURUMA3 == string.Empty)
                {
                    SHURUMA3 = shuRuMa.Text.Value;
                    continue;
                }
            }
            ctx.AddInParameter(command, "shuruma1", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA1) ? "" : SHURUMA1.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "shuruma2", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA2) ? "" : SHURUMA2.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "shuruma3", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA3) ? "" : SHURUMA3.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            #endregion
        } 
        #endregion

        #region 实体参数（更新数据)
        /// <summary>
        /// 对Entity进行赋值
        /// wuchengwu 2014-05-23
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="zaa">The zaa.</param>
        /// <param name="daiMaLb">The dai ma lb.</param>
        /// <remarks></remarks>
        public void SetEntityForUpdating(Z3H seg, Database ctx, DbCommand command)
        {
            ctx.AddInParameter(command, "shangjifl", System.Data.DbType.AnsiString, seg.FuLeiId.Value);
            ctx.AddInParameter(command, "fenleimc", System.Data.DbType.AnsiString, seg.YaoPinFlMc.Value);
            ctx.AddInParameter(command, "biaozhunbm", System.Data.DbType.AnsiString, seg.BiaoZhunBm.Value);
            ctx.AddInParameter(command, "yaopinlx", System.Data.DbType.Int16, seg.YaoPinLx.Value);
            //wuchengwu 20140911 modi 去掉顺序号的更新
            //ctx.AddInParameter(command, "shunxuhao", System.Data.DbType.Int32, MFNBase.GetSortNum(ctx, "gy_yaopinfl"));
            ctx.AddInParameter(command, "xiugairen", System.Data.DbType.AnsiString, seg.XiuGaiRen.IDNumber.Value);
            ctx.AddInParameter(command, "xiugaisj", System.Data.DbType.DateTime, seg.XiuGaiSJ.TimeOfAnEvent.GetAsDate());
            ctx.AddInParameter(command, "fenleilb", System.Data.DbType.Int16, 1);//分类类别待定
            ctx.AddInParameter(command, "zuofeibz", System.Data.DbType.Int16, seg.ZuoFeiBz.Value == "1" ? (short)1 : (short)0);
            #region 获取输入码
            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.YaoPinFlMc.Value) : shuRuMa.Text.Value;
                    continue;
                }
                if (SHURUMA2 == string.Empty)
                {
                    SHURUMA2 = string.IsNullOrEmpty(shuRuMa.Text.Value) ? MFNBase.GetInputCode(1, seg.YaoPinFlMc.Value) : shuRuMa.Text.Value;
                    continue;
                }
                if (SHURUMA3 == string.Empty)
                {
                    SHURUMA3 = shuRuMa.Text.Value;
                    continue;
                }
            }
            ctx.AddInParameter(command, "shuruma1", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA1) ? "" : SHURUMA1.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "shuruma2", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA2) ? "" : SHURUMA2.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            ctx.AddInParameter(command, "shuruma3", System.Data.DbType.AnsiString, string.IsNullOrEmpty(SHURUMA3) ? "" : SHURUMA3.Replace(" ", "").Replace("\r", "").Replace("\t", "").Replace("\n", ""));
            #endregion
        }
        #endregion
    }
}
