using ICS.WCF.Base;
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 ICS.CreateLotMaster
{
    public class CustCreateLotMaster
    {
        /// <summary>
        /// 创建批号
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResule CustCreateRCVLotMaster(string WHCode, string ItemCode, string LotNo, string OrgID, ref string LotID)
        {
            //U9.PM.PO.POShipLine.CreatePOShipLineDefault();
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 

            UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient();
            //服务返回结果
            UFIDAU9BaseDTOsIDCodeNameDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //;
            OperationResule result = new OperationResule();
            string[] splitBy = new string[] { };
            UFIDAU9ISVCBOLotCreateLotMasterDTOData[] createLotMasterDTOList = new UFIDAU9ISVCBOLotCreateLotMasterDTOData[] { };
            List<UFIDAU9ISVCBOLotCreateLotMasterDTOData> list = new List<UFIDAU9ISVCBOLotCreateLotMasterDTOData>();

            UFIDAU9ISVCBOLotCreateLotMasterDTOData _model = new UFIDAU9ISVCBOLotCreateLotMasterDTOData();
            #region 验证批号是否存在，如存在则不需要创建
            string lotchk = @"  select A.ID from Lot_LotMaster A
                                LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item
                                WHERE A.LotCode='{0}' AND B.Code='{1}' AND B.Org='{2}'";
            lotchk = string.Format(lotchk, LotNo, ItemCode, OrgID);
            DataTable chkdt = DBhlper.Query(lotchk, Appconfig.GetU9ConnStr());
            if (chkdt.Rows.Count != 0)
            {
                result.DocNo = LotNo;
                result.IsSuccess = true;
                LotID = chkdt.Rows[0]["ID"].ToString();
                result.Message = "库存批号已存在！";
                return result;
            }
            #endregion
            #region 获取料品有效期天数
            int EfftiveDay = 0;
            string lotsql = @"select ISNULL(B.LotValidDate,0) AS LotValidDate from CBO_ItemMaster A
                              INNER JOIN CBO_InventoryInfo B ON B.ItemMaster=A.ID
                              where Code='{0}' and Org='{1}'";
            lotsql = string.Format(lotsql, ItemCode, OrgID);
            DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
            if (lotdt.Rows.Count != 0)
            {
                EfftiveDay = int.Parse(lotdt.Rows[0]["LotValidDate"].ToString());
            }

            if (EfftiveDay == 0)
            {
                EfftiveDay = 9990;
            }
            #endregion
            _model.m_lotCode = LotNo;//批号
            _model.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_item.m_code = ItemCode;//料品
            _model.m_usedToOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_usedToOrg.m_iD = long.Parse(OrgID);
            _model.m_lotEnableTime = DateTime.Now;
            _model.m_lotDisabledTime = DateTime.Now.AddDays(EfftiveDay);
            _model.m_availableDate = EfftiveDay;
            _model.m_disabledTime = DateTime.Now.AddDays(EfftiveDay);

            list.Add(_model);
            createLotMasterDTOList = list.ToArray();

            try
            {
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //给传入参数赋值
                //pOList = SetrCVDtos( rCVInfoList);
                //服务调用

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnItems = client.Do(out returnMsg, context, createLotMasterDTOList);
                foreach (var item in returnItems)
                {
                    long id = item.m_iD;
                    string sql = @"SELECT lotcode  from Lot_LotMaster WHERE ID={0}";
                    sql = string.Format(sql, id);
                    DataTable _dtlotcode = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    string lotcode = string.Empty;
                    if (_dtlotcode != null && _dtlotcode.Rows.Count > 0)
                    {
                        lotcode = _dtlotcode.Rows[0][0].ToString();
                    }
                    result.DocNo = lotcode;
                    result.IsSuccess = true;
                    LotID = id.ToString();
                    result.Message = "创建库存批号成功";
                }

                return result;
            }
            catch (Exception ex)
            {
                //异常信息捕获

                string Message = GetExceptionMessage(ex);
                result.DocNo = "";
                result.IsSuccess = false;
                result.Message = Message;
                return result;
            }
            #endregion
        }
        /// <summary>
        /// 创建批号(查询时去掉组织条件---起因：派纳批号只在101存在)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResule CustCreateRCVLotMasterPN(string WHCode, string ItemCode, string LotNo, string OrgID, ref string LotID)
        {
            //U9.PM.PO.POShipLine.CreatePOShipLineDefault();
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 

            UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient();
            //服务返回结果
            UFIDAU9BaseDTOsIDCodeNameDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //;
            OperationResule result = new OperationResule();
            string[] splitBy = new string[] { };
            UFIDAU9ISVCBOLotCreateLotMasterDTOData[] createLotMasterDTOList = new UFIDAU9ISVCBOLotCreateLotMasterDTOData[] { };
            List<UFIDAU9ISVCBOLotCreateLotMasterDTOData> list = new List<UFIDAU9ISVCBOLotCreateLotMasterDTOData>();

            UFIDAU9ISVCBOLotCreateLotMasterDTOData _model = new UFIDAU9ISVCBOLotCreateLotMasterDTOData();
            #region 验证批号是否存在，如存在则不需要创建
            string lotchk = @"  select A.ID from Lot_LotMaster A
                                LEFT JOIN CBO_ItemMaster B ON B.ID=A.Item
                                WHERE A.LotCode='{0}' AND B.Code='{1}'";
            lotchk = string.Format(lotchk, LotNo, ItemCode, OrgID);
            DataTable chkdt = DBhlper.Query(lotchk, Appconfig.GetU9ConnStr());
            if (chkdt.Rows.Count != 0)
            {
                result.DocNo = LotNo;
                result.IsSuccess = true;
                LotID = chkdt.Rows[0]["ID"].ToString();
                result.Message = "库存批号已存在！";
                return result;
            }
            #endregion
            #region 获取料品有效期天数
            int EfftiveDay = 0;
            string lotsql = @"select ISNULL(B.LotValidDate,0) AS LotValidDate from CBO_ItemMaster A
                              INNER JOIN CBO_InventoryInfo B ON B.ItemMaster=A.ID
                              where Code='{0}' and Org='{1}'";
            lotsql = string.Format(lotsql, ItemCode, OrgID);
            DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
            if (lotdt.Rows.Count != 0)
            {
                EfftiveDay = int.Parse(lotdt.Rows[0]["LotValidDate"].ToString());
            }
            #endregion
            _model.m_lotCode = LotNo;//批号
            _model.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_item.m_code = ItemCode;//料品
            _model.m_usedToOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_usedToOrg.m_iD = long.Parse(OrgID);
            _model.m_lotEnableTime = DateTime.Now;
            _model.m_lotDisabledTime = DateTime.Now.AddDays(EfftiveDay);
            _model.m_availableDate = EfftiveDay;
            _model.m_disabledTime = DateTime.Now.AddDays(EfftiveDay);

            list.Add(_model);
            createLotMasterDTOList = list.ToArray();

            try
            {
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //给传入参数赋值
                //pOList = SetrCVDtos( rCVInfoList);
                //服务调用

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnItems = client.Do(out returnMsg, context, createLotMasterDTOList);
                foreach (var item in returnItems)
                {
                    long id = item.m_iD;
                    string sql = @"SELECT lotcode  from Lot_LotMaster WHERE ID={0}";
                    sql = string.Format(sql, id);
                    DataTable _dtlotcode = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    string lotcode = string.Empty;
                    if (_dtlotcode != null && _dtlotcode.Rows.Count > 0)
                    {
                        lotcode = _dtlotcode.Rows[0][0].ToString();
                    }
                    result.DocNo = lotcode;
                    result.IsSuccess = true;
                    LotID = id.ToString();
                    result.Message = "创建库存批号成功";
                }

                return result;
            }
            catch (Exception ex)
            {
                //异常信息捕获

                string Message = GetExceptionMessage(ex);
                result.DocNo = "";
                result.IsSuccess = false;
                result.Message = Message;
                return result;
            }
            #endregion
        }

        /// <summary>
        /// 创建批号（创建时间修改）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResule CustCreateRCVLotMaster(string WHCode, string ItemCode, string LotNo, DateTime CreateTime, string OrgID, ref string LotID)
        {
            //U9.PM.PO.POShipLine.CreatePOShipLineDefault();
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 

            UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient();
            //服务返回结果
            UFIDAU9BaseDTOsIDCodeNameDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //;
            OperationResule result = new OperationResule();
            string[] splitBy = new string[] { };
            UFIDAU9ISVCBOLotCreateLotMasterDTOData[] createLotMasterDTOList = new UFIDAU9ISVCBOLotCreateLotMasterDTOData[] { };
            List<UFIDAU9ISVCBOLotCreateLotMasterDTOData> list = new List<UFIDAU9ISVCBOLotCreateLotMasterDTOData>();

            UFIDAU9ISVCBOLotCreateLotMasterDTOData _model = new UFIDAU9ISVCBOLotCreateLotMasterDTOData();


            _model.m_lotCode = LotNo;//批号
            _model.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_item.m_code = ItemCode;//料品
            _model.m_usedToOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_usedToOrg.m_iD = long.Parse(OrgID);
            //_model.m_lotDisabledTime = Convert.ToDateTime("9999.12.31");

            list.Add(_model);
            createLotMasterDTOList = list.ToArray();

            try
            {
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //给传入参数赋值
                //pOList = SetrCVDtos( rCVInfoList);
                //服务调用

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnItems = client.Do(out returnMsg, context, createLotMasterDTOList);
                foreach (var item in returnItems)
                {
                    long id = item.m_iD;
                    string sql = @"SELECT lotcode  from Lot_LotMaster WHERE ID={0}";
                    sql = string.Format(sql, id);
                    DataTable _dtlotcode = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    string lotcode = _dtlotcode.Rows[0][0].ToString();
                    //if (_dtlotcode != null && _dtlotcode.Rows.Count > 0)
                    //{
                    //    lotcode = _dtlotcode.Rows[0][0].ToString();
                    //    sql = @"Update Lot_LotMaster set CreatedOn='{0}'
                    //            Where ID='{1}'";
                    //    sql = string.Format(sql, CreateTime, id);
                    //    DBhlper.EXecute(sql, Appconfig.GetU9ConnStr());
                    //}
                    result.DocNo = lotcode;
                    result.IsSuccess = true;
                    LotID = id.ToString();
                    result.Message = "创建库存批号成功";
                }

                return result;
            }
            catch (Exception ex)
            {
                //异常信息捕获

                string Message = GetExceptionMessage(ex);
                result.DocNo = "";
                result.IsSuccess = false;
                result.Message = Message;
                return result;
            }
            #endregion
        }

        /// <summary>
        /// 创建批号（指定生效日期）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public OperationResule CreateLotMasterWithProductDate(string WHCode, string ItemCode, string LotNo, string ProductDate, string OrgID, ref string LotID)
        {
            //U9.PM.PO.POShipLine.CreatePOShipLineDefault();
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 

            UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient();
            //服务返回结果
            UFIDAU9BaseDTOsIDCodeNameDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //;
            OperationResule result = new OperationResule();
            string[] splitBy = new string[] { };
            UFIDAU9ISVCBOLotCreateLotMasterDTOData[] createLotMasterDTOList = new UFIDAU9ISVCBOLotCreateLotMasterDTOData[] { };
            List<UFIDAU9ISVCBOLotCreateLotMasterDTOData> list = new List<UFIDAU9ISVCBOLotCreateLotMasterDTOData>();

            #region 获取料品有效期天数
            int EfftiveDay = 0;
            string lotsql = @"select B.LotValidDate from CBO_ItemMaster A
                              INNER JOIN CBO_InventoryInfo B ON B.ItemMaster=A.ID
                              where Code='{0}' and Org='{1}'";
            lotsql = string.Format(lotsql, ItemCode, OrgID);
            DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
            if (lotdt.Rows.Count != 0)
            {
                EfftiveDay = int.Parse(lotdt.Rows[0]["LotValidDate"].ToString());
            }
            #endregion
            UFIDAU9ISVCBOLotCreateLotMasterDTOData _model = new UFIDAU9ISVCBOLotCreateLotMasterDTOData();
            _model.m_lotCode = LotNo;//批号
            _model.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_item.m_code = ItemCode;//料品
            _model.m_usedToOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_usedToOrg.m_iD = long.Parse(OrgID);
            _model.m_lotEnableTime = Convert.ToDateTime(ProductDate);
            _model.m_lotDisabledTime = Convert.ToDateTime(ProductDate).AddDays(EfftiveDay);
            _model.m_availableDate = EfftiveDay;
            _model.m_disabledTime = Convert.ToDateTime(ProductDate).AddDays(EfftiveDay);

            list.Add(_model);
            createLotMasterDTOList = list.ToArray();

            try
            {
                //给上下文信息赋值
                context = CreateContextObj(OrgID);
                //给传入参数赋值
                //pOList = SetrCVDtos( rCVInfoList);
                //服务调用

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnItems = client.Do(out returnMsg, context, createLotMasterDTOList);
                foreach (var item in returnItems)
                {
                    long id = item.m_iD;
                    string sql = @"SELECT lotcode  from Lot_LotMaster WHERE ID={0}";
                    sql = string.Format(sql, id);
                    DataTable _dtlotcode = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    string lotcode = _dtlotcode.Rows[0][0].ToString();
                    result.DocNo = lotcode;
                    result.IsSuccess = true;
                    LotID = id.ToString();
                    result.Message = "创建库存批号成功";
                }

                return result;
            }
            catch (Exception ex)
            {
                //异常信息捕获

                string Message = GetExceptionMessage(ex);
                result.DocNo = "";
                result.IsSuccess = false;
                result.Message = Message;
                return result;
            }
            #endregion
        }
        /// <summary>
        /// 特殊批号创建（U9创建出的批号没有失效时间的情况）
        /// </summary>
        /// <param name="WHCode"></param>
        /// <param name="ItemCode"></param>
        /// <param name="LotNo"></param>
        /// <param name="CreateOn"></param>
        /// <param name="OrgID"></param>
        /// <param name="LotID"></param>
        /// <returns></returns>
        public OperationResule CreateRCVLotMasterSpecial(string BatchID, string WHCode, string ItemCode, string LotNo, DateTime CreateOn, string OrgID, ref string LotID)
        {
            //U9.PM.PO.POShipLine.CreatePOShipLineDefault();
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 

            UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient();
            //服务返回结果
            UFIDAU9BaseDTOsIDCodeNameDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //;
            OperationResule result = new OperationResule();

            try
            {
                #region 获取料品有效期天数
                int EfftiveDay = 0;
                string lotsql = @"select ISNULL(B.LotValidDate,0) AS LotValidDate from CBO_ItemMaster A
                              INNER JOIN CBO_InventoryInfo B ON B.ItemMaster=A.ID
                              where Code='{0}' and Org='{1}'";
                lotsql = string.Format(lotsql, ItemCode, OrgID);
                DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                if (lotdt.Rows.Count != 0)
                {
                    EfftiveDay = int.Parse(lotdt.Rows[0]["LotValidDate"].ToString());
                }

                if (EfftiveDay == 0)
                {
                    EfftiveDay = 9990;
                }

                #endregion
                string sql = @"update Lot_LotMaster set InvalidTime=DATEADD(DAY,{1},CreatedOn),EffectiveDatetime=CreatedOn,ValidDate={1}
                               where ID='{0}'";
                sql = string.Format(sql, BatchID, EfftiveDay);
                DBhlper.EXecute(sql, Appconfig.GetU9ConnStr());
                result.DocNo = LotNo;
                result.IsSuccess = true;
                LotID = BatchID;
                result.Message = "库存批号失效时间修改成功";

                return result;
            }
            catch (Exception ex)
            {
                //异常信息捕获

                string Message = GetExceptionMessage(ex);
                result.DocNo = "";
                result.IsSuccess = false;
                result.Message = Message;
                return result;
            }
            #endregion
        }

        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private 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 ThreadContext CreateContextObj(string OrgID)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].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

        #region 表头类
        public class LotMaster
        {
            //private string _LotCodingRule; //编码规则


            private string _ItemCode;

            //private string _DocCode;//单据号RCVNo

            private string _LotCode;//批号

            private string _WHCode;//存储地点

            public string LotCode
            {
                get { return _LotCode; }
                set { _LotCode = value; }
            }

            //public string DocCode
            //{
            //    get { return _DocCode; }
            //    set { _DocCode = value; }
            //}


            public string ItemCode
            {
                get { return _ItemCode; }
                set { _ItemCode = value; }
            }

            public string WHCode
            {
                get { return _WHCode; }
                set { _WHCode = value; }
            }
        }
        #endregion


        public class OperationResule
        {

            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }
    }
}