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

namespace ICSSoft.APICreateLotMaster
{
    public class CreateLotMaster
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];

        public OperationResule Create(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();
            _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);

            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
        }

        public OperationResule Create(string WHCode, string ItemCode, string LotNo, string OrgID, ref string LotID, DateTime EffectiveTime, DateTime DisabledTime, int LotLastTime)
        {
            //U9.PM.PO.POShipLine.CreatePOShipLineDefault();                   
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 

            UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient client = new UFIDAU9ISVCBOLotICommonCreateLotMasterSRVClient();
            //服务返回结果
            UFIDAU9BaseDTOsIDCodeNameDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            //;
            #region 根据传入料号及组织编码查询料品ID
            long ItemID = 0;
            string itemsql = @"select ID from CBO_ItemMaster
                           where Code='{0}' and Org='{1}'";
            itemsql = string.Format(itemsql, ItemCode, OrgID);
            DataTable dt = DBhlper.Query(itemsql, Appconfig.GetU9ConnStr());
            if (dt.Rows.Count == 0)
            {
                throw new Exception("传入料号:" + ItemCode + "在当前组织未查询到有效数据，请确认！");
            }
            else
            {
                ItemID = long.Parse(dt.Rows[0]["ID"].ToString());
            }
            #endregion
            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_iD = ItemID;
            _model.m_item.m_code = ItemCode;//料品
            _model.m_usedToOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
            _model.m_usedToOrg.m_iD = long.Parse(OrgID);
            _model.m_lotDisabledTime = DisabledTime;
            _model.m_availableDate = LotLastTime;
            //_model.m_lotDisabledTime = Convert.ToDateTime("9999.12.31");

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

            try
            {

                #region 查询批号是否存在，如已存在，不需要重复创建
                string chksql = @"select ID from Lot_LotMaster
                                  where LotCode='{0}' and Item=(select ID from CBO_ItemMaster
                                  where Code='{1}' and Org='{2}')";
                chksql = string.Format(chksql, LotNo, ItemCode, OrgID);
                DataTable chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                if (chkdt.Rows.Count != 0)
                {
                    result.DocNo = LotNo;
                    result.IsSuccess = true;
                    LotID = chkdt.Rows[0]["ID"].ToString();
                    result.Message = "库存批号已存在。";
                    return result;
                }
                #endregion
                log.Info("创建批号调用接口传入值记录，批号:" + LotNo + ",料品ID:" + ItemID + ",料品编码:" + ItemCode + ",组织ID:" + OrgID + "");
                //给上下文信息赋值
                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;
                    #region 更新批号有效期天数 生效日期 失效日期
                    string lotsql = @"update Lot_LotMaster set EffectiveDatetime='{0}',ValidDate={1},InvalidTime='{2}'
                                      where ID='{3}'";
                    lotsql = string.Format(lotsql, EffectiveTime, LotLastTime, DisabledTime, id);
                    DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                    #endregion
                    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
        }
        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static 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

        private static DataTable GetData(string DocCode, string OrgID)
        {
            string sql = @" select  ID,DocNo
                           from  MO_IssueDoc
                           where DocNo='" + DocCode + "' AND Org='" + OrgID + "'";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }

        #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

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