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 ICSSoft.APIApproveCompRpt;
using ICSSoft.APIDeleteCompRpt;
using ICSSoft.APICloseCompRpt;
using UFIDA.ISV.CreateRcvRpt;
using ICSSoft.DataProject;
using ICS.WCF.Base;
using UFIDA.ISV.CreateRcvRptByApply;
using UFIDA.ISV.RcvRptDelete;
using UFIDA.ISV.RcvRptApprove;

namespace ICSSoft.APICreateCompRpt
{
    public class CreateCompRpt
    {
        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"];
        /// <summary>
        /// 创建完工报告（外部通过API调用）
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public Result Create(List<ICSManufactureReceiveDoc> infos)
        {
            var res = new Result();
            var datalist = new List<ICSManufactureReceiveDoc>();
            //var doclist = new Dictionary<string, string>();
            string OrgID = "";
            var UserCode = "";
            var UserID = "";
            var UserName = "";
            foreach (var info in infos)
            {
                try
                {
                    DataSet ds = new DataSet();
                    UFIDAU9ISVMOICreateCompRptSrvClient client = new UFIDAU9ISVMOICreateCompRptSrvClient();
                    //服务返回结果
                    UFIDAU9ISVMOCompRptKeyDTOData[] returnItem;
                    //返回异常信息，目前还没有使用此属性
                    UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                    //上下文信息
                    object context;
                    //传入 参数
                    UFIDAU9ISVMOCompRptDTOData[] compRptDTOs;
                    List<string> DocNoList = new List<string>();


                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入的组织编码有误!");
                    }




                    string sql = @"select ID,Name from base_user
                                                   where Code='{0}'";
                    sql = string.Format(sql, info.User);
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        sql = @"select ID,Name from base_user
                                                   where Code='{0}'";
                        sql = string.Format(sql, Appconfig.GetDefaultUser());
                        dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("未获取到用户ID");
                        }
                        UserCode = Appconfig.GetDefaultUser();
                        UserID = dt.Rows[0]["ID"].ToString();
                        UserName =  dt.Rows[0]["Name"].ToString();
                    }
                    else
                    {
                        UserCode = info.User;
                        UserID = dt.Rows[0]["ID"].ToString();
                        UserName = dt.Rows[0]["Name"].ToString();
                    }



                    UFIDA.ISV.CreateRcvRpt.rtnRcvInfo completeres = new UFIDA.ISV.CreateRcvRpt.rtnRcvInfo();
                    CustCreateRcvRptSrv completesrv = new CustCreateRcvRptSrv();
                    List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo> ListInfo = new List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo>();
                    CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo Info = new CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo();
                    List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine> LineListInfo = new List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine>();
                    CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine LineInfo = new CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine();

                    Info = new CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo();
                    Info.MOCode = info.MOCode;
                    Info.WorkPoint = info.WorkPoint;
                    LineListInfo = new List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine>();
                    foreach (ICSManufactureReceiveDocs completelineInfo in info.details)
                    {
                        LineInfo = new CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine();
                        LineInfo.MODetailID = completelineInfo.MODetailID;
                        LineInfo.Sequence = completelineInfo.Sequence;
                        LineInfo.InvCode = completelineInfo.InvCode;
                        LineInfo.Quantity = completelineInfo.Quantity;
                        LineInfo.BatchCode = completelineInfo.BatchCode;
                        LineInfo.WHCode = completelineInfo.WHCode;
                        LineInfo.Version = completelineInfo.Version;
                        LineInfo.LogIds = completelineInfo.LogIds;
                        LineListInfo.Add(LineInfo);
                    }
                    Info.details = LineListInfo;
                    ListInfo.Add(Info);

                    Result approveres = new Result();
                    if (Appconfig.GetMoRptType() == "成品入库")
                    {
                        approveres = completesrv.CreateRcvRptByMo(ListInfo, OrgID, UserID, UserCode, datalist, UserName);
                    }
                    else
                    {
                        //context = CreateContextObj(OrgID, UserID, info.User);
                        //compRptDTOs = GetDataNew(infos, OrgID);
                        //returnItem = client.Do(out returnMsg, context, compRptDTOs);
                        //if (returnItem.Length == 0)
                        //{
                        //    throw new Exception("创建单据失败");
                        //}
                        //if (!string.IsNullOrEmpty(returnItem[0].m_errorMsg))
                        //{
                        //    throw new Exception("创建单据失败:"+ returnItem[0].m_errorMsg);
                        //}

                        //DocNoList.Add(returnItem[0].m_docNo);

                        //ApproveCompRpt custApproveComRpt = new ApproveCompRpt();
                        //ApproveResult = custApproveComRpt.Approve(DocNoList, info.WorkPoint);
                    }


