using ICS.WCF.Base;
using ICSSoft.Entity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.ModifyLotMaster
{
    public class CustModifyLot
    {

        private static string ERPConStr = Appconfig.GetU9ConnStr();
        //private static string ORGCode = ConfigurationManager.AppSettings["orgCode"].ToString();
        //private static string UserCode = ConfigurationManager.AppSettings["userCode"].ToString();
        private static string ORGCode = "";
        private static string UserCode = "";
        private static string MessageLogName = "修改批次";


        public ModifyLotMasterReturnModel Modify(ModifyLotMasterModel DATA)
        {
            ModifyLotMasterReturnModel res1 = new ModifyLotMasterReturnModel();
            res1.IsSuccess = false;
            res1.Message = "";

            try
            {
                if (DATA == null)
                {
                    throw new Exception("传入内容为空");
                }
                if (!string.IsNullOrEmpty(DATA.ORGCode))
                {
                    ORGCode = DATA.ORGCode;
                }

                if (!string.IsNullOrEmpty(DATA.ModifyUserCode))
                {
                    UserCode = DATA.ModifyUserCode;
                }
                string ORGID = Appconfig.IsExistsCode(ORGCode, "Base_Organization");

                if (string.IsNullOrEmpty(ORGID))
                {
                    throw new Exception("组织不存在：" + ORGCode);
                }

                object con = CreateContextObj(ORGID, UserCode);//上下文
                UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;

                if (DATA.ListLot == null || DATA.ListLot.Count == 0)
                {
                    throw new Exception("传入批次数据为空。");
                }
                //先查询再修改


                UFIDAU9ISVCBOLotICommonQueryLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonQueryLotMasterSRVClient();
                List<UFIDAU9ISVCBOLotQueryLotMasterDTOData> List = new List<UFIDAU9ISVCBOLotQueryLotMasterDTOData>();
                foreach (LotModel Info in DATA.ListLot)
                {
                    long LOTID = Appconfig.GetLotID(Info.LotCode, Info.INVCode, ORGID);
                    if (LOTID == 0)
                    {
                        throw new Exception("传入批次与料品无法找到U9对应的批次料号信息。");
                    }
                    UFIDAU9ISVCBOLotQueryLotMasterDTOData vDTO = new UFIDAU9ISVCBOLotQueryLotMasterDTOData();

                    vDTO.m_iD = Convert.ToInt64(LOTID);
                    List.Add(vDTO);
                }
                UFIDAU9ISVCBOLotLotMasterDTOData[] retList = client.Do(out returnMsg, con, List.ToArray());

                string ErrMessage = "";
                if (returnMsg != null && returnMsg.Count() > 0)
                {
                    foreach (UFSoft.UBF.Exceptions1.MessageBase mm in returnMsg)
                    {
                        ErrMessage += mm.innerMessages + ";";
                    }
                    Appconfig.WriteLogFile("查批次数据异常：" + ErrMessage, MessageLogName);
                }
                if (retList == null || retList.Count() == 0)
                {
                    throw new Exception("查询批次信息异常：未查到批次相关信息.");
                }

                UFIDAU9ISVCBOLotICommonModifyLotMasterSRVClient clientm = new UFIDAU9ISVCBOLotICommonModifyLotMasterSRVClient();

                List<UFIDAU9ISVCBOLotLotMasterDTOData> Listm = new List<UFIDAU9ISVCBOLotLotMasterDTOData>();
                foreach (LotModel mm in DATA.ListLot)
                {
                    long LOTID = Appconfig.GetLotID(mm.LotCode, mm.INVCode, ORGID);
                    List<UFIDAU9ISVCBOLotLotMasterDTOData> lots = retList.Where(a => a.m_iD == LOTID).ToList();
                    if (lots != null && lots.Count > 0)
                    {
                        UFIDAU9ISVCBOLotLotMasterDTOData vDTO = lots.First();
                        //修改
                        vDTO.m_lotDisabledTime = mm.InvalidTime;
                        vDTO.m_disabledTime = mm.InvalidTime;
                        TimeSpan ts = mm.InvalidTime - vDTO.m_lotEnableTime;
                        vDTO.m_availableDate = ts.Days; // 两天相差的天数  
                        vDTO.m_iD = LOTID;
                        Listm.Add(vDTO);

                    }
                    else
                    {
                        Appconfig.WriteLogFile("批次ID:" + LOTID + ",批次Code:" + mm.LotCode + "未查到信息", MessageLogName);
                    }
                }
                UFSoft.UBF.Exceptions1.MessageBase[] retmList = clientm.Do(con, Listm.ToArray());
                res1.IsSuccess = true;
                res1.Message = "批号失效日期修改成功";
            }
            catch (Exception ex)
            {
                res1.IsSuccess = false;
                res1.Message = GetExceptionMessage(ex);
                Appconfig.WriteLogFile(ex.ToString(), MessageLogName);
            }


            StringBuilder strHead2 = new StringBuilder();
            strHead2.AppendLine("***************接口传出参数：");
            strHead2.AppendLine("IsSuccess：" + res1.IsSuccess.ToString() + "MESSAGE:" + res1.Message);
            strHead2.AppendLine("***************接口传出参数End");
            Appconfig.WriteLogFile(strHead2.ToString(), MessageLogName);
            return res1;

        }

        public ModifyLotMasterReturnModel ModifyByJob(ModifyLotMasterJobModel DATA)
        {
            ModifyLotMasterReturnModel res1 = new ModifyLotMasterReturnModel();
            res1.IsSuccess = false;
            res1.Message = "";

            try
            {
                if (DATA == null)
                {
                    throw new Exception("传入内容为空");
                }
                if (!string.IsNullOrEmpty(DATA.ORGCode))
                {
                    ORGCode = DATA.ORGCode;
                }

                if (!string.IsNullOrEmpty(DATA.ModifyUserCode))
                {
                    UserCode = DATA.ModifyUserCode;
                }
                string ORGID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, DATA.ORGCode);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    ORGID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }

                object con = CreateContextObj(ORGID, UserCode);//上下文
                UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;

                if (DATA.ListLot == null || DATA.ListLot.Count == 0)
                {
                    throw new Exception("传入批次数据为空。");
                }
                //先查询再修改


                UFIDAU9ISVCBOLotICommonQueryLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonQueryLotMasterSRVClient();
                List<UFIDAU9ISVCBOLotQueryLotMasterDTOData> List = new List<UFIDAU9ISVCBOLotQueryLotMasterDTOData>();
                foreach (LotJobModel Info in DATA.ListLot)
                {
                    UFIDAU9ISVCBOLotQueryLotMasterDTOData vDTO = new UFIDAU9ISVCBOLotQueryLotMasterDTOData();

                    vDTO.m_iD = Info.LotID;
                    List.Add(vDTO);
                }
                UFIDAU9ISVCBOLotLotMasterDTOData[] retList = client.Do(out returnMsg, con, List.ToArray());
                string ErrMessage = "";
                if (returnMsg != null && returnMsg.Count() > 0)
                {
                    foreach (UFSoft.UBF.Exceptions1.MessageBase mm in returnMsg)
                    {
                        ErrMessage += mm.innerMessages + ";";
                    }
                    Appconfig.WriteLogFile("查批次数据异常：" + ErrMessage, MessageLogName);
                }
                if (retList == null || retList.Count() == 0)
                {
                    throw new Exception("查询批次信息异常：未查到批次相关信息.");
                }

                UFIDAU9ISVCBOLotICommonModifyLotMasterSRVClient clientm = new UFIDAU9ISVCBOLotICommonModifyLotMasterSRVClient();

                List<UFIDAU9ISVCBOLotLotMasterDTOData> Listm = new List<UFIDAU9ISVCBOLotLotMasterDTOData>();
                string UpdateSql = "";
                foreach (LotJobModel mm in DATA.ListLot)
                {
                    List<UFIDAU9ISVCBOLotLotMasterDTOData> lots = retList.Where(a => a.m_iD == mm.LotID).ToList();
                    if (lots != null && lots.Count > 0)
                    {
                        UFIDAU9ISVCBOLotLotMasterDTOData vDTO = lots.First();
                        //修改
                        vDTO.m_lotEnableTime = mm.LotEnableTime;
                        vDTO.m_lotDisabledTime = mm.LotEnableTime.AddDays(mm.LotInvalidDays);
                        vDTO.m_disabledTime = mm.LotEnableTime.AddDays(mm.LotInvalidDays);
                        vDTO.m_availableDate = mm.LotInvalidDays; // 有效期天数  
                        vDTO.m_iD = mm.LotID;
                        Listm.Add(vDTO);
                        #region 因为接口传入的新生效时间不生效，使用Update语句单独更新批号的生效时间
                        UpdateSql += @"update Lot_LotMaster set EffectiveDatetime='{0}'
                                       where ID='{1}'";
                        UpdateSql = string.Format(UpdateSql, mm.LotEnableTime, mm.LotID);
                        #endregion
                    }
                    else
                    {
                        Appconfig.WriteLogFile("批次ID:" + mm.LotID + "未查到信息", MessageLogName);
                    }
                }
                UFSoft.UBF.Exceptions1.MessageBase[] retmList = clientm.Do(con, Listm.ToArray());
                DBhlper.Query(UpdateSql, Appconfig.GetU9ConnStr());
                res1.IsSuccess = true;
                res1.Message = "批号失效日期修改成功";
            }
            catch (Exception ex)
            {
                res1.IsSuccess = false;
                res1.Message = GetExceptionMessage(ex);
                Appconfig.WriteLogFile(ex.ToString(), MessageLogName);
            }


            StringBuilder strHead2 = new StringBuilder();
            strHead2.AppendLine("***************接口传出参数：");
            strHead2.AppendLine("IsSuccess：" + res1.IsSuccess.ToString() + "MESSAGE:" + res1.Message);
            strHead2.AppendLine("***************接口传出参数End");
            Appconfig.WriteLogFile(strHead2.ToString(), MessageLogName);
            return res1;

        }



        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private static string GetExceptionMessage(Exception ex)
        {
            string faultMessage = "未知错误，请查看ERP日志！";

            System.TimeoutException timeoutEx = ex as System.TimeoutException;
            if (timeoutEx != null)
            {
                faultMessage = "访问服务超时，请修改配置信息！";
            }
            else
            {
                FaultException<ServiceException> faultEx = ex as FaultException<ServiceException>;
                if (faultEx == null)
                {
                    faultMessage = ex.Message;
                }
                else
                {
                    ServiceException serviceEx = faultEx.Detail;
                    if (serviceEx != null && !string.IsNullOrEmpty(serviceEx.Message)
                        && !serviceEx.Message.Equals("fault", StringComparison.OrdinalIgnoreCase))
                    {
                        // 错误信息在faultEx.Message中，请提取，
                        // 格式为"Fault:料品不能为空，请录入\n 在....."
                        int startIndex = serviceEx.Message.IndexOf(":");
                        int endIndex = serviceEx.Message.IndexOf("\n");
                        if (endIndex == -1)
                            endIndex = serviceEx.Message.Length;
                        if (endIndex > 0 && endIndex > startIndex + 1)
                        {
                            faultMessage = serviceEx.Message.Substring(startIndex + 1, endIndex - startIndex - 1);
                        }
                        else
                        {
                            faultMessage = serviceEx.Message;
                        }
                    }
                }
            }
            return faultMessage;
        }
        #endregion

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID, string CreateByCode)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();


            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);

            if (!string.IsNullOrEmpty(CreateByCode))
            {
                ns.Add("UserCode", CreateByCode);
                DataTable dt_UserName = Appconfig.GetU9UserNameByCode(CreateByCode);
                if (dt_UserName != null && dt_UserName.Rows.Count > 0)
                {
                    ns.Add("UserID", dt_UserName.Rows[0]["ID"].ToString());
                    ns.Add("UserName", dt_UserName.Rows[0]["UserName"].ToString());
                }
            }
            else
            {
                ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
                ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].ToString());
                DataTable dt_UserName = Appconfig.GetU9UserNameByCode(ConfigurationManager.AppSettings["userCode"].ToString());
                if (dt_UserName != null && dt_UserName.Rows.Count > 0)
                {
                    ns.Add("UserName", dt_UserName.Rows[0]["UserName"].ToString());
                }

            }
            ns.Add("Datetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            ns.Add("CultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("EnterpriseID", ConfigurationManager.AppSettings["enterpriseID"].ToString());
            ns.Add("DefaultCultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            thContext.nameValueHas = ns;

            return thContext;
        }
        #endregion
    }
}
