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

namespace ICS.CreateBFMiscRcv
{

    public class CustCreateBFMiscRcv
    {
        //public List<rtnRcvInfo> CreateBFMisRcv(List<rCVhead> rCVInfoList)
        public rtnRcvInfo CreateBFMisRcv(List<rCVhead> rCVInfoList)
        {
            #region 接口传入参数日志
            StringBuilder firststrlog = new StringBuilder();
            firststrlog.AppendLine("传入数据开始");
            firststrlog.AppendLine("*****************************************************");
            foreach (var item in rCVInfoList)
            {
                firststrlog.AppendLine("单据编号:" + item.DocNO);
                firststrlog.AppendLine("单据类型:" + item.DocType);
                firststrlog.AppendLine("组织编码:" + item.WorkPoint);
                firststrlog.AppendLine("客户编码:" + item.ClientCode);
                firststrlog.AppendLine("用户名:" + item.UserName);
                foreach (var line in item.details)
                {
                    firststrlog.AppendLine("料品编码:" + line.InvCode);
                    firststrlog.AppendLine("料品数量:" + line.Quantity);
                    firststrlog.AppendLine("批号:" + line.BatchCode);
                    firststrlog.AppendLine("仓库:" + line.WHCode);
                    firststrlog.AppendLine("部门编码:" + line.Dep);
                    firststrlog.AppendLine("受益项目:" + line.Project);
                    firststrlog.AppendLine("cFree1:" + line.cFree1);
                    firststrlog.AppendLine("cFree2:" + line.cFree2);
                    firststrlog.AppendLine("cFree3:" + line.cFree3);
                    firststrlog.AppendLine("cFree4:" + line.cFree4);
                    firststrlog.AppendLine("cFree5:" + line.cFree5);
                    firststrlog.AppendLine("cFree6:" + line.cFree6);
                    firststrlog.AppendLine("cFree7:" + line.cFree7);
                    firststrlog.AppendLine("cFree8:" + line.cFree8);
                    firststrlog.AppendLine("cFree9:" + line.cFree9);
                    firststrlog.AppendLine("cFree10:" + line.cFree10);
                    firststrlog.AppendLine("LogId:" + line.LogId);
                }
            }
            firststrlog.AppendLine("*****************************************************");
            firststrlog.AppendLine("传入数据结束");
            Appconfig.WriteLogFile(firststrlog.ToString(), "创建杂收单");
            #endregion
            #region 服务调用框架结构
            UFIDAU9ISVMiscRcvISVICommonCreateMiscRcvClient client = new UFIDAU9ISVMiscRcvISVICommonCreateMiscRcvClient();
            //服务返回结果
            UFIDAU9CBOPubControllerCommonArchiveDataDTOData[] returnItems;
            //返回异常信息，目前还没有使用此属性
            UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数
            UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData[] pOList;
            //空
            string[] splitBy = new string[] { };

            try
            {
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                long PickID = 0;
                long ItemID = 0;
                if (rCVInfoList == null || rCVInfoList.Count == 0)
                {
                    rtnpo.Success = false;
                    rtnpo.Message = "传入参数不能为空";
                    //rtnpos.Add(rtnpo);
                    return rtnpo;
                }
                string OrgID = "";
                foreach (var item in rCVInfoList)
                {
                    if (item.DocType == null || item.DocType == "")
                    {
                        rtnpo.Success = false;
                        rtnpo.Message = "传入单据类型不能为空";
                        //rtnpos.Add(rtnpo);
                        return rtnpo;
                    }
                    //if (item.ClientCode == null || item.ClientCode == "")
                    //{
                    //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                    //    rtnpo.IsSuccess = false;
                    //    rtnpo.Message = "传入客户信息不能为空";
                    //    rtnpos.Add(rtnpo);
                    //    return rtnpos;
                    //}
                    if (item.details == null || item.details.Count() == 0)
                    {
                        rtnpo.Success = false;
                        rtnpo.Message = "传入行信息不能为空";
                        //rtnpos.Add(rtnpo);
                        return rtnpo;
                    }
                    foreach (var _item in item.details)
                    {
                        if (_item.InvCode == null || _item.InvCode == "")
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中料号不能为空!";
                            //rtnpos.Add(rtnpo);
                            return rtnpo;
                        }
                        if (_item.Quantity == 0)
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中数量不能为空";
                            //rtnpos.Add(rtnpo);
                            return rtnpo;
                        }
                        if (_item.WHCode == null || _item.WHCode == "")
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "传入行信息中仓库不能为空";
                            //rtnpos.Add(rtnpo);
                            return rtnpo;
                        }
                        //if (string.IsNullOrEmpty(_item.Dep))
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.Success = false;
                        //    rtnpo.Message = "传入行信息中部门不能为空";
                        //    //rtnpos.Add(rtnpo);
                        //    return rtnpo;
                        //}
                        //if (string.IsNullOrEmpty(_item.Project))
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.Success = false;
                        //    rtnpo.Message = "传入行信息中项目不能为空";
                        //    rtnpos.Add(rtnpo);
                        //    return rtnpos;
                        //}



                    }
                }