                    if (approveres.Success == false)
                    {
                        throw new Exception(approveres.Message);
                    }

                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSManufactureReceiveDocs>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSManufactureReceiveDocs
                        {
                            MODetailID = item.MODetailID,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new ICSManufactureReceiveDoc
                    {
                        IsSuccess = false,
                        Message = "创建失败：" + ex.Message,
                        details = linelist
                    });
                }
            }

            //var a = datalist.Select(x => x.IsSuccess == false).ToList().Count;

            //if (datalist.Where(x => x.IsSuccess == false).ToList().Count > 0)
            //{
            //    if (doclist.Count > 0)
            //    {
            //        foreach (var dic in doclist)
            //        {
            //            if (dic.Value == "2")//弃审删除
            //            {
            //                CustRcvRptApprove rptapprove = new CustRcvRptApprove();
            //                UFIDA.ISV.RcvRptApprove.CustRcvRptApprove.OperationResult result = rptapprove.CustUnApproveRcvRpt(long.Parse(dic.Key), OrgID, UserID, UserCode);
            //                if (result.Success)
            //                {
            //                    CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
            //                    Result deleteres = rptDelete.CustRcvRptDelete(long.Parse(dic.Key), OrgID);
            //                }
            //            }
            //            else
            //            {
            //                CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
            //                Result deleteres = rptDelete.CustRcvRptDelete(long.Parse(dic.Key), OrgID);
            //            }
            //        }
            //    }

            //}



            res.Success = true;
            res.Message = "成功";
            res.Data = datalist;
            return res;
        }


        /// <summary>
        /// 完工申报创建成品入库（外部通过API调用）
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public Result CreateRcvRptByCompleteApplyDoc(List<ICSManufactureReceiveDocComRcvRpt> infos)
        {
            var res = new Result();
            var datalist = new List<ICSManufactureReceiveDocComRcvRpt>();
            //var doclist = new Dictionary<string, string>();
            string OrgID = "";
            var UserCode = "";
            var UserID = "";
            foreach (var info in infos)
            {
                try
                {
                    DataSet ds = new DataSet();
                    UFIDAU9ISVMOICreateCompRptSrvClient client = new UFIDAU9ISVMOICreateCompRptSrvClient();
                    //服务返回结果
                    UFIDAU9ISVMOCompRptKeyDTOData[] returnItem;
                    //返回异常信息，目前还没有使用此属性
                    UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                    //上下文信息
                    object context;
                    //传入 参数
                    UFIDAU9ISVMOCompRptDTOData[] compRptDTOs;
                    List<string> DocNoList = new List<string>();


                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入的组织编码有误!");
                    }




                    string sql = @"select ID from base_user
                                                   where Code='{0}'";
                    sql = string.Format(sql, info.User);
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    if (dt.Rows.Count == 0)
                    {
                        sql = @"select ID from base_user
                                                   where Code='{0}'";
                        sql = string.Format(sql, Appconfig.GetDefaultUser());
                        dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                        if (dt.Rows.Count == 0)
                        {
                            throw new Exception("未获取到用户ID");
                        }
                        UserCode = Appconfig.GetDefaultUser();
                        UserID = dt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        UserCode = info.User;
                        UserID = dt.Rows[0]["ID"].ToString();
                    }




                    Result approveres = new Result();
                    CustCreateRcvRptSrv completesrv = new CustCreateRcvRptSrv();
                    List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo> ListInfo = new List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo>();
                    CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo Info = new CustCreateRcvRptSrv.RcvRptByCompleteApplyInfo();
                    List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine> LineListInfo = new List<CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine>();
                    foreach (ICSManufactureReceiveDocsComRcvRpt completelineInfo in info.details)
                    {
                        CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine LineInfo = new CustCreateRcvRptSrv.RcvRptByCompleteApplyInfoLine();

                        LineInfo.MODetailID = completelineInfo.CRTDetailID;
                        LineInfo.Sequence = completelineInfo.Sequence;
                        LineInfo.InvCode = completelineInfo.InvCode;
                        LineInfo.Quantity = completelineInfo.Quantity;
                        LineInfo.BatchCode = completelineInfo.BatchCode;
                        LineInfo.WHCode = completelineInfo.WHCode;
                        LineInfo.LogIds = completelineInfo.LogIds;
                        LineListInfo.Add(LineInfo);
                    }
                    Info.MOCode = info.CRTCode;
                    Info.WorkPoint = info.WorkPoint;
                    Info.details = LineListInfo;
                    ListInfo.Add(Info);

                    approveres = completesrv.CreateRcvRptByCompleteApplyDoc(ListInfo, OrgID, UserID, UserCode, datalist);

                    if (approveres.Success == false)
                    {
                        throw new Exception(approveres.Message);
                    }


                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSManufactureReceiveDocsComRcvRpt>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSManufactureReceiveDocsComRcvRpt
                        {
                            CRTDetailID = item.CRTDetailID,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new ICSManufactureReceiveDocComRcvRpt
                    {
                        IsSuccess = false,
                        Message = "创建失败：" + ex.Message,
                        details = linelist
                    });
                }
            }

            //var a = datalist.Select(x => x.IsSuccess == false).ToList().Count;

            //if (datalist.Where(x => x.IsSuccess == false).ToList().Count > 0)
            //{
            //    if (doclist.Count > 0)
            //    {
            //        foreach (var dic in doclist)
            //        {
            //            if (dic.Value == "2")//弃审删除
            //            {
            //                CustRcvRptApprove rptapprove = new CustRcvRptApprove();
            //                UFIDA.ISV.RcvRptApprove.CustRcvRptApprove.OperationResult result = rptapprove.CustUnApproveRcvRpt(long.Parse(dic.Key), OrgID, UserID, UserCode);
            //                if (result.Success)
            //                {
            //                    CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
            //                    Result deleteres = rptDelete.CustRcvRptDelete(long.Parse(dic.Key), OrgID);
            //                }
            //            }
            //            else
            //            {
            //                CustDeleteRcvRpt rptDelete = new CustDeleteRcvRpt();
            //                Result deleteres = rptDelete.CustRcvRptDelete(long.Parse(dic.Key), OrgID);
            //            }
            //        }
            //    }

            //}



            res.Success = true;
            res.Message = "成功";
            res.Data = datalist;
            return res;
        }

        /// <summary>
        /// 创建副产品完工报告（外部通过API调用）
        /// </summary>
        /// <param name="infos"></param>
        /// <returns></returns>
        public string CreateFCPCompleteRpt(List<FCPRcvRptInfo> infos)
        {
            string msg = "";
            DataSet ds = new DataSet();
            UFIDAU9ISVMOICreateCompRptSrvClient client = new UFIDAU9ISVMOICreateCompRptSrvClient();
            //服务返回结果
            UFIDAU9ISVMOCompRptKeyDTOData[] returnItem;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVMOCompRptDTOData[] compRptDTOs;
            List<string> DocNoList = new List<string>();
            try
            {
                if (infos == null || infos.Count == 0)
                {
                    throw new Exception("传入数据不能为空!");
                }
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入的组织编码有误!");
                }
                //给上下文信息赋值
                context = CreateContextObj(OrgID, "", "");
                //给传入参数赋值
                compRptDTOs = GetDataForFCP(infos, OrgID);

                //服务调用

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                returnItem = client.Do(out returnMsg, context, compRptDTOs);
                foreach (UFIDAU9ISVMOCompRptKeyDTOData data in returnItem)
                {
                    if (data.m_operateResult == false)
                    {
                        throw new Exception(data.m_errorMsg);
                    }
                    DocNoList.Add(data.m_docNo);
                }
                bool ApproveResult = false;
                ApproveCompRpt custApproveComRpt = new ApproveCompRpt();
                ApproveResult = custApproveComRpt.Approve(DocNoList, infos[0].WorkPoint);
                if (ApproveResult == false)
                {
                    bool DeleteResult = false;
                    DeleteCompRpt delete = new DeleteCompRpt();

                    DeleteResult = delete.Delete(DocNoList, infos[0].WorkPoint);
                }
                else
                {
                    string strDocNOList = "";
                    foreach (string DocNo in DocNoList)
                    {
                        if (strDocNOList == "")
                        {
                            strDocNOList = "'" + DocNo + "'";
                        }
                        else
                        {
                            strDocNOList += ",'" + DocNo + "'";
                        }
                    }
                    string sql = @"select DISTINCT a.ID as ID,a.ID as IDs,a.DocNo as MRCVCode,c.Code AS cDepCode,d.Name AS cDepName
							,e.Code AS WHCode,f.Name AS cWhName
                            ,g.DocNo as MOCode ,a.CreatedBy as CreateUser ,a.CreatedOn as CreateDateTime
                            ,a.ApproveBy as Checker ,a.ApproveOn as CheckDateTime 
                              from MO_CompleteRpt a 
                             left join CBO_Department c on c.ID=a.HandleDept
							 left join CBO_Department_Trl d on d.ID=c.ID
                             left join CBO_Wh e on e.ID=a.RcvWh
							 left join CBO_Wh_Trl f on f.ID=e.ID
							 left join MO_MO g on g.ID=a.MO
							 WHERE A.DocNo in({0}) AND a.Org='{1}'";
                    sql = string.Format(sql, strDocNOList, OrgID);
                    DataTable mdt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    sql = @"select DISTINCT a.ID as IDs, b.ID as DetailID,b.LineNum as Sequence,c.Code as InvCode ,
                            b.RcvQtyByWhUOM as Quantity ,0 as Amount,a.MO as MODetailID,
							isnull(d.Code,'') ProjectCode,isnull(e.LotCode,'') cBatch,'' version ,'' brand,
							a.DescFlexField_PrivateDescSeg15 as cFree1,
							'' as cFree2,
							'' as cFree3,
							'' as cFree4,
							'' as cFree5,
							'' as cFree6,
							'' as cFree7,
							'' as cFree8,
							'' as cFree9,
							'' as cFree10
                            from MO_CompleteRpt a 
                            left join MO_CompleteRptRcvLine b on b.CompleteRpt=a.ID
							left join CBO_ItemMaster c on c.ID=a.Item
							left join CBO_Project d on d.ID=a.Project
							left join Lot_LotMaster e on e.ID=b.RcvLotMaster
							WHERE A.DocNo in({0}) AND a.Org='{1}'";
                    sql = string.Format(sql, strDocNOList, OrgID);
                    DataTable cdt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());

                    DataTable tempdt1 = mdt.Copy();
                    tempdt1.TableName = "tempdt1";
                    ds.Tables.Add(tempdt1);

                    DataTable tempdt2 = cdt.Copy();
                    tempdt2.TableName = "tempdt2";
                    ds.Tables.Add(tempdt2);
                    //}
                    //else
                    //{
                    //    throw new Exception("完工报告关闭失败，创建的完工报告已删除!");
                    //}
                }
            }
            catch (Exception ex)
            {
                if (DocNoList.Count != 0)
                {
                    DeleteCompRpt delete = new DeleteCompRpt();
                    delete.Delete(DocNoList, infos[0].WorkPoint);
                }
                log.Error(GetExceptionMessage(ex));
                throw new Exception(GetExceptionMessage(ex));
            }
            msg = JSON.DataSetToJson(ds, "details", "IDs");
            return msg;
        }

        private static long GetTypeID(string docTypeCode, string OrgID)
        {
            string sql = @"select ID from MO_CompleteRpt where DocNo='" + docTypeCode + "' AND Org='" + OrgID + "' ";
            DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
            if (dt.Rows.Count > 0)
            {
                return long.Parse(dt.Rows[0][0].ToString());
            }
            else
            {
                return 0;
            }
        }

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID, string UserID, string UserCode)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();


            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", UserID);
            ns.Add("UserCode", UserCode);
            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 UFIDAU9ISVMOCompRptDTOData[] GetDataNew(List<ICSManufactureReceiveDoc> CompRptList, string OrgID)
        {
            List<UFIDAU9ISVMOCompRptDTOData> datas = new List<UFIDAU9ISVMOCompRptDTOData>();
            string LotValidTime = ConfigurationManager.ConnectionStrings["LotValidTime"]?.ConnectionString;
            if (LotValidTime == null)
            {
                LotValidTime = "0";
            }
            foreach (ICSManufactureReceiveDoc item in CompRptList)
            {
                int Num = 10;
                UFIDAU9ISVMOCompRptDTOData data = new UFIDAU9ISVMOCompRptDTOData();
                List<UFIDAU9ISVMOCompRptRcvLineDTOData> rcvLineList = new List<UFIDAU9ISVMOCompRptRcvLineDTOData>();
                foreach (ICSManufactureReceiveDocs line in item.details)
                {
                    if (line.Quantity != 0)
                    {
                        data.m_completeQty += line.Quantity;
                        data.m_completeQtyCoUOM += line.Quantity;
                        data.m_completeQtyWhUOM += line.Quantity;
                        data.m_eligibleQty += line.Quantity;
                        data.m_eligibleQtyCoUOM += line.Quantity;
                        data.m_reworkingQtyCoUOM += line.Quantity;
                    }
                    long LotMaster = 0;
                    DateTime DisabledTime = new DateTime();
                    int LotLastTime = 0;
                    string orgsql = @"select LotValidDate,* from CBO_ItemMaster a
                    LEFT JOIN CBO_InventoryInfo b on a.InventoryInfo=b.ID
                    where a.Code='{0}' and Org='{1}'";
                    orgsql = string.Format(orgsql, line.InvCode, OrgID);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        int date = Convert.ToInt32(orgdt.Rows[0]["LotValidDate"].ToString());
                        if (date > 0)
                        {
                            DisabledTime = DateTime.Now.AddDays(date);
                            LotLastTime = date;
                        }
                        else
                        {
                            if (line.ProjectCode == "")
                            {
                                LotLastTime = Convert.ToInt32(LotValidTime);
                                DisabledTime = DateTime.Now.AddDays(Convert.ToInt32(LotValidTime));
                            }
                            else
                            {
                                DisabledTime = Convert.ToDateTime(line.ProjectCode);
                                LotLastTime = Convert.ToDateTime(line.ProjectCode).Subtract(Convert.ToDateTime(line.Brand)).Days;
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("传入的组织编码有误!");
                    }
                    if (!string.IsNullOrWhiteSpace(line.BatchCode))
                    {
                        //创建批号
                        string lotID = "";
                        APICreateLotMaster.CreateLotMaster createLot = new APICreateLotMaster.CreateLotMaster();
                        //APICreateLotMaster.CreateLotMaster.OperationResule result = createLot.Create(item.WHCode, line.InvCode, line.BatchCode, OrgID, ref lotID, Convert.ToDateTime(line.Brand), DisabledTime, LotLastTime);
                        APICreateLotMaster.CreateLotMaster.OperationResule result = createLot.Create(item.WHCode, line.InvCode, line.BatchCode, OrgID, ref lotID, DateTime.Now, DisabledTime, LotLastTime); ;


                        if (result.IsSuccess)
                        {
                            LotMaster = long.Parse(lotID);
                        }
                        else
                        {
                            throw new Exception(result.Message);
                        }
                    }
                    #region 获取工单的业务类型
                    int bussinesstype = 0;
                    string mosql = @"select BusinessType from MO_MO 
                                     where DocNo='{0}' AND Org='{1}'";
                    mosql = string.Format(mosql, item.MOCode, OrgID);
                    DataTable modt = DBhlper.Query(mosql, Appconfig.GetU9ConnStr());
                    if (modt.Rows.Count != 0)
                    {
                        bussinesstype = Convert.ToInt32(modt.Rows[0]["BusinessType"].ToString());
                    }
                    #endregion 
                    data.m_org = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_org.m_iD = long.Parse(OrgID);
                    data.m_completeDocType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    if (bussinesstype == 48)
                    {
                        data.m_completeDocType.m_code = "5";
                    }
                    else
                    {
                        data.m_completeDocType.m_code = "1";
                    }
                    //data.m_completeDocType.m_iD = GetTypeID("1", OrgID);
                    data.m_mO = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_mO.m_code = item.MOCode;
                    data.m_handlePerson = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_handlePerson.m_code = item.User;
                    data.m_handleDept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_handleDept.m_code = item.DepCode;

                    data.m_rcvWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_rcvWh.m_iD = GetWHID(item.WHCode, OrgID);
                    data.m_completeDate = DateTime.Now;
                    data.m_actualRcvTime = DateTime.Now;
                    data.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                    data.m_descFlexField.m_privateDescSeg30 = line.LogIds;



                    UFIDAU9ISVMOCompRptRcvLineDTOData rcvLine = new UFIDAU9ISVMOCompRptRcvLineDTOData();
                    rcvLine.m_lineNum = Num;
                    if (LotMaster != 0)
                    {
                        rcvLine.m_rcvLotNo = line.BatchCode;
                        rcvLine.m_rcvLotMaster = long.Parse(LotMaster.ToString());
                    }
                    rcvLine.m_rcvQtyByCostUOM = line.Quantity;
                    rcvLine.m_rcvQtyByProductUOM = line.Quantity;
                    rcvLine.m_rcvQtyByWhUOM = line.Quantity;
                    rcvLine.m_storageType = 4;
                    rcvLine.m_grade = -1;
                    rcvLine.m_element = -1;
                    rcvLineList.Add(rcvLine);
                    Num += 10;
                }
                data.m_completeRptRcvLines = rcvLineList.ToArray();

                datas.Add(data);
            }

            return datas.ToArray();

        }

        private static UFIDAU9ISVMOCompRptDTOData[] GetDataForFCP(List<FCPRcvRptInfo> CompRptList, string OrgID)
        {
            List<UFIDAU9ISVMOCompRptDTOData> datas = new List<UFIDAU9ISVMOCompRptDTOData>();
            string LotValidTime = ConfigurationManager.AppSettings["LotValidTime"]?.ToString(); ;
            if (LotValidTime == null)
            {
                LotValidTime = "0";
            }
            foreach (FCPRcvRptInfo item in CompRptList)
            {
                int Num = 10;
                UFIDAU9ISVMOCompRptDTOData data = new UFIDAU9ISVMOCompRptDTOData();
                List<UFIDAU9ISVMOCompRptRcvLineDTOData> rcvLineList = new List<UFIDAU9ISVMOCompRptRcvLineDTOData>();
                foreach (FCPRcvRptLine line in item.details)
                {
                    if (line.Quantity != 0)
                    {
                        data.m_completeQty += line.Quantity;
                        data.m_completeQtyCoUOM += line.Quantity;
                        data.m_completeQtyWhUOM += line.Quantity;
                        data.m_eligibleQty += line.Quantity;
                        data.m_eligibleQtyCoUOM += line.Quantity;
                        data.m_reworkingQtyCoUOM += line.Quantity;
                    }
                    long LotMaster = 0;
                    DateTime DisabledTime = new DateTime();
                    int LotLastTime = 0;
                    string ItemID = "";
                    string orgsql = @"select LotValidDate,a.ID from CBO_ItemMaster a
                    LEFT JOIN CBO_InventoryInfo b on a.InventoryInfo=b.ID
                    where a.Code='{0}' and Org='{1}'";
                    orgsql = string.Format(orgsql, line.InvCode, OrgID);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        int date = Convert.ToInt32(orgdt.Rows[0]["LotValidDate"].ToString());
                        ItemID = orgdt.Rows[0]["ID"].ToString();
                        if (date > 0)
                        {
                            DisabledTime = DateTime.Now.AddDays(date);
                            LotLastTime = date;
                        }
                        else
                        {
                            LotLastTime = Convert.ToInt32(LotValidTime);
                            DisabledTime = DateTime.Now.AddDays(Convert.ToInt32(LotValidTime));
                        }
                    }
                    else
                    {
                        throw new Exception("传入的物料编码无法查询到对应数据!");
                    }
                    if (!string.IsNullOrWhiteSpace(line.BatchCode))
                    {
                        //创建批号
                        string lotID = "";
                        APICreateLotMaster.CreateLotMaster createLot = new APICreateLotMaster.CreateLotMaster();
                        APICreateLotMaster.CreateLotMaster.OperationResule result = createLot.Create(item.WHCode, line.InvCode, line.BatchCode, OrgID, ref lotID, DateTime.Now, DisabledTime, LotLastTime); ;


                        if (result.IsSuccess)
                        {
                            LotMaster = long.Parse(lotID);
                        }
                        else
                        {
                            throw new Exception("批号生成失败，完工报告生成失败！");
                        }
                    }
                    #region 获取工单的业务类型
                    int bussinesstype = 0;
                    long DocTypeID = 0;
                    string DocTypeCode = "";
                    string mosql = @"   select A.BusinessType,B.OutputType,C.Code,C.ID from MO_MO A
                                        LEFT JOIN MO_MOOutput B ON B.MO=A.ID
                                        LEFT JOIN MO_CompleteRptDocType C ON C.BusinessType=A.BusinessType 
                                        AND CASE WHEN C.CompleteRptType=1 THEN 2 WHEN C.CompleteRptType=2 THEN 1 ELSE 0 END=B.OutputType
                                        where A.DocNo='{0}' AND A.Org='{1}'
                                        AND B.Item='{2}'";
                    mosql = string.Format(mosql, item.MOCode, OrgID, ItemID);
                    DataTable modt = DBhlper.Query(mosql, Appconfig.GetU9ConnStr());
                    if (modt.Rows.Count != 0)
                    {
                        bussinesstype = Convert.ToInt32(modt.Rows[0]["BusinessType"].ToString());
                        DocTypeID = long.Parse(modt.Rows[0]["ID"].ToString());
                        DocTypeCode = modt.Rows[0]["Code"].ToString();
                    }
                    else
                    {
                        throw new Exception("U9未维护对应工单业务类型的单据类型，无法生成完工报告！");
                    }
                    #endregion 
                    data.m_org = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_org.m_iD = long.Parse(OrgID);
                    data.m_completeDocType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_completeDocType.m_iD = DocTypeID;
                    data.m_completeDocType.m_code = DocTypeCode;
                    //data.m_completeDocType.m_iD = GetTypeID("1", OrgID);
                    data.m_mO = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_mO.m_code = item.MOCode;
                    data.m_itemMaster = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_itemMaster.m_iD = long.Parse(ItemID);
                    data.m_itemMaster.m_code = line.InvCode;
                    data.m_handlePerson = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_handlePerson.m_code = item.User;
                    data.m_handleDept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_handleDept.m_code = item.DepCode;

                    data.m_rcvWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    data.m_rcvWh.m_iD = GetWHID(item.WHCode, OrgID);
                    data.m_completeDate = DateTime.Now;
                    data.m_actualRcvTime = DateTime.Now;



                    UFIDAU9ISVMOCompRptRcvLineDTOData rcvLine = new UFIDAU9ISVMOCompRptRcvLineDTOData();
                    rcvLine.m_lineNum = Num;
                    if (LotMaster != 0)
                    {
                        rcvLine.m_rcvLotNo = line.BatchCode;
                        rcvLine.m_rcvLotMaster = long.Parse(LotMaster.ToString());
                    }
                    rcvLine.m_rcvQtyByCostUOM = line.Quantity;
                    rcvLine.m_rcvQtyByProductUOM = line.Quantity;
                    rcvLine.m_rcvQtyByWhUOM = line.Quantity;
                    rcvLine.m_storageType = 4;
                    rcvLine.m_grade = -1;
                    rcvLine.m_element = -1;
                    rcvLineList.Add(rcvLine);
                    Num += 10;
                }
                data.m_completeRptRcvLines = rcvLineList.ToArray();

                datas.Add(data);
            }

            return datas.ToArray();

        }

        public static long GetWHID(string WHCode, string OrgID)
        {
            long WHID = 0;
            string sql = @" SELECT ID FROM CBO_Wh WHERE Code='" + WHCode + "' AND Org='" + OrgID + "' ";
            sql = string.Format(sql);
            DataTable _dtWH = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
            string _WHCode = string.Empty;

            if (_dtWH != null && _dtWH.Rows.Count > 0)
            {
                _WHCode = _dtWH.Rows[0][0].ToString();
                WHID = long.Parse(_WHCode);
            }

            return WHID;
        }
        #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
    }
}
