using ICS.CreateLotMaster;
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 UFIDA.ISV.ATWApproveFCTMatrialPick;
using UFIDA.ISV.BFPMRecedeDelete;
//using UFIDA.ISV.BFPMRecedeDelete;
//using UFIDA.ISV.CreateLotMaster;
using UFSoft.UBF.Exceptions;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
//using UFIDA.ISV.ATWApproveFCTMatrialPick;

namespace UFIDA.ISV.ATWCreatePMIssue
{
    public class CustCreatePMIssue
    {

        /// 创建领料单
        /// </summary>
        /// <returns></returns>
        /// 
        public OperationResult CreatePMIssue(List<PMIssueData> modellist)
        {
            OperationResult result = new OperationResult();
            try
            {
                string _MOCode = string.Empty;
                UFIDAU9ISVPMIssueICreatePMIssue4ExternalClient client = new UFIDAU9ISVPMIssueICreatePMIssue4ExternalClient();
                MessageBase[] message = null;
                UFIDAU9ISVPMIssuePMIssueKeyDTOData[] _result = new UFIDAU9ISVPMIssuePMIssueKeyDTOData[] { };
                List<UFIDAU9ISVPMIssuePMIssueDTOData> molist = new List<UFIDAU9ISVPMIssuePMIssueDTOData>();


                //UFIDAU9CBOPubControllerCommonArchiveDataDTOData docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                string orgID = "";
                foreach (PMIssueData model in modellist)
                {
                    UFIDAU9ISVPMIssuePMIssueDTOData mo = new UFIDAU9ISVPMIssuePMIssueDTOData();
                    if (!string.IsNullOrWhiteSpace(model.SourceCode))
                    {
                        //string orgID = "";
                        string orgsql = @"select ID from Base_Organization
                                      where Code='{0}' ";
                        orgsql = string.Format(orgsql, model.WorkPoint);
                        DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                        if (orgdt.Rows.Count == 0)
                        {
                            throw new Exception("组织编码:" + model.WorkPoint + "不存在!");
                        }
                        else
                        {
                            orgID = orgdt.Rows[0]["ID"].ToString();
                        }

                        long WGID = 0;
                        string llsql = @"select ID from PM_PurchaseOrder
                                         where DOCNO='{0}' and Org ='" + orgID + "'";
                        llsql = string.Format(llsql, model.SourceCode);
                        DataTable lldt = DBhlper.Query(llsql, Appconfig.GetU9ConnStr());
                        if (lldt.Rows.Count > 0)
                        {
                            WGID = long.Parse(lldt.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            throw new Exception("委外订单:" + model.SourceCode + "不存在!");
                        }
                        long IssueDocTypeID = 0;
                        string IssueDocType = "";
                        int IssueBusinessType = 0;
                        string IssueDocTypeCode = "";
                        string doctypesql = @"select C.ID,B.Code AS DocTypeCode,B.BusinessType,C.Code
											  from PM_PurchaseOrder A
										   	  LEFT JOIN PM_PODocType B ON B.ID=A.DocumentType AND B.Org=A.Org
											  LEFT JOIN PM_IssueDocType C ON C.BusinessType=B.BusinessType AND C.Org=B.Org
											  LEFT JOIN PM_IssueDocType_Trl D ON D.ID=C.ID AND D.SysMLFlag='zh-CN'
											  where A.DocNo='{0}' AND A.Org={1} AND D.Name like '%非成套%'";
                        doctypesql = string.Format(doctypesql, model.SourceCode, orgID);
                        DataTable doctypedt = DBhlper.Query(doctypesql, Appconfig.GetU9ConnStr());
                        if (doctypedt.Rows.Count != 0)
                        {
                            IssueDocTypeID = long.Parse(doctypedt.Rows[0]["ID"].ToString());
                            IssueDocType = doctypedt.Rows[0]["DocTypeCode"].ToString();
                            IssueBusinessType = int.Parse(doctypedt.Rows[0]["BusinessType"].ToString());
                            IssueDocTypeCode = doctypedt.Rows[0]["Code"].ToString();
                        }
                        mo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        mo.m_docType.m_iD = IssueDocTypeID;


                        mo.m_docType.m_code = IssueDocTypeCode;
                        mo.m_businessType = IssueBusinessType;
                        mo.m_businessCreatedOn = model.DocDate;
                        List<UFIDAU9ISVPMIssuePMIssueLineDTOData> picklist = new List<UFIDAU9ISVPMIssuePMIssueLineDTOData>();
                        List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData> polist = new List<UFIDAU9CBOPubControllerCommonArchiveDataDTOData>();
                        #region 遍历入参LL单行
                        foreach (var item in model.details)
                        {
                            long WGLineID = 0;
                            string WGLineNO = "";
                            llsql = @"select ID,DocLineNo from PM_POLine 
                                  where ID='{0}'";
                            llsql = string.Format(llsql, item.SourceLineID);
                            lldt = DBhlper.Query(llsql, Appconfig.GetU9ConnStr());
                            if (lldt.Rows.Count > 0)
                            {
                                WGLineID = long.Parse(lldt.Rows[0]["ID"].ToString());
                                WGLineNO = lldt.Rows[0]["DocLineNo"].ToString();
                            }
                            else
                            {
                                throw new Exception("委外订单行不存在!");
                            }
                            long WHID = 0;
                            long ItemID = 0;
                            bool IsLot = false;
                            string OutboundType = "";
                            llsql = @"select ID,OutboundType,IsLot from CBO_Wh
                                      where Code='{0}' and org ='" + orgID + "'";
                            llsql = string.Format(llsql, item.WHCode);
                            lldt = DBhlper.Query(llsql, Appconfig.GetU9ConnStr());
                            if (lldt.Rows.Count > 0)
                            {
                                WHID = long.Parse(lldt.Rows[0]["ID"].ToString());
                                OutboundType = lldt.Rows[0]["OutboundType"].ToString();
                                IsLot = Convert.ToBoolean(lldt.Rows[0]["IsLot"].ToString());
                            }
                            else
                            {
                                throw new Exception("存储地点:" + item.WHCode + ",不存在!");
                            }
                            llsql = @"select ID from CBO_ItemMaster
                                      where Code='{0}' AND Org='{1}'";
                            llsql = string.Format(llsql, item.InvCode, orgID);
                            lldt = DBhlper.Query(llsql, Appconfig.GetU9ConnStr());
                            if (lldt.Rows.Count > 0)
                            {
                                ItemID = long.Parse(lldt.Rows[0]["ID"].ToString());
                            }
                            else
                            {
                                throw new Exception("料号:" + item.InvCode + ",不存在!");
                            }
                            long SCMPickID = 0;
                            string SupplierCode = "";
                            long SupplierID = 0;
                            llsql = @"select A.ID,ISNULL(D.Supplier_Code,'') AS Supplier_Code
                                ,ISNULL(D.Supplier_Supplier,0) AS Supplier_Supplier from CBO_SCMPickList A
                                LEFT JOIN CBO_SCMPickHead B
                                ON B.ID=A.PicKHead
                                LEFT JOIN PM_POLine C
                                ON C.ID=B.POLine
                                LEFT JOIN PM_PurchaseOrder D
                                ON D.ID=C.PurchaseOrder
                                WHERE A.ID='{0}'";
                            llsql = string.Format(llsql, item.SourceDetailID);
                            lldt = DBhlper.Query(llsql, Appconfig.GetU9ConnStr());
                            if (lldt.Rows.Count > 0)
                            {
                               

                                SCMPickID = long.Parse(lldt.Rows[0]["ID"].ToString());
                                SupplierCode = lldt.Rows[0]["Supplier_Code"].ToString();
                                SupplierID = long.Parse(lldt.Rows[0]["Supplier_Supplier"].ToString());
                            }
                            else
                            {
                                throw new Exception("采购订单备料行ID查询失败!");
                            }
                            //ConfigurationManager.AppSettings["orgID"].ToString()
                            UFIDAU9ISVPMIssuePMIssueLineDTOData pickinfo = new UFIDAU9ISVPMIssuePMIssueLineDTOData();
                            UFIDAU9CBOPubControllerCommonArchiveDataDTOData poinfo = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            pickinfo.m_sCMPickList = SCMPickID;
                            pickinfo.m_issuedQty = item.Quantity;
                            pickinfo.m_issueQty = item.Quantity;
                            pickinfo.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            pickinfo.m_issueWh.m_code = item.WHCode;
                            pickinfo.m_issueWh.m_iD = WHID;
                            if (OutboundType == "1")
                            {
                                pickinfo.m_supplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                pickinfo.m_supplier.m_iD = SupplierID;
                                pickinfo.m_supplier.m_code = SupplierCode;
                            }
                            pickinfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            pickinfo.m_item.m_iD = ItemID;

                            #region 获取批号ID
                            long LotID = 0;
                            if (item.BatchCode != "" && IsLot == true)
                            {
                                string lotsql = @"SELECT ID FROM Lot_LotMaster
                                                  WHERE LotCode='{0}' AND ItemCode='{1}'";
                                lotsql = string.Format(lotsql, item.BatchCode, item.InvCode);
                                DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                                if (lotdt.Rows.Count == 0)
                                {
                                    throw new Exception("传入批号对应料号无关联，获取批号ID失败！");
                                }
                                else
                                {
                                    LotID = long.Parse(lotdt.Rows[0]["ID"].ToString());
                                }
                            }
                            #endregion
                            if (LotID != 0)
                            {
                                pickinfo.m_lot = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                pickinfo.m_lot.m_iD = LotID;
                                pickinfo.m_lot.m_code = item.BatchCode;
                            }
                            picklist.Add(pickinfo);
                            poinfo.m_iD = WGLineID;
                            polist.Add(poinfo);
                        }
                        mo.m_pickListDTOs = picklist.ToArray();
                        mo.m_pOLine = polist.ToArray();
                        molist.Add(mo);
                        #endregion
                    }
                    else
                    {
                        throw new Exception("委外订单号为空！");
                    }
                }

                ThreadContext context = CreateContextObj(orgID);
                _result = client.Do(out message, context, molist.ToArray());

                if (_result != null && _result.Count() > 0)
                {
                    List<string> _DocCodeList = new List<string>();
                    string meg = "";
                    string err = "";
                    for (int i = 0; i < _result.Count(); i++)
                    {
                        if (_result[i].m_docNo.ToString() == "")
                            continue;
                        List<string> LLCodeList = new List<string>();
                        LLCodeList.Add(_result[i].m_docNo.ToString());

                        ATWFCTMatrialPick.OperationResult shResult = new ATWFCTMatrialPick.OperationResult();
                        ATWFCTMatrialPick sh = new ATWFCTMatrialPick();
                        shResult = sh.CustLLState(LLCodeList, orgID);
                        if (shResult.IsSuccess == true)
                        {
                            result.Success = true;
                            for (int z = 0; z < _result.Count(); z++)
                            {
                                if (_result[i].m_docNo.ToString() == "")
                                    continue;
                                if (meg == "")
                                    meg = _result[i].m_docNo.ToString();
                                else
                                    meg += "," + _result[i].m_docNo.ToString();
                            }
                            result.LLCode = _result[i].m_docNo;
                        }
                        else
                        {
                            _DocCodeList.Add(_result[i].m_docNo.ToString());
                            result.Success = false;
                            err += shResult.Message;
                            result.Message = err;
                            result.Success = false;

                            BFPMRecedeDelete.CustDeleteBFPMRecede.CustBFPMRecedeDelete(_DocCodeList, orgID);

                        }
                    }

                    result.Success = true;
                    if (err != "")
                    {
                        result.Message = err;
                        result.Success = false;
                    }
                    else
                        result.Message = "委外发料单创建成功!";
                }
            }
            catch (Exception ex)
            {
                string Message = GetExceptionMessage(ex);
                result.Success = false;
                result.Message += Message;
            }

            result.Data = new List<Data> { new Data { details = new List<DataLine> { new DataLine { LogId = "" } } } };
            return result;
        }


        # 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


        #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 OperationResult
        {
            /// <summary>
            /// 结果状态,默认值false
            /// </summary>
            public bool Success { get; set; }

            /// <summary>
            ///处理消息
            /// </summary>
            public string Message { get; set; }

            /// <summary>
            /// 输出领料订单
            /// </summary>
            public string LLCode { get; set; }
            public List<Data> Data { get; set; }
        }

        public class Data
        {
            public string ID { get; set; }
            public string IssueCode { get; set; }
            public string cDepCode { get; set; }
            public string cDepName { get; set; }
            public string cWHCode { get; set; }
            public string cWHName { get; set; }
            public string cMaker { get; set; }
            public DateTime dnmaketime { get; set; }
            public List<DataLine> details { get; set; }
        }

        public class DataLine
        {
            public string SourceDetailID { get; set; }
            public int Sequence { get; set; }
            public string cInvCode { get; set; }
            public Decimal iQuantity { get; set; }
            public string DetailID { get; set; }
            public Decimal Amount { get; set; }
            public string cBatch { get; set; }
            public string brand { get; set; }
            public string cFree1 { get; set; }
            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; }
        }

    }


}
