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.Business.BusinessEntity;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
using UFIDA.ISV.BFRCVApprove;

namespace UFIDA.ISV.CreateBFRTN
{

    public class CustCreateBFRTNSrvSub
    {
        public List<rtnRcvInfo> CustCreateBFRTN(List<rCVhead> rCVInfoList)
        {
            #region 服务调用框架结构
            UFIDAU9ISVRCVICeateReceivementFromPOSRVClient client = new UFIDAU9ISVRCVICeateReceivementFromPOSRVClient();
            //服务返回结果
            EntityKey[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVRCVDTOPOToRcvTransDTOData[] pOList;
            //空
            string[] splitBy = new string[] { };

            try
            {
                List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();

                if (rCVInfoList == null || rCVInfoList.Count == 0)
                {
                    rtnRcvInfo rtnpo = new rtnRcvInfo();
                    rtnpo.IsSuccess = false;
                    rtnpo.Message = "传入参数不能为空";
                    rtnpos.Add(rtnpo);
                    return rtnpos;
                }

                foreach (var item in rCVInfoList)
                {
                    if (item.lines == null || item.lines.Count() == 0)
                    {
                        rtnRcvInfo rtnpo = new rtnRcvInfo();
                        rtnpo.IsSuccess = false;
                        rtnpo.Message = "传入行信息不能为空";
                        rtnpos.Add(rtnpo);
                        return rtnpos;
                    }
                    foreach (var _item in item.lines)
                    {
                        //if (string.IsNullOrWhiteSpace(_item.InvCode))
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.IsSuccess = false;
                        //    rtnpo.Message = "传入料号不能为空";
                        //    rtnpos.Add(rtnpo);
                        //    return rtnpos;
                        //}
                        if (_item.srcDocPOLineNo == 0)
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "请传入来源单据行号";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }
                        if (_item.Quantity == 0)
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "传入数量不能为空";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }

                        //if (string.IsNullOrWhiteSpace(_item.WhCode))
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.IsSuccess = false;
                        //    rtnpo.Message = "传入仓库不能为空";
                        //    rtnpos.Add(rtnpo);
                        //    return rtnpos;
                        //}
                    }
                }


                //给上下文信息赋值
                context = CreateContextObj();
                //给传入参数赋值

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建委外收货单");
                strlog.AppendLine("*****************************************************");

                List<UFIDAU9ISVRCVDTOPOToRcvTransDTOData> rCVList = new List<UFIDAU9ISVRCVDTOPOToRcvTransDTOData>();
                foreach (var rCVhead in rCVInfoList)
                {
                    strlog.AppendLine("来源采购订单号:" + rCVhead.OOCode);
                    foreach (rCVLine line in rCVhead.lines)
                    {
                        UFIDAU9ISVRCVDTOPOToRcvTransDTOData rCV = new UFIDAU9ISVRCVDTOPOToRcvTransDTOData();

                        rCV.m_pONo = rCVhead.OOCode;
                        rCV.m_pOLineNo = line.srcDocPOLineNo;
                        rCV.m_businessDate = Convert.ToDateTime(rCVhead.DocDate);
                        rCV.m_arrivedTime = Convert.ToDateTime(rCVhead.ArrDate);  
                        //数量
                        rCV.m_transQty = new UFIDAU9CBODTOsDoubleQuantityData();

                        rCV.m_transQty.m_amount1 = line.Quantity;
                        rCV.m_transQty.m_amount2 = decimal.Zero;
                       

                        string sqlWH = @"select Code from CBO_Wh
                                         WHERE Code='" + line.WhCode + "' ";
                        sqlWH = string.Format(sqlWH);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHCode = _dtWH.Rows[0][0].ToString();
                        }
                        if (string.IsNullOrWhiteSpace(WHCode))
                        {
                            rtnRcvInfo rtnpo = new rtnRcvInfo();
                            rtnpo.IsSuccess = false;
                            rtnpo.Message = "未获取到仓库";
                            rtnpos.Add(rtnpo);
                            return rtnpos;
                        }
                        //仓库
                        rCV.m_rcvLineInfoDTO = new UFIDAU9ISVRCVDTORcvLineInfoDTOData();
                        rCV.m_rcvLineInfoDTO.m_whCode = WHCode;
                        rCV.m_rcvLineInfoDTO.m_storageType = 4;

                        string sqlOper = @"select id,a.dept from CBO_Operators a where code='adminck' ";
                        sqlOper = string.Format(sqlOper);
                        DataTable _dtOper = DBhlper.Query(sqlOper, Appconfig.GetU9ConnStr());
                        string operID = string.Empty;
                        string operDept = string.Empty;

                        if (_dtOper != null && _dtOper.Rows.Count > 0)
                        {
                            operID = _dtOper.Rows[0][0].ToString();
                            operDept = _dtOper.Rows[0][1].ToString();
                            rCV.m_rcvLineInfoDTO.WhMan =long.Parse( operID);
                            rCV.m_rcvLineInfoDTO.m_whManCode = "adminck";
                        }
                        rCV.m_descFlexSegments = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                        rCV.m_descFlexSegments.m_privateDescSeg1 = line.cFree1;
                        rCV.m_descFlexSegments.m_privateDescSeg2 = line.cFree2;
                        rCV.m_descFlexSegments.m_privateDescSeg3 = line.cFree3;
                        rCV.m_descFlexSegments.m_privateDescSeg4 = line.cFree4;
                        rCV.m_descFlexSegments.m_privateDescSeg5 = line.cFree5;
                        rCV.m_descFlexSegments.m_privateDescSeg6 = line.cFree6;
                        rCV.m_descFlexSegments.m_privateDescSeg7 = line.cFree7;
                        rCV.m_descFlexSegments.m_privateDescSeg8 = line.cFree8;
                        rCV.m_descFlexSegments.m_privateDescSeg9 = line.cFree9;
                        rCV.m_descFlexSegments.m_privateDescSeg10 = line.cFree10;

                        //库位
                        rCV.m_rcvLineInfoDTO.m_lineLocations = new UFIDAU9ISVRCVDTOOBARcvLineLocationDTOData[] { };

                        List<UFIDAU9ISVRCVDTOOBARcvLineLocationDTOData> locationList = new List<UFIDAU9ISVRCVDTOOBARcvLineLocationDTOData>();

                        UFIDAU9ISVRCVDTOOBARcvLineLocationDTOData location = new UFIDAU9ISVRCVDTOOBARcvLineLocationDTOData();
                        location.m_location = new UFIDAU9PMDTOsBESimp4UIDTOData();
                        location.m_location.m_code = line.BinCode;
                        //location.m_location.m_iD = long.Parse("");
                        location.m_locationQtySU = line.Quantity;
                        location.m_locationQtyTU = line.Quantity;

                         

                        if (!string.IsNullOrWhiteSpace(line.BatchCode))
                        {
                            strlog.AppendLine("开始调用创建批号接口------------");
                            string OrgID = string.Empty;
                            string OrgIDSQL = "SELECT a.Org FROM PM_PurchaseOrder a where DocNo='" + rCVhead.OOCode + "'";
                            DataTable dtOrgID = DBhlper.Query(OrgIDSQL, Appconfig.GetU9ConnStr());
                            if (dtOrgID.Rows.Count > 0)
                            {
                                OrgID = dtOrgID.Rows[0][0].ToString();
                            }
                            string LotID = "";
                            //创建批号
                            //UFIDA.ISV.CreateLotMaster.CustCreateLotMaster createLot = new CreateLotMaster.CustCreateLotMaster();
                            //UFIDA.ISV.CreateLotMaster.CustCreateLotMaster.LotMaster lot = new CreateLotMaster.CustCreateLotMaster.LotMaster();
                            //lot.InvCode = line.InvCode;
                            //lot.LotCode = line.BatchCode;
                            //UFIDA.ISV.CreateLotMaster.CustCreateLotMaster.OperationResule result = createLot.CustCreateRCVLotMaster(lot);
                            ICS.CreateLotMaster.CustCreateLotMaster LotMasterCreate = new ICS.CreateLotMaster.CustCreateLotMaster();
                            string lotWHCode = line.WhCode;
                            string lotItemCode = line.InvCode;
                            string LotCode = line.BatchCode;
                            LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, DateTime.Now, OrgID, ref LotID);
                            if (LotID == "")
                            {
                                rtnRcvInfo rtnpo = new rtnRcvInfo();
                                rtnpo.IsSuccess = false;
                                rtnpo.Message = "批号创建失败";
                                rtnpos.Add(rtnpo);
                                return rtnpos;
                            }

                            if (!string.IsNullOrWhiteSpace(LotID))
                            {
                                //rCV.m_rcvLineInfoDTO.m_invLotCode = result.DocNo;
                                rCV.m_rcvLineInfoDTO.m_invLotCode = LotCode;

                                strlog.AppendLine("创建批号接口成功------------");
                            }
                            else
                            {
                                strlog.AppendLine("创建批号接口失败------------");
                            }
                        }
                        //rCV.m_rcvLineInfoDTO.m_invLotCode = line.BatchCode;
                        locationList.Add(location);
                        rCV.m_rcvLineInfoDTO.m_lineLocations = locationList.ToArray();
                        rCVList.Add(rCV);

                        strlog.AppendLine("来源采购订单行号:" + line.srcDocPOLineNo);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + WHCode);
                        strlog.AppendLine("库存批号:" + line.BatchCode);

                    }
                }
                pOList = rCVList.ToArray();

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                returnItems = client.Do(out returnMsg, context, pOList, splitBy, true);
                List<string> docno = new List<string>();
                if (returnItems != null && returnItems.Length > 0)
                {
                    //获取返回信息得到创建的收货单信息
                    foreach (EntityKey returnInfo in returnItems)
                    {
                        //表头信息
                        rtnRcvInfo rtnpo = new rtnRcvInfo();

                        //行信息 服务不返回 sql查询
                        string sql = @"select A.DocNo as docNo,A1.DocLineNo as docLineNo,A1.ItemInfo_ItemCode,A1.ID as lineID from PM_Receivement A 
                                           left join PM_RcvLine A1 on A.ID=A1.Receivement where A.ID='{0}'";
                        sql = string.Format(sql, returnInfo.ID);
                        DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count > 0)
                        {
                            List<rtnRcvLine> pOLines = new List<rtnRcvLine>();
                            foreach (DataRow dr in dt.Rows)
                            {
                                rtnpo.DocNo = dr["docNo"].ToString();
                                docno.Add(dr["docNo"].ToString());
                                rtnpo.IsSuccess = true;
                                rtnRcvLine line = new rtnRcvLine();
                                line.LineNo = int.Parse(dr["docLineNo"].ToString());
                                line.LogId = "";

                                pOLines.Add(line);
                            }
                            rtnpo.rtnLines = pOLines.ToArray();
                        }
                        rtnpos.Add(rtnpo);
                    }
                }

                foreach (string item in docno)
                {
                    string sql = @"select  A.Status
                                        from  PM_Receivement as A  
                                        where A.DocNo='" + item + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    string Status = dt.Rows[0]["Status"].ToString();

                    if (Status != "5")
                    {
                        UFIDA.ISV.BFRCVApprove.CustBFRCVApprove.ReturnValue1 SH = CustBFRCVApprove.CustApproveRec(item, rCVInfoList[0].lines[0].FurnaceNo, "审核");
                        if (!SH.IsSuccess)
                            throw new Exception("单据：" + item + "审核错误，错误提示：" + SH.Mes + "！");
                    }
                }

                strlog.AppendLine("返回数据:");
                foreach (var info in rtnpos)
                {
                    strlog.AppendLine("单号:" + info.DocNo);
                    strlog.AppendLine("结果:" + info.IsSuccess);
                    strlog.AppendLine("返回消息:" + info.Message);
                    foreach (var _line in info.rtnLines)
                    {
                        strlog.AppendLine("行号:" + _line.LineNo);
                    }
                }
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建委外收货单");

                return rtnpos;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                rtnpo.IsSuccess = false;
                rtnpo.Message = GetExceptionMessage(ex);
                rtnpos.Add(rtnpo);

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建委外收货单");
                strlog.AppendLine("*****************************************************");
                foreach (var item in rCVInfoList)
                {
                    strlog.AppendLine("来源采购订单号:" + item.OOCode);
                    foreach (var line in item.lines)
                    {
                        strlog.AppendLine("来源采购订单行号:" + line.srcDocPOLineNo);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + line.WhCode);
                        strlog.AppendLine("库存批号:" + line.BatchCode);
                    }
                }
                strlog.AppendLine("返回消息：" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建委外收货单");

                return rtnpos;
            }
            #endregion
        }

        #region 表头类
        public class rCVhead
        {
            private rCVLine[] _lines;
            private string _srcDocPONo;

            private string _DocType;

            private DateTime _DocDate;

            private DateTime _ArrDate;


            /// 来源采购订单
            /// </summary>
            public DateTime DocDate
            {
                get { return _DocDate; }
                set { _DocDate = value; }
            }

            /// 来源采购订单
            /// </summary>
            public DateTime ArrDate
            {
                get { return _ArrDate; }
                set { _ArrDate = value; }
            }
            public rCVLine[] lines
            {
                get { return _lines; }
                set { _lines = value; }
            }

            /// <summary>
            /// 来源采购订单
            /// </summary>
            public string OOCode
            {
                get { return _srcDocPONo; }
                set { _srcDocPONo = value; }
            }


            public string DocType
            {
                get { return _DocType; }
                set { _DocType = value; }
            }
        }
        #endregion

        #region 表体类
        public class rCVLine
        {
            /// <summary>
            /// 数量
            /// </summary>
            public decimal Quantity { get; set; }

            public string WhCode { get; set; }

            public string BinCode { get; set; }

            /// <summary>
            /// 炉号
            /// </summary>
            public string FurnaceNo { get; set; }


            /// <summary>
            /// 来源采购订单料号
            /// </summary>
            public string InvCode { get; set; }


            /// <summary>
            /// 来源采购订单行
            /// </summary>
            public int srcDocPOLineNo { get; set; }


            /// <summary>
            /// 库存批号
            /// </summary>
            public string BatchCode { get; set; }
            /// 私有段1
          

            public string cFree1 { get; set; }
            /// 私有段2
            public string cFree2 { get; set; }

            public string cFree3 { get; set; }
            public string cFree4 { get; set; }
            public string cFree5 { get; set; }
            public string cFree6 { get; set; }
            public string cFree7 { get; set; }
            public string cFree8 { get; set; }
            public string cFree9 { get; set; }
            public string cFree10 { get; set; }

            public string LogId { get; set; }

        }
        #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()
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", ConfigurationManager.AppSettings["orgID"].ToString());
            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 时间戳方法
        private DateTime TimestampToDateTime(long timestamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = timestamp * 10000000;
            TimeSpan nowTimeSpan = new TimeSpan(lTime);
            DateTime resultDateTime = dateTimeStart.Add(nowTimeSpan);
            return resultDateTime;
        }
        #endregion
    }

    #region 上下文类信息
    public class contextInfo
    {
        private long _OrgID;
        private string _OrgCode;
        private long _UserID;
        private string _UserCode;
        private DateTime _Datetime;
        private string _CultureName;
        private string _EnterpriseID;


        /// <summary>
        /// 组织ID
        /// </summary>
        public long OrgID
        {
            get { return _OrgID; }
            set { _OrgID = value; }
        }

        /// <summary>
        /// 组织编码
        /// </summary>
        public string WorkPoint
        {
            get { return _OrgCode; }
            set { _OrgCode = value; }
        }

        /// <summary>
        /// 操作员ID
        /// </summary>
        public long UserID
        {
            get { return _UserID; }
            set { _UserID = value; }
        }

        /// <summary>
        /// 操作员编码
        /// </summary>
        public string UserCode
        {
            get { return _UserCode; }
            set { _UserCode = value; }
        }

        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Datetime
        {
            get { return _Datetime; }
            set { _Datetime = value; }
        }

        /// <summary>
        /// 语言
        /// </summary>
        public string CultureName
        {
            get { return _CultureName; }
            set { _CultureName = value; }
        }

        /// <summary>
        /// 企业ID号
        /// </summary>
        public string EnterpriseID
        {
            get { return _EnterpriseID; }
            set { _EnterpriseID = value; }
        }

        public contextInfo()
        {
            CultureName = "zh-CN";
            Datetime = DateTime.Now;
        }
    }
    #endregion



    #region 返回信息类
    public class rtnRcvInfo
    {
        public string DocNo { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public rtnRcvLine[] rtnLines { get; set; }
    }

    public class rtnRcvLine
    {
        public int LineNo { get; set; }

        public string LogId { get; set; }

        //public string srcDocNo { get; set; }

        //public int srcLineNo { get; set; }

        //public decimal reqQty { get; set; }

        //public string proCode { get; set; }
    }
    #endregion


    #region 表体类
    //public class rCVLine
    //{
    //    /// <summary>
    //    ///  来源采购订单
    //    /// </summary>
    //    public string OOCode { get; set; }

    //    private int _srcDocPOLineNo;
    //    private decimal _reqQty;
    //    public string WhCode { get; set; }

    //    /// <summary>
    //    /// 炉号
    //    /// </summary>
    //    public string FurnaceNo { get; set; }

    //    /// <summary>
    //    /// 数量
    //    /// </summary>
    //    public decimal Quantity
    //    {
    //        get { return _reqQty; }
    //        set { _reqQty = value; }
    //    }

    //    /// <summary>
    //    /// 来源采购订单行
    //    /// </summary>
    //    public int srcDocPOLineNo
    //    {
    //        get { return _srcDocPOLineNo; }
    //        set { _srcDocPOLineNo = value; }
    //    }
    //}
    #endregion


}