                //给传入参数赋值

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                string orgID = "";
                strlog.AppendLine("创建杂收单");
                strlog.AppendLine("*****************************************************");
                List<UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData> rcvList = new List<UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData>();
                foreach (var rCVhead in rCVInfoList)
                {
                    strlog.AppendLine("组织编码:" + rCVhead.WorkPoint);
                    //获取组织ID
                    string orgsql = @"select ID from Base_Organization
                                      where Code='{0}' ";
                    orgsql = string.Format(orgsql, rCVhead.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count == 0)
                    {
                        rtnpo.Success = false;
                        rtnpo.Message = "组织编码不存在";
                        //rtnpos.Add(rtnpo);
                        return rtnpo;
                    }
                    else
                    {
                        orgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    //获取单据类型ID
                    string docsql = @"select ID from InvDoc_MiscRcvDocType
                                          where Code='{0}' AND Org='{1}'";
                    docsql = string.Format(docsql, rCVhead.DocType, orgID);
                    DataTable docdt = DBhlper.Query(docsql, Appconfig.GetU9ConnStr());
                    long docTypeID = 0;
                    if (docdt != null && docdt.Rows.Count > 0)
                    {
                        docTypeID = long.Parse(docdt.Rows[0]["ID"].ToString());
                    }
                    if (docTypeID == 0)
                    {
                        rtnpo.Success = false;
                        rtnpo.Message = "未获取到单据类型ID";
                        //rtnpos.Add(rtnpo);
                        return rtnpo;
                    }
                    UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData rcv = new UFIDAU9ISVMiscRcvISVIC_MiscRcvDTOData();
                    rcv.m_docNo = rCVhead.DocNO;
                    rcv.m_miscRcvDocType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    rcv.m_miscRcvDocType.m_code = rCVhead.DocType;
                    rcv.m_miscRcvDocType.m_iD = docTypeID;

                    rcv.m_businessDate = Convert.ToDateTime(rCVhead.DocDate);

                    rcv.m_benefitOrg = long.Parse(orgID);
                    List<UFIDAU9ISVMiscRcvISVIC_MiscRcvTransLsDTOData> rcvLineList = new List<UFIDAU9ISVMiscRcvISVIC_MiscRcvTransLsDTOData>();
                    foreach (rCVLine line in rCVhead.details)
                    {
                        #region 获取料品ID
                        string sqlitem = @"select ID from CBO_ItemMaster 
                                           where Code='" + line.InvCode + "' AND Org='" + orgID + "'";
                        sqlitem = string.Format(sqlitem);
                        DataTable dtitem = DBhlper.Query(sqlitem, Appconfig.GetU9ConnStr());
                        if (dtitem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(dtitem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "料品不存在!";
                            //rtnpos.Add(rtnpo);
                            return rtnpo;
                        }
                        #endregion
                        #region 获取仓库ID
                        string sqlWH = @"select ID,Code from CBO_Wh
                                         WHERE Code='" + line.WHCode + "' AND Org='" + orgID + "' ";
                        sqlWH = string.Format(sqlWH);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        long WHID = 0;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHCode = _dtWH.Rows[0]["Code"].ToString();
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                        }
                        if (string.IsNullOrWhiteSpace(WHCode))
                        {
                            rtnpo.Success = false;
                            rtnpo.Message = "未获取到仓库";
                            //rtnpos.Add(rtnpo);
                            return rtnpo;
                        }
                        #endregion
                        #region 获取部门ID
                        long DeptID = 0;
                        string IsMFG = "";
                        if (!string.IsNullOrEmpty(line.Dep))
                        {
                            string deptsql = @"select ID,Case When IsMFG=1 then 'True' Else 'False' End AS IsMFG from CBO_Department
                                           where Code='{0}' AND Org='{1}'";

                            deptsql = string.Format(deptsql, line.Dep, orgID);
                            DataTable deptdt = DBhlper.Query(deptsql, Appconfig.GetU9ConnStr());
                            if (deptdt != null && deptdt.Rows.Count > 0)
                            {
                                DeptID = long.Parse(deptdt.Rows[0]["ID"].ToString());
                                IsMFG = deptdt.Rows[0]["IsMFG"].ToString();
                            }
                            if (DeptID == 0)
                            {
                                rtnpo.Success = false;
                                rtnpo.Message = "未获取到部门";
                                return rtnpo;
                            }
                        }
                        #endregion
                        UFIDAU9ISVMiscRcvISVIC_MiscRcvTransLsDTOData rcvLine = new UFIDAU9ISVMiscRcvISVIC_MiscRcvTransLsDTOData();
                        if (!string.IsNullOrEmpty(line.Dep))
                        {
                            rcvLine.m_benefitDept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            rcvLine.m_benefitDept.m_code = line.Dep;
                            //rcvLine.m_benefitDept.m_iD = DeptID;
                        }
                        rcvLine.m_benefitOrg = long.Parse(orgID);
                        rcvLine.m_itemInfo = new UFIDAU9CBOSCMItemItemInfoData();
                        rcvLine.m_itemInfo.m_itemCode = line.InvCode;
                        rcvLine.m_itemInfo.ItemID = ItemID;
                        rcvLine.m_itemInfo.ItemID_SKey = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                        rcvLine.m_itemInfo.ItemID_SKey.ID = ItemID;
                        rcvLine.m_storeType = 4;
                        rcvLine.m_costUOMQty = line.Quantity;
                        rcvLine.m_wh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        rcvLine.m_wh.m_code = WHCode;
                        rcvLine.m_iD = WHID;
                        rcvLine.m_customerInfo = new UFIDAU9CBOSCMCustomerCustomerMISCInfoData();
                        rcvLine.m_customerInfo.m_code = rCVhead.ClientCode;
                        rcvLine.m_memo = line.Memo;
                        if (IsMFG == "True")
                        {
                            rcvLine.m_isMFG = true;
                        }
                        else
                        {
                            rcvLine.m_isMFG = false;
                        }
                        //string selSql = @"
                        //                    select * from
                        //                (
                        //                    SELECT  A.[ID] as [ID], A.[SysVersion] as [SysVersion], A.[ID] as [MainID], A2.[Name] as [CostField_Name], A5.[Name] as 
                        //                    [CostType_Name], A7.[Name] as [SOB_Name], A8.[DisplayName] as [SOBPeriod_DisplayName],
                        //                    A.[ItemInfo_ItemName] as [ItemInfo_ItemName], A.[ItemInfo_ItemCode] as [ItemInfo_ItemCode],

                        //                    A.[ElementTypeCost_MaterialCurrentCost]+A.[ElementTypeCost_MaterialPriorCost]+A.[ElementTypeCost_LaborCurrentCost] + A.[ElementTypeCost_LaborPriorCost] + A.[ElementTypeCost_OverheadCurrentCost] + A.[ElementTypeCost_OverheadPriorCost]+ A.[ElementTypeCost_SubcontractCurrentCost]+
                        //                    A.[ElementTypeCost_SubcontractPriorCost]+A.[ElementTypeCost_MachineCurrentCost]+ A.[ElementTypeCost_MachinePriorCost] Cost,
                        //                    row_number()over(partition by A9.Code,A.[ItemInfo_ItemCode] order by A8.[DisplayName] desc) as RowNo
                        //                    FROM  IC_ItemInvCost as A  
                        //                    left join [CBO_CostField] as A1 on (A.[CostField] = A1.[ID]) 
                        //                    left join Base_Language as A3 on (A3.Code = 'zh-CN') and (A3.Effective_IsEffective = 1)  
                        //                    left join [CBO_CostField_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A2.SysMlFlag = A3.Code) and (A1.[ID] = A2.[ID])  
                        //                    left join [CBO_CostType] as A4 on (A.[CostType] = A4.[ID]) 
                        //                    left join [CBO_CostType_Trl] as A5 on (A5.SysMlFlag = 'zh-CN') and (A5.SysMlFlag = A3.Code) and (A4.[ID] = A5.[ID]) 
                        //                    left join [Base_SetofBooks] as A6 on (A.[SOB] = A6.[ID])
                        //                    left join [Base_SetofBooks_Trl] as A7 on (A7.SysMlFlag = 'zh-CN') and (A7.SysMlFlag = A3.Code) and (A6.[ID] = A7.[ID])  
                        //                    left join [Base_SOBAccountingPeriod] as A8 on (A.[SOBPeriod] = A8.[ID]) 
                        //                    left join [CBO_ItemMaster] as A9 on (A.[ItemInfo_ItemID] = A9.[ID])
                        //                    WHERE   A.[Org] =" + orgID + "   )  as a   where RowNo=1 and A.[ItemInfo_ItemCode] = N'" + line.InvCode + "' ";
                        //DataTable Seldt = DBhlper.Query(selSql, Appconfig.GetU9ConnStr());
                        //Decimal cost = 0;
                        //if (Seldt != null && Seldt.Rows.Count > 0)
                        //{
                        //    if (!string.IsNullOrEmpty(Seldt.Rows[0]["Cost"].ToString()))
                        //    {
                        //        rcvLine.m_costPrice = Decimal.Parse(Seldt.Rows[0]["Cost"].ToString()); ;
                        //    }
                        //    else
                        //    {
                        //        rcvLine.m_costPrice = 0;
                        //    }
                        //}
                        //else
                        //{
                        //    rcvLine.m_costPrice = 0;
                        //}

                        if (!string.IsNullOrEmpty(line.Project))
                        {
                            string projectsql = @"select ID from CBO_Project
                                           where Code='{0}' AND Org='{1}'";
                            projectsql = string.Format(projectsql, line.Project, orgID);
                            DataTable projectdt = DBhlper.Query(projectsql, Appconfig.GetU9ConnStr());
                            long projectID = 0;
                            if (projectdt != null && projectdt.Rows.Count > 0)
                            {
                                projectID = long.Parse(projectdt.Rows[0]["ID"].ToString());
                                //rcvLine.m_project = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                //rcvLine.m_project.m_code = line.Project;
                                //rcvLine.m_project.m_iD = projectID;

                                rcvLine.m_benefitProject = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                rcvLine.m_benefitProject.m_code = line.Project;
                                rcvLine.m_benefitProject.m_iD = projectID;
                            }
                            if (projectID == 0)
                            {
                                rtnpo.Success = false;
                                rtnpo.Message = "项目有误，请核对！";
                                //rtnpos.Add(rtnpo);
                                return rtnpo;
                            }
                        }
                        //else
                        //{
                        //    rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //    rtnpo.Success = false;
                        //    rtnpo.Message = "受益项目为空，请核对！";
                        //    rtnpos.Add(rtnpo);
                        //    return rtnpos;
                        //}

                        rcvLine.m_descFlexSegments = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData();
                        rcvLine.m_descFlexSegments.m_privateDescSeg1 = line.cFree1;
                        rcvLine.m_descFlexSegments.m_privateDescSeg2 = line.cFree2;
                        rcvLine.m_descFlexSegments.m_privateDescSeg3 = line.cFree3;
                        rcvLine.m_descFlexSegments.m_privateDescSeg4 = line.cFree4;
                        rcvLine.m_descFlexSegments.m_privateDescSeg5 = line.cFree5;
                        rcvLine.m_descFlexSegments.m_privateDescSeg6 = line.cFree6;
                        rcvLine.m_descFlexSegments.m_privateDescSeg7 = line.cFree7;
                        rcvLine.m_descFlexSegments.m_privateDescSeg8 = line.cFree8;
                        rcvLine.m_descFlexSegments.m_privateDescSeg9 = line.cFree9;
                        rcvLine.m_descFlexSegments.m_privateDescSeg10 = line.cFree10;

                        #region 创建批号接口调用
                        string LotID = "";
                        if (line.BatchCode != "")
                        {
                            CustCreateLotMaster LotMasterCreate = new CustCreateLotMaster();
                            string lotWHCode = line.WHCode;
                            string lotItemCode = line.InvCode;
                            string LotCode = line.BatchCode;
                            LotMasterCreate.CustCreateRCVLotMaster(lotWHCode, lotItemCode, LotCode, orgID, ref LotID);
                            if (LotID != "")
                            {
                                rcvLine.m_lotInfo = new UFIDAU9CBOSCMPropertyTypesLotInfoData();
                                rcvLine.m_lotInfo.m_lotCode = line.BatchCode;
                                rcvLine.m_lotInfo.m_lotMaster = new UFIDAU9BasePropertyTypesBizEntityKeyData();
                                rcvLine.m_lotInfo.m_lotMaster.m_entityID = long.Parse(LotID);
                            }
                        }
                        #endregion

                        rcvLineList.Add(rcvLine);
                        strlog.AppendLine("料品编码:" + line.InvCode);
                        strlog.AppendLine("料品数量:" + line.Quantity);
                        strlog.AppendLine("仓库:" + WHCode);
                        strlog.AppendLine("批号ID:" + LotID);

                    }
                    rcv.m_miscRcvTransLs = rcvLineList.ToArray();
                    rcvList.Add(rcv);
                }
                pOList = rcvList.ToArray();

                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                List<string> shDocList = new List<string>();

                //给上下文信息赋值
                context = CreateContextObj(rCVInfoList, long.Parse(orgID));
                returnItems = client.Do(out returnMsg, context, pOList);
                strlog.AppendLine("返回数据:");
                bool isDel = false;
                rtnRcvInfo rtnpo_ = new rtnRcvInfo();
                List<string> StrList = new List<string>();
                List<Data> _datalist = new List<Data>();
                foreach (var info in returnItems)
                {
                    strlog.AppendLine("单号:" + info.m_code);
                    strlog.AppendLine("*****************************************************");
                    string DocTypeName = string.Empty;
                    Data _data = new Data();
                    if (returnItems != null)
                    {
                        //rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //rtnpo.Success = true;
                        //rtnpo.DocNo = info.m_code;
                        //rtnpo.Message = "杂收单创建成功";

                        List<DataLine> list = new List<DataLine>();
                        string Selsql = @"SELECT bbb.Name DocTypeName,a.ID,b.BenefitDept,a.DocNo SourceCode,c.Code cWHCode,cc.Name cWHName,b.id DetailID,b.DocLineNo Sequence,b.ItemInfo_ItemCode InvCode,b.StoreUOMQty Quantity,b.LotInfo_LotCode cBatch,
                        '' cFree1,'' cFree2,'' cFree3,
                        '' cFree4,'' cFree5,'' cFree6,
                        '' cFree7,'' cFree8,'' cFree9,
                        '' cFree10,'' LogId
                          FROM InvDoc_MiscRcvTrans a
                        LEFT JOIN InvDoc_MiscRcvTransL b ON b.MiscRcvTrans=a.ID
                        LEFT JOIN CBO_Wh c ON b.Wh=c.ID
                        LEFT JOIN CBO_Wh_Trl cc ON c.ID=cc.ID
LEFT JOIN InvDoc_MiscRcvDocType bb on a.MiscRcvDocType=bb.ID
LEFT JOIN InvDoc_MiscRcvDocType_Trl bbb ON bb.ID=bbb.ID  AND bbb.SysMLFlag='zh-CN'
                        WHERE a.DocNo='" + info.m_code + "'";
                        DataTable Seldt = DBhlper.Query(Selsql, Appconfig.GetU9ConnStr());
                       
                        if (Seldt != null && Seldt.Rows.Count > 0)
                        {
                            foreach (DataRow item in Seldt.Rows)
                            {
                                DocTypeName= item["DocTypeName"].ToString();
                                DataLine _DataLine = new DataLine();
                                _data.ID = item["ID"].ToString();
                                _data.SourceCode = info.m_code;
                                _data.cDepCode = item["BenefitDept"].ToString();
                                _data.cWHCode = item["cWHCode"].ToString();
                                _data.cWHName = item["cWHName"].ToString();
                                _DataLine.DetailID = item["DetailID"].ToString();
                                _DataLine.Sequence = Int32.Parse(item["Sequence"].ToString());
                                _DataLine.Quantity = Decimal.Parse(item["Quantity"].ToString());
                                _DataLine.InvCode = item["InvCode"].ToString();
                                _DataLine.cBatch = item["cBatch"].ToString();
                                _DataLine.cFree1 = item["cFree1"].ToString();
                                _DataLine.cFree2 = item["cFree2"].ToString();
                                _DataLine.cFree3 = item["cFree3"].ToString();
                                _DataLine.cFree4 = item["cFree4"].ToString();
                                _DataLine.cFree5 = item["cFree5"].ToString();
                                _DataLine.cFree6 = item["cFree6"].ToString();
                                _DataLine.cFree7 = item["cFree7"].ToString();
                                _DataLine.cFree8 = item["cFree8"].ToString();
                                _DataLine.cFree9 = item["cFree9"].ToString();
                                _DataLine.cFree10 = item["cFree10"].ToString();
                                _DataLine.LogId = item["LogId"].ToString();

                                list.Add(_DataLine);
                            }
                            _data.details = list;
                            _datalist.Add(_data);
                            //rtnpo.Data = _data;
                            //rtnpos.Add(rtnpo);
                        }
                        //rtnpos.Add(rtnpo);
                    }
                    if (!DocTypeName.Contains("期初生产退料"))
                    {
                        StrList.Add(info.m_code);
                    }
                }
                rtnpo.Success = true;
                rtnpo.DocNo = "";
                rtnpo.Message = "杂收单创建成功!";
                rtnpo.Data = _datalist;
                //List<Data> _datalist = new List<Data>();
                //rtnpo.Data = _datalist;
                if (StrList!=null&& StrList.Count>0)
                {
                    #region 提交杂收单
                    StringBuilder submitlog = new StringBuilder();
                    submitlog.AppendLine("---------------------提交杂收单----------------------------");
                    submitlog.AppendLine("杂收单号:" + StrList);
                    OperationResult result = new OperationResult();
                    result = CustCallSubmitMisRcv.CustSubmitMisRcv(StrList, orgID);
                    List<string> listt = new List<string>();
                    if (result.IsSuccess == true)
                    {
                        submitlog.AppendLine("杂收单提交成功!");
                        #region 审核杂收单
                        CustApproveMiscRcv.OperationResult_ApproveMiscRcv approveresult = new CustApproveMiscRcv.OperationResult_ApproveMiscRcv();
                        CustApproveMiscRcv approveclient = new CustApproveMiscRcv();
                        //approveresult = approveclient.CustApproveMis(info.m_code, rCVInfoList[0].WorkPoint);
                        approveresult = approveclient.CustApproveMis(StrList, rCVInfoList[0].WorkPoint);


                        if (approveresult.IsSuccess == true)
                        {
                            //StrList.Add(info.m_code);
                            submitlog.AppendLine("杂收单审核成功!");
                            //rtnRcvInfo rtnpo = new rtnRcvInfo();
                            //rtnpo.Success = true;
                            //rtnpo.DocNo = info.m_code;
                            //rtnpo.Message = "杂收单审核成功!";
                            //rtnpo.Data = _data;
                            //rtnpos.Add(rtnpo);

                            rtnpo.Success = true;
                            rtnpo.DocNo = "";
                            rtnpo.Message = "杂收单审核成功!";
                            rtnpo.Data = _datalist;
                        }
                        else
                        {
                            isDel = true;

                            submitlog.AppendLine("杂收单审核失败!");
                            submitlog.AppendLine("失败原因:" + approveresult.Message);

                            rtnpo.Success = false;
                            rtnpo.DocNo = "";
                            rtnpo.Message = "杂收单审核失败";
                            rtnpo.Data = _datalist;
                            //rtnpos.Add(rtnpo);
                            //listt.Add(info.m_code);
                            ICS.DeleteMiscRcv.CustDeleteMiscRcv custtt = new DeleteMiscRcv.CustDeleteMiscRcv();
                            custtt.CustDeleteMiscShip(StrList, orgID);

                        }
                        #endregion
                    }
                    else
                    {
                        submitlog.AppendLine("杂收单提交失败!");
                        submitlog.AppendLine("失败原因:" + result.Message);
                        //rtnRcvInfo rtnpo = new rtnRcvInfo();
                        //rtnpo.Success = false;
                        //rtnpo.DocNo = info.m_code;
                        //rtnpo.Message = result.Message;// "杂收单提交失败";
                        //rtnpos.Add(rtnpo);
                        //listt.Add(info.m_code);

                        rtnpo.Success = false;
                        rtnpo.DocNo = "";
                        rtnpo.Data = _datalist;
                        rtnpo.Message = result.Message;

                        ICS.DeleteMiscRcv.CustDeleteMiscRcv custtt = new DeleteMiscRcv.CustDeleteMiscRcv();
                        custtt.CustDeleteMiscShip(StrList, orgID);
                    }
                    Appconfig.WriteLogFile(submitlog.ToString(), "创建杂收单");
                    #endregion
                }


                Appconfig.WriteLogFile(strlog.ToString(), "创建杂收单");
                return rtnpo;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                //List<rtnRcvInfo> rtnpos = new List<rtnRcvInfo>();
                rtnRcvInfo rtnpo = new rtnRcvInfo();
                rtnpo.Success = false;
                rtnpo.Message = GetExceptionMessage(ex);
                //rtnpos.Add(rtnpo);

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建杂发单");
                strlog.AppendLine("*****************************************************");
                foreach (var item in rCVInfoList)
                {
                    strlog.AppendLine("组织编码:" + item.WorkPoint);
                    foreach (var line in item.details)
                    {
                        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 rtnpo;
            }
            #endregion
        }

        #region 表头类
       
        public class rCVhead
        {
            private rCVLine[] _lines;
            private string _DocType;
            private string _OrgCode;
            private string _ClientCode;
            private string _UserName;
            private string _ServiceMoCode;
            private string _DocNo;
            public string DocDate { get; set; }
            //private string _DocType;


            public rCVLine[] details
            {
                get { return _lines; }
                set { _lines = value; }
            }

            public string DocNO
            {
                get { return _DocNo; }
                set { _DocNo = value; }
            }

            /// <summary>
            /// 单据类型
            /// </summary>
            public string DocType
            {
                get { return _DocType; }
                set { _DocType = value; }
            }
            /// <summary>
            /// 组织编号
            /// </summary>
            public string WorkPoint
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }
            /// <summary>
            /// 客户
            /// </summary>
            public string ClientCode
            {
                get { return _ClientCode; }
                set { _ClientCode = value; }
            }
            public string UserName
            {
                get { return _UserName; }
                set { _UserName = 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 InvCode { get; set; }
            /// <summary>
            /// 受益部门
            /// </summary>
            //public string DepCode { get; set; }
            //public string ProjectCode { get; set; }

            public string Dep { get; set; }
            public string Project { get; set; }



            /// <summary>
            /// 库存批号
            /// </summary>
            public string BatchCode { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string Memo { 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(List<rCVhead> rcvInfoList, long 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 时间戳方法
        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 Success { get; set; }
        public string Message { get; set; }
        //public rtnRcvLine[] rtnLines { get; set; }
        //public rtnRcvLine[] rtnLines { get; set; }
        //public Data Data { get; set; }
        public List<Data> Data { get; set; }
    }

    public class Data
    {
        public string ID { get; set; }
        public string SourceCode { get; set; }
        public string OtherInCode { get; set; }
        public string cDepCode { get; set; }
        public string proCode { get; set; }
        public string cDepName { get; set; }
        public string cWHCode { get; set; }
        public string cWHName { get; set; }
        public string SourceType { get; set; }
        public string CreateUser { get; set; }
        public DateTime CreateDateTime { get; set; }
        public string Checker { get; set; }
        public DateTime CheckDateTime { get; set; }
        public List<DataLine> details { get; set; }
    }

    public class DataLine
    {
        public string DetailID { get; set; }
        public int Sequence { get; set; }
        public string InvCode { get; set; }
        public Decimal Quantity { get; set; }
        public string SourceDetailID { get; set; }
        public string ProjectCode { 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; }
    }

    public class rtnRcvLine
    {
        public int LineNo { 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 srcDocPONo { 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


}
