using ICS.BFIssueDelete;
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.BFIssueApprove;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.CreateAboveIssueMore
{
    public class CustCreateAboveIssue
    {
        /// <summary>
        /// 创建领料单
        /// </summary>
        /// <returns></returns>
        /// 
        public OperationResult CreateAboveIssue(List<IssueAboveData> modellist)
        {

            OperationResult result = new OperationResult();
            ThreadContext context = CreateContextObj();
            string OrgID = "";
            try
            {
                string _MOCode = string.Empty;
                UFIDAU9ISVMOICreateIssue4ExternalClient client = new UFIDAU9ISVMOICreateIssue4ExternalClient();
                MessageBase[] message = null;
                List<UFIDAU9ISVMOIssueDTOData> molist = new List<UFIDAU9ISVMOIssueDTOData>();
                UFIDAU9ISVMOIssueDTOData mo = new UFIDAU9ISVMOIssueDTOData();
                List<UFIDAU9ISVMOPickListDTOData> PL = new List<UFIDAU9ISVMOPickListDTOData>();
                foreach (IssueAboveData model in modellist)
                {
                    mo = new UFIDAU9ISVMOIssueDTOData();
                    PL = new List<UFIDAU9ISVMOPickListDTOData>();
                    if (!string.IsNullOrWhiteSpace(model.SourceCode))
                    {
                        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)
                        {
                            OrgID = orgdt.Rows[0]["ID"].ToString();
                        }
                        else
                        {
                            throw new Exception("未获取到组织!");
                        }
                        //验证该工单的备料表中是否存在数据
                        int p = Appconfig.IsExistcPickList(model.SourceCode);

                        if (p > 0)
                        {
                            #region 遍历入参LL单行

                            foreach (var item in model.details)
                            {
                                bool IsVMI = false;
                                string strCcode = item.InvCode; //子料
                                decimal _useQty = item.Quantity; //子件使用量

                                string _strWhID = string.Empty;//仓库ID
                                string WHID = "";

                                if (!string.IsNullOrWhiteSpace(strCcode))
                                {
                                    //虚拟库位 ZP1-01 20190912新增过滤虚拟库位

                                    string _SqlDbType = @"  select Distinct ID,Code from CBO_WH
                                                        where Code='" + item.WHCode + "' AND Org='" + OrgID + "'";
                                    _SqlDbType = string.Format(_SqlDbType);
                                    DataTable _SqlDbTypedt = DBhlper.Query(_SqlDbType, Appconfig.GetU9ConnStr());
                                    if (_SqlDbTypedt != null && _SqlDbTypedt.Rows.Count > 0)
                                    {
                                        WHID = _SqlDbTypedt.Rows[0]["ID"].ToString();
                                    }
                                    else
                                    {
                                        result.Message = "传入仓库不存在!";
                                        result.Success = false;
                                        return result;
                                    }
                                }

                                UFIDAU9ISVMOPickListDTOData PLS = new UFIDAU9ISVMOPickListDTOData();

                                PLS.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();

                                PLS.m_descFlexField.m_privateDescSeg1 = item.cFree1;
                                PLS.m_descFlexField.m_privateDescSeg2 = item.cFree2;
                                PLS.m_descFlexField.m_privateDescSeg3 = item.cFree3;
                                PLS.m_descFlexField.m_privateDescSeg4 = item.cFree4;
                                PLS.m_descFlexField.m_privateDescSeg5 = item.cFree5;
                                PLS.m_descFlexField.m_privateDescSeg6 = item.cFree6;
                                PLS.m_descFlexField.m_privateDescSeg7 = item.cFree7;
                                PLS.m_descFlexField.m_privateDescSeg8 = item.cFree8;
                                PLS.m_descFlexField.m_privateDescSeg9 = item.cFree9;
                                PLS.m_descFlexField.m_privateDescSeg10 = item.cFree10;

                                int i = Appconfig.IsExistItem(strCcode);
                                if (i < 1)
                                {
                                    result.Message = "料品编码不存在!";
                                    result.Success = false;
                                    return result;
                                }

                                Decimal MOQty = 0;
                                long MOID = 0;
                                _MOCode = model.SourceCode;
                                DataTable _dt = Appconfig.GetMOQtyAndID(model.SourceCode,OrgID);
                                if (_dt != null && _dt.Rows.Count > 0)
                                {
                                    foreach (DataRow _item in _dt.Rows)
                                    {
                                        string _strMOQty = string.Empty;
                                        string _strMOID = string.Empty;

                                        _strMOQty = _item["ProductQty"].ToString();
                                        if (!string.IsNullOrWhiteSpace(_strMOQty))
                                        {
                                            MOQty = Decimal.Parse(_strMOQty);//生产订单数量
                                        }
                                        _strMOID = _item["ID"].ToString();
                                        if (!string.IsNullOrWhiteSpace(_strMOID))
                                        {
                                            MOID = long.Parse(_strMOID);
                                        }
                                    }
                                }

                                string mOPickList = string.Empty;
                                mOPickList = Appconfig.GetMoPickListID(model.SourceCode, strCcode, OrgID);// 1001903220007058;// iPickid;
                                Decimal IssuedQty = 0;   //已发放数量
                                Decimal ActualReqQty = 0; //实际需求数量
                                if (!string.IsNullOrWhiteSpace(mOPickList))
                                {
                                    //已发放数量-领料未发数量
                                    DataTable dtQty = Appconfig.GetQtyBymOPickList(model.SourceCode, strCcode);
                                    if (dtQty != null && dtQty.Rows.Count > 0)
                                    {
                                        ActualReqQty = Decimal.Parse(dtQty.Rows[0]["ActualReqQty"].ToString());
                                    }
                                    PLS.m_mOPickList = long.Parse(mOPickList);
                                }
                                else
                                {
                                    result.Message = "备料表单ID不存在!工单：'" + model.SourceCode + "',料号：'" + strCcode + "' ";
                                    result.Success = false;
                                    return result;
                                }

                                //PLS.m_issueQty = useQty * MOQty - SendQty;// item.issueQty* useQty;//1;   //应发数量

                                //if (ActualReqQty < _useQty)
                                //{
                                //    result.Message += "该料品" + strCcode + "需要领用的数量大于未领数量不能创建改料品的领用;";
                                //}
                                //else
                                //{




                                //if (useQty * MOQty - SendQty - IssueNotDeliverQty > 0)
                                //{
                                //20190920修改ZM
                                //PLS.m_issuedQty = useQty * MOQty - SendQty - IssueNotDeliverQty;// item.issuedQty* useQty;// 1;  //实发数量

                                PLS.m_issueQty = _useQty;
                                PLS.m_issuedQty = _useQty;// item.issuedQty* useQty;// 1;  //实发数量

                                //仓库
                                if (!string.IsNullOrWhiteSpace(WHID))
                                {
                                    PLS.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                    //PLS.m_issueWh.m_code = strWhCode;// "004";//cWh;
                                    PLS.m_issueWh.m_iD = long.Parse(WHID);// "004";//cWh;

                                }
                                //发货单位
                                PLS.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                string uom = Appconfig.GetMaterialUOM(strCcode);
                                if (!string.IsNullOrWhiteSpace(uom))
                                {
                                    PLS.m_issueUOM.m_iD = long.Parse(uom);// Appconfig.GetMaterialUOM(item.InvCode);// 1001607080022602;// iMaterialOutUOM;
                                }
                                PLS.m_aCDType = 0;
                                PLS.m_storageType = 4;//存储类型
                                                      //SourceDoc_SrcDocNo
                                PLS.SourceIssueDocLine = MOID;
                                #region 获取批号ID
                                long LotID = 0;
                                if (item.BatchCode != "")
                                {
                                    string lotsql = @"SELECT ID FROM Lot_LotMaster
                                                      WHERE LotCode='{0}' AND ItemCode='{1}'
                                                      AND ItemOwnerOrg='{2}'";
                                    lotsql = string.Format(lotsql, item.BatchCode, item.InvCode, OrgID);
                                    DataTable lotdt = DBhlper.Query(lotsql, Appconfig.GetU9ConnStr());
                                    if (lotdt.Rows.Count == 0)
                                    {
                                        result.Message += "传入批号对应料号无关联，获取批号ID失败！";
                                        result.Success = false;
                                        return result;
                                    }
                                    else
                                    {
                                        LotID = long.Parse(lotdt.Rows[0]["ID"].ToString());
                                    }
                                }
                                #endregion
                                if (LotID != 0)
                                {
                                    PLS.m_lot = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                    PLS.m_lot.m_code = item.BatchCode;
                                    PLS.m_lot.m_iD = LotID;
                                }
                                if (IsVMI == true)
                                {
                                    PLS.m_supplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                    PLS.m_supplier.m_code = item.Vender;
                                }

                                PL.Add(PLS);
                            }

                            //}

                            #endregion
                        }
                        else
                        {
                            result.Message += "该工单没有备料表信息 ";
                            result.Success = false;

                            return result;
                        }
                        if (PL != null && PL.Count() > 0)
                        {
                            //部门
                            mo.m_dept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            mo.m_dept.m_code = model.DepCode;// "MY0601";
                            mo.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            #region 获取生产订单单据类型（作为生产领料单的业务类型）
                            //string IssueDocType = "";
                            int IssueBusinessType = 0;
                            string IssueDocTypeCode = "";
                            string DocTypeID = "";


                            //string doctypesql = @"SELECT     c.Code AS DocTypeCode,    aa.BusinessType,aa.Code,aa.ID
                            //                        FROM     MO_MO A
                            //                        LEFT JOIN MO_MODocType c ON c.ID = A.MODocType AND c.Org = A.Org
                            //                        LEFT JOIN   MO_IssueDocType aa ON c.BusinessType=aa.BusinessType
                            //                        LEFT JOIN MO_IssueDocType_Trl b ON aa.ID=b.ID AND b.SysMLFlag='zh-CN'
                            //                       WHERE a.DocNo='{0}' AND a.Org={1} AND b.Name='生产领料单'";

                            string doctypesql = @"SELECT       aa.BusinessType,aa.Code,aa.ID
                                                    FROM       MO_IssueDocType aa  
                                                   WHERE aa.Code='{0}' AND aa.Org={1} ";

                            doctypesql = string.Format(doctypesql, model.DocTypeCode, OrgID);
                            DataTable doctypedt = DBhlper.Query(doctypesql, Appconfig.GetU9ConnStr());
                            if (doctypedt.Rows.Count != 0)
                            {
                                //IssueDocType = doctypedt.Rows[0]["DocTypeCode"].ToString();
                                IssueBusinessType = int.Parse(doctypedt.Rows[0]["BusinessType"].ToString());
                                IssueDocTypeCode = doctypedt.Rows[0]["Code"].ToString();
                                DocTypeID = doctypedt.Rows[0]["ID"].ToString();
                            }
                            #endregion
                            //mo.m_docType.m_code = IssueDocType;
                            mo.m_docType.m_code = IssueDocTypeCode;
                            mo.m_businessType = IssueBusinessType;
                            mo.m_issueType = 3;
                            mo.m_businessDate = DateTime.Now;

                            string BusinessType = Appconfig.GetBusinessType(model.DocTypeCode);
                            mo.m_srcDoc = new UFIDAU9MOPropertyTypesMOSourceDocData();// _MOCode;
                            mo.m_srcDoc.m_srcDocNo = _MOCode;

                            //mo.m_memo = model.Memo; //备注
                            mo.m_memo = model.SuperCollarMessage; //备注

                            mo.m_pickListDTOs = PL.ToArray();

                            molist.Add(mo);
                        }
                        else
                        {
                            result.Message += "传入的数据未获取到创建领料的信息 ";
                            result.Success = false;

                            return result;
                        }
                    }
                    else
                    {
                        result.Message += "该工单号不能为空 ";
                        result.Success = false;

                        return result;
                    }
                }

                UFIDAU9ISVMOIssueKeyDTOData[] _result = null;
                _result = client.Do(out message, context, molist.ToArray());
                List<string> LLCodeList = new List<string>();
                if (_result != null && _result.Count() > 0)
                {
                    foreach (var item in _result)
                    {
                        if (!string.IsNullOrWhiteSpace(item.m_docNo))
                        {
                            LLCodeList.Add(item.m_docNo);
                        }
                    }
                }
                #region 审核生产领料单
                CustApproveIssue approveIssue = new CustApproveIssue();
                CustApproveIssue.OperationResult approveresult = new CustApproveIssue.OperationResult();
                approveresult = approveIssue.CustBFApproveIssue(LLCodeList, modellist[0].WorkPoint);
                #endregion
                if (approveresult.IsSuccess == true)
                {
                    foreach (string docno in LLCodeList)
                    {
                        result.Data += docno + ";";
                    }
                    result.Success = true;
                    result.Message = "成功创建领料单！";
                }
                else
                {
                    #region 审核失败日志
                    StringBuilder strlog = new StringBuilder();
                    strlog.AppendLine("审核失败日志记录开始");
                    strlog.AppendLine("*****************************************************");
                    foreach (string code in LLCodeList)
                    {
                        strlog.AppendLine("领料单号:" + code);
                    }
                    strlog.AppendLine("失败原因:" + approveresult.MESSAGE);
                    strlog.AppendLine("*****************************************************");
                    Appconfig.WriteLogFile(strlog.ToString(), "创建U9领料单");
                    #endregion
                    #region 审核失败时删除所有生成的领料单
                    CustBFIssueDelete issueDelete = new CustBFIssueDelete();
                    issueDelete.CustDeleteIssue(LLCodeList, OrgID);
                    #endregion
                    result.Success = false;
                    result.Message = "领料单审核失败，生成的领料单已经删除,失败原因:" + approveresult.MESSAGE;
                }
            }
            catch (Exception ex)
            {
                #region 错误日志
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("错误日志记录开始");
                strlog.AppendLine("*****************************************************");
                foreach (IssueAboveData model in modellist)
                {
                    strlog.AppendLine("领料部门:" + model.DepCode);
                    strlog.AppendLine("生产订单:" + model.SourceCode);
                    strlog.AppendLine("组织编码:" + model.WorkPoint);
                    strlog.AppendLine("备注:" + model.Memo);
                    foreach (IssueLineData lineinfo in model.details)
                    {
                        strlog.AppendLine("领料料号:" + lineinfo.InvCode);
                        strlog.AppendLine("领料数量:" + lineinfo.Quantity);
                        strlog.AppendLine("存储地点:" + lineinfo.WHCode);
                    }
                }
                strlog.AppendLine("失败原因:" + GetExceptionMessage(ex));
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建U9领料单");
                #endregion
                string Message = GetExceptionMessage(ex);
                result.Success = false;
                result.Message += Message;
            }
            //"必需设置请指定IssueDTO.BusinessType属性，生产线日计划：51，标准生产：47，返工生产：48，报废生产：49"
            return result;
        }

        # region 辅助方法
        /// <summary>
        /// 创建上下文
        /// </summary>
        /// <returns></returns>
        private static 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 提取异常信息
        /// <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 object Data { get; set; }
        }


        #region 20190705


        #endregion


        public class IssueAboveData
        {
            /// <summary>
            /// 申请部门
            /// </summary>
            public string DepCode { get; set; }

            /// <summary>
            /// 领料单据类型    1--生产领料单
            /// </summary>
            public string DocTypeCode { get; set; }

            /// <summary>
            /// 生产工单 
            /// </summary>
            public string SourceCode { get; set; }

            public string Memo { get; set; }//备注
            /// <summary>
            /// 组织编码
            /// </summary>
            public string WorkPoint { get; set; }

            //public string WhCode { get; set; }//仓库
            //public string BinCode { get; set; }//库位 20190917换到表体上
            public List<IssueLineData> details { get; set; }


            public string SuperCollarMessage { get; set; }

        }

        public class IssueData_bak20190709
        {
            /// <summary>
            /// 申请部门
            /// </summary>
            public string DepCode { get; set; }

            /// <summary>
            /// 领料单据类型    1--生产领料单
            /// </summary>
            public string DocTypeCode { get; set; }

            /// <summary>
            /// 生产工单 
            /// </summary>
            public string SourceCode { get; set; }

            public string Memo { get; set; }//备注

            public string WhCode { get; set; }//仓库
            public string BinCode { get; set; }//库位 
            public List<IssueLineData> details { get; set; }

        }

        public class IssueLineData
        {
            public string SubLineNO { get; set; }//工单子件行号
            public string InvCode { get; set; }//子料号
            public Decimal Quantity { get; set; }//子料数量
            public string WHCode { get; set; }//存储地点 
            public string BatchCode { get; set; }//领料批号
            public string Vender { get; set; }//供应商

            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; }
        }


        public class RtnIssueData
        {
            public string DocNo { get; set; }//单号
            public List<IssueLineData> lines { get; set; }//行
        }
    }


}
