using ICS.WCF.Base;
using ICSSoft.APIApproveIssue;
using ICSSoft.DataProject;
using ICSSoft.Entity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using UFSoft.UBF.Exceptions1;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
using ICSSoft.Common;

namespace ICSSoft.APIModifyIssue
{
    public class ModifyIssue
    {
        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"];
        private static string LogName = "创建材料出库单";
        /// <summary>
        /// 生产领料单（修改并审核生产领料单/根据领料申请单创建材料出库单）
        /// </summary>
        /// <returns></returns>
        /// 
        public bool ActionModifyIssue(List<ICSRdrecord11> infos)
        {
            ThreadContext context;
            try
            {


                string _MOCode = string.Empty;
                UFIDAU9ISVMOIModifyIssue4ExternalClient client = new UFIDAU9ISVMOIModifyIssue4ExternalClient();
                MessageBase[] message = null;
                List<UFIDAU9ISVMOIssueModifyDTOData> LLlist = new List<UFIDAU9ISVMOIssueModifyDTOData>();
                UFIDAU9ISVMOIssueModifyDTOData LL = new UFIDAU9ISVMOIssueModifyDTOData();
                List<UFIDAU9ISVMOIssueModifyDTOData> RollBackLLlist = new List<UFIDAU9ISVMOIssueModifyDTOData>();
                UFIDAU9ISVMOIssueModifyDTOData RollBackLL = new UFIDAU9ISVMOIssueModifyDTOData();
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                foreach (var Info in infos)
                {
                    string headsql = @"select A.ID,ISNULL(A.BusinessCreatedOn,'') AS BusinessCreatedOn,ISNULL(A.BusinessDate,'') AS BusinessDate
                                            ,ISNULL(A.HandleDept,'') AS HandleDept,A.DocNo,A.IssueDocType
                                            ,A.IsSpecialIssue,A.SourceDoc_MOSrcDocType,A.SourceDoc_SrcDocID
                                            ,A.SourceDoc_SrcDocLineID,A.SourceDoc_SrcDocLineNo,A.SourceDoc_SrcDocNo
                                            ,A.SourceDoc_SrcDocSublineNo,A.SourceDoc_SrcDocType,A.SourceDoc_SrcDocVer
                                            ,A.SourceDoc_SrcDocOrg,B.BusinessType,A.IssueType from MO_IssueDoc A
											LEFT JOIN MO_IssueDocType B ON B.ID=A.IssueDocType
                                            where A.DocNo='{0}' AND A.Org='{1}'";
                    headsql = string.Format(headsql, Info.SourceCode, OrgID);
                    DataTable headdt = DBhlper.Query(headsql, connString);
                    if (headdt.Rows.Count == 0)
                    {
                        throw new Exception("领料单号:'" + Info.SourceCode + "'不存在!");
                    }
                    else
                    {
                        LL = new UFIDAU9ISVMOIssueModifyDTOData();
                        RollBackLL = new UFIDAU9ISVMOIssueModifyDTOData();
                        LL.m_issueDTO = new UFIDAU9ISVMOIssueDTOData();
                        RollBackLL.m_issueDTO = new UFIDAU9ISVMOIssueDTOData();
                        //if (headdt.Rows[0]["BusinessCreatedOn"].ToString() != "")
                        //{
                        //    LL.m_issueDTO.m_businessCreatedOn = Convert.ToDateTime(headdt.Rows[0]["BusinessCreatedOn"].ToString());
                        //    RollBackLL.m_issueDTO.m_businessCreatedOn = Convert.ToDateTime(headdt.Rows[0]["BusinessCreatedOn"].ToString());
                        //}
                        if (headdt.Rows[0]["BusinessDate"].ToString() != "")
                        {
                            LL.m_issueDTO.m_businessDate = Convert.ToDateTime(headdt.Rows[0]["BusinessDate"].ToString());
                            RollBackLL.m_issueDTO.m_businessDate = Convert.ToDateTime(headdt.Rows[0]["BusinessDate"].ToString());
                        }
                        LL.m_issueDTO.m_businessType = int.Parse(headdt.Rows[0]["BusinessType"].ToString());
                        RollBackLL.m_issueDTO.m_businessType = int.Parse(headdt.Rows[0]["BusinessType"].ToString());
                        if (headdt.Rows[0]["HandleDept"].ToString() != "")
                        {
                            LL.m_issueDTO.m_dept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            LL.m_issueDTO.m_dept.m_iD = long.Parse(headdt.Rows[0]["HandleDept"].ToString());
                            RollBackLL.m_issueDTO.m_dept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            RollBackLL.m_issueDTO.m_dept.m_iD = long.Parse(headdt.Rows[0]["HandleDept"].ToString());
                        }
                        LL.m_issueDTO.m_docNo = headdt.Rows[0]["DocNo"].ToString();
                        LL.m_issueDTO.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        LL.m_issueDTO.m_docType.m_iD = long.Parse(headdt.Rows[0]["IssueDocType"].ToString());
                        LL.m_issueDTO.m_isSpecialIssue = Convert.ToBoolean(headdt.Rows[0]["IsSpecialIssue"]);
                        LL.m_issueDTO.m_issueOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        LL.m_issueDTO.m_issueOrg.m_iD = long.Parse(OrgID);
                        LL.m_issueDTO.m_issueType = Convert.ToInt32(headdt.Rows[0]["IssueType"].ToString());
                        LL.m_issueKeyDTO = new UFIDAU9ISVMOIssueKeyDTOData();
                        LL.m_issueKeyDTO.m_docNo = headdt.Rows[0]["DocNo"].ToString();
                        LL.m_issueKeyDTO.m_iD = long.Parse(headdt.Rows[0]["ID"].ToString());
                        RollBackLL.m_issueDTO.m_docNo = headdt.Rows[0]["DocNo"].ToString();
                        RollBackLL.m_issueDTO.m_docType = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        RollBackLL.m_issueDTO.m_docType.m_iD = long.Parse(headdt.Rows[0]["IssueDocType"].ToString());
                        RollBackLL.m_issueDTO.m_isSpecialIssue = Convert.ToBoolean(headdt.Rows[0]["IsSpecialIssue"]);
                        RollBackLL.m_issueDTO.m_issueOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                        RollBackLL.m_issueDTO.m_issueOrg.m_iD = long.Parse(OrgID);
                        RollBackLL.m_issueDTO.m_issueType = 0;
                        RollBackLL.m_issueKeyDTO = new UFIDAU9ISVMOIssueKeyDTOData();
                        RollBackLL.m_issueKeyDTO.m_docNo = headdt.Rows[0]["DocNo"].ToString();
                        RollBackLL.m_issueKeyDTO.m_iD = long.Parse(headdt.Rows[0]["ID"].ToString());
                        if (headdt.Rows[0]["SourceDoc_SrcDocID"].ToString() != "-1")
                        {
                            LL.m_issueDTO.m_srcDoc = new UFIDAU9MOPropertyTypesMOSourceDocData();
                            LL.m_issueDTO.m_srcDoc.m_mOSrcDocType = int.Parse(headdt.Rows[0]["SourceDoc_MOSrcDocType"].ToString());
                            LL.m_issueDTO.m_srcDoc.m_srcDocID = long.Parse(headdt.Rows[0]["SourceDoc_SrcDocID"].ToString());
                            LL.m_issueDTO.m_srcDoc.m_srcDocLineID = long.Parse(headdt.Rows[0]["SourceDoc_SrcDocLineID"].ToString());
                            LL.m_issueDTO.m_srcDoc.m_srcDocLineNo = headdt.Rows[0]["SourceDoc_SrcDocLineNo"].ToString();
                            LL.m_issueDTO.m_srcDoc.m_srcDocNo = headdt.Rows[0]["SourceDoc_SrcDocNo"].ToString();
                            LL.m_issueDTO.m_srcDoc.m_srcDocSublineNo = headdt.Rows[0]["SourceDoc_SrcDocSublineNo"].ToString();
                            LL.m_issueDTO.m_srcDoc.m_srcDocType = headdt.Rows[0]["SourceDoc_SrcDocType"].ToString();
                            LL.m_issueDTO.m_srcDoc.m_srcDocVer = headdt.Rows[0]["SourceDoc_SrcDocVer"].ToString();
                            LL.m_issueDTO.m_srcDoc.SrcDocOrg = long.Parse(headdt.Rows[0]["SourceDoc_SrcDocOrg"].ToString());

                            RollBackLL.m_issueDTO.m_srcDoc = new UFIDAU9MOPropertyTypesMOSourceDocData();
                            RollBackLL.m_issueDTO.m_srcDoc.m_mOSrcDocType = int.Parse(headdt.Rows[0]["SourceDoc_MOSrcDocType"].ToString());
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocID = long.Parse(headdt.Rows[0]["SourceDoc_SrcDocID"].ToString());
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocLineID = long.Parse(headdt.Rows[0]["SourceDoc_SrcDocLineID"].ToString());
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocLineNo = headdt.Rows[0]["SourceDoc_SrcDocLineNo"].ToString();
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocNo = headdt.Rows[0]["SourceDoc_SrcDocNo"].ToString();
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocSublineNo = headdt.Rows[0]["SourceDoc_SrcDocSublineNo"].ToString();
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocType = headdt.Rows[0]["SourceDoc_SrcDocType"].ToString();
                            RollBackLL.m_issueDTO.m_srcDoc.m_srcDocVer = headdt.Rows[0]["SourceDoc_SrcDocVer"].ToString();
                            RollBackLL.m_issueDTO.m_srcDoc.SrcDocOrg = long.Parse(headdt.Rows[0]["SourceDoc_SrcDocOrg"].ToString());
                        }
                        List<UFIDAU9ISVMOPickListDTOData> PickList = new List<UFIDAU9ISVMOPickListDTOData>();
                        List<UFIDAU9ISVMOPickListDTOData> RollBackPickList = new List<UFIDAU9ISVMOPickListDTOData>();
                        foreach (var LLLineInfo in Info.details)
                        {
                            string linesql = @" select ISNULL(B.BenifitMO,'') AS BenifitMO,ISNULL(B.CostField,'') AS CostField,ISNULL(B.CostBaseUOM,'') AS CostBaseUOM
                                                    ,B.Element,B.Grade,B.IsNoPickLine,ISNULL(B.IssueDept,'') AS IssueDept,ISNULL(B.ID,'') AS ID,ISNULL(B.IssueUOM,'') AS IssueUOM
                                                    ,ISNULL(B.Wh,'') AS Wh,ISNULL(B.Item,'') AS Item,ISNULL(B.ItemVersion,'') AS ItemVersion,ISNULL(B.LotMaster,'') AS LotMaster
                                                    ,ISNULL(B.LotDisableDate,'') AS LotDisableDate,ISNULL(B.LotEffectivedate,'') AS LotEffectivedate,ISNULL(B.MO,'') AS MO 
                                                    ,ISNULL(B.MOPick,'') AS MOPick,B.OpNum,ISNULL(B.PickSupplier,'') AS PickSupplier,B.PlanIssueDate,ISNULL(B.PLS,'') AS PLS,B.ItemInfo_ItemPotency
                                                    ,ISNULL(B.Project,'') AS Project,B.StorageType,ISNULL(B.Supplier,'') AS Supplier,ISNULL(B.WhUOM,'') AS WhUOM
                                                    ,B.IssueQty
                                                    from MO_IssueDoc A
                                                    LEFT JOIN MO_IssueDocLine B ON B.IssueDoc=A.ID
                                                    where B.ID='{0}' AND A.Org='{1}'";
                            linesql = string.Format(linesql, LLLineInfo.SourceDetailID, OrgID);
                            DataTable linedt = DBhlper.Query(linesql, connString);
                            if (linedt.Rows.Count == 0)
                            {
                                throw new Exception("行ID:'" + LLLineInfo.SourceDetailID + "''不存在!");
                            }
                            else
                            {
                                UFIDAU9ISVMOPickListDTOData PickInfo = new UFIDAU9ISVMOPickListDTOData();
                                UFIDAU9ISVMOPickListDTOData RollBackPickInfo = new UFIDAU9ISVMOPickListDTOData();
                                PickInfo.m_aCDType = 1;
                                PickInfo.m_benifitMO = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_benifitMO.m_iD = long.Parse(linedt.Rows[0]["BenifitMO"].ToString());
                                PickInfo.m_costField = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_costField.m_iD = long.Parse(linedt.Rows[0]["CostField"].ToString());
                                PickInfo.m_costUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_costUOM.m_iD = long.Parse(linedt.Rows[0]["CostBaseUOM"].ToString());
                                PickInfo.m_costUOMQty = LLLineInfo.IssuedQuantity + LLLineInfo.Quantity;
                                PickInfo.m_fromElement = int.Parse(linedt.Rows[0]["Element"].ToString());
                                PickInfo.m_fromGrade = int.Parse(linedt.Rows[0]["Grade"].ToString());
                                PickInfo.m_isNoPickLine = Convert.ToBoolean(linedt.Rows[0]["IsNoPickLine"]);
                                PickInfo.m_issueDept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_issueDept.m_iD = long.Parse(linedt.Rows[0]["IssueDept"].ToString());
                                PickInfo.m_issueDocLineID = long.Parse(linedt.Rows[0]["ID"].ToString());
                                PickInfo.m_issuedQty = LLLineInfo.IssuedQuantity + LLLineInfo.Quantity;
                                PickInfo.m_issueQty = Convert.ToDecimal(linedt.Rows[0]["IssueQty"].ToString());
                                PickInfo.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_issueUOM.m_iD = long.Parse(linedt.Rows[0]["IssueUOM"].ToString());
                                PickInfo.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_issueWh.m_iD = long.Parse(linedt.Rows[0]["Wh"].ToString());
                                PickInfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_item.m_iD = long.Parse(linedt.Rows[0]["Item"].ToString());
                                PickInfo.m_itemVersion = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_itemVersion.m_iD = long.Parse(linedt.Rows[0]["ItemVersion"].ToString());
                                PickInfo.m_lot = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_lot.m_iD = long.Parse(linedt.Rows[0]["LotMaster"].ToString());
                                if (linedt.Rows[0]["LotDisableDate"].ToString() == "1900-01-01 00:00:00.000")
                                {
                                    PickInfo.m_lotDisableDate = Convert.ToDateTime(linedt.Rows[0]["LotDisableDate"].ToString());
                                }
                                if (linedt.Rows[0]["LotEffectivedate"].ToString() == "1900-01-01 00:00:00.000")
                                {
                                    PickInfo.m_lotEffectivedate = Convert.ToDateTime(linedt.Rows[0]["LotEffectivedate"].ToString());
                                }
                                PickInfo.m_mO = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_mO.m_iD = long.Parse(linedt.Rows[0]["MO"].ToString());
                                PickInfo.m_mOPickList = long.Parse(linedt.Rows[0]["MOPick"].ToString());
                                PickInfo.m_opNum = linedt.Rows[0]["OpNum"].ToString();
                                PickInfo.m_ownerOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_ownerOrg.m_iD = long.Parse(OrgID);
                                PickInfo.m_pickSupplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_pickSupplier.m_iD = long.Parse(linedt.Rows[0]["PickSupplier"].ToString());
                                PickInfo.m_planIssueDate = Convert.ToDateTime(linedt.Rows[0]["PlanIssueDate"].ToString());
                                PickInfo.m_pLS = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_pLS.m_iD = long.Parse(linedt.Rows[0]["PLS"].ToString());
                                PickInfo.m_potency = int.Parse(linedt.Rows[0]["ItemInfo_ItemPotency"].ToString());
                                if (linedt.Rows[0]["Project"].ToString() != "0")
                                {
                                    PickInfo.m_project = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                    PickInfo.m_project.m_iD = long.Parse(linedt.Rows[0]["Project"].ToString());
                                }
                                PickInfo.m_recedeReason = -1;
                                PickInfo.m_storageType = int.Parse(linedt.Rows[0]["StorageType"].ToString());
                                PickInfo.m_supplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_supplier.m_iD = long.Parse(linedt.Rows[0]["Supplier"].ToString());
                                PickInfo.m_whUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                PickInfo.m_whUOM.m_iD = long.Parse(linedt.Rows[0]["WhUOM"].ToString());
                                PickInfo.m_whUOMQty = LLLineInfo.IssuedQuantity + LLLineInfo.Quantity;
                                PickList.Add(PickInfo);

                                RollBackPickInfo.m_aCDType = 1;
                                RollBackPickInfo.m_benifitMO = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_benifitMO.m_iD = long.Parse(linedt.Rows[0]["BenifitMO"].ToString());
                                RollBackPickInfo.m_costField = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_costField.m_iD = long.Parse(linedt.Rows[0]["CostField"].ToString());
                                RollBackPickInfo.m_costUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_costUOM.m_iD = long.Parse(linedt.Rows[0]["CostBaseUOM"].ToString());
                                RollBackPickInfo.m_costUOMQty = Convert.ToDecimal(linedt.Rows[0]["IssueQty"].ToString());
                                RollBackPickInfo.m_fromElement = int.Parse(linedt.Rows[0]["Element"].ToString());
                                RollBackPickInfo.m_fromGrade = int.Parse(linedt.Rows[0]["Grade"].ToString());
                                RollBackPickInfo.m_isNoPickLine = Convert.ToBoolean(linedt.Rows[0]["IsNoPickLine"]);
                                RollBackPickInfo.m_issueDept = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_issueDept.m_iD = long.Parse(linedt.Rows[0]["IssueDept"].ToString());
                                RollBackPickInfo.m_issueDocLineID = long.Parse(linedt.Rows[0]["ID"].ToString());
                                RollBackPickInfo.m_issuedQty = Convert.ToDecimal(linedt.Rows[0]["IssueQty"].ToString());
                                RollBackPickInfo.m_issueQty = Convert.ToDecimal(linedt.Rows[0]["IssueQty"].ToString());
                                RollBackPickInfo.m_issueUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_issueUOM.m_iD = long.Parse(linedt.Rows[0]["IssueUOM"].ToString());
                                RollBackPickInfo.m_issueWh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_issueWh.m_iD = long.Parse(linedt.Rows[0]["Wh"].ToString());
                                RollBackPickInfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_item.m_iD = long.Parse(linedt.Rows[0]["Item"].ToString());
                                RollBackPickInfo.m_itemVersion = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_itemVersion.m_iD = long.Parse(linedt.Rows[0]["ItemVersion"].ToString());
                                RollBackPickInfo.m_lot = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_lot.m_iD = long.Parse(linedt.Rows[0]["LotMaster"].ToString());
                                if (linedt.Rows[0]["LotDisableDate"].ToString() == "1900-01-01 00:00:00.000")
                                {
                                    RollBackPickInfo.m_lotDisableDate = Convert.ToDateTime(linedt.Rows[0]["LotDisableDate"].ToString());
                                }
                                if (linedt.Rows[0]["LotEffectivedate"].ToString() == "1900-01-01 00:00:00.000")
                                {
                                    RollBackPickInfo.m_lotEffectivedate = Convert.ToDateTime(linedt.Rows[0]["LotEffectivedate"].ToString());
                                }
                                RollBackPickInfo.m_mO = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_mO.m_iD = long.Parse(linedt.Rows[0]["MO"].ToString());
                                RollBackPickInfo.m_mOPickList = long.Parse(linedt.Rows[0]["MOPick"].ToString());
                                RollBackPickInfo.m_opNum = linedt.Rows[0]["OpNum"].ToString();
                                RollBackPickInfo.m_ownerOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_ownerOrg.m_iD = long.Parse(OrgID);
                                RollBackPickInfo.m_pickSupplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_pickSupplier.m_iD = long.Parse(linedt.Rows[0]["PickSupplier"].ToString());
                                RollBackPickInfo.m_planIssueDate = Convert.ToDateTime(linedt.Rows[0]["PlanIssueDate"].ToString());
                                RollBackPickInfo.m_pLS = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_pLS.m_iD = long.Parse(linedt.Rows[0]["PLS"].ToString());
                                RollBackPickInfo.m_potency = int.Parse(linedt.Rows[0]["ItemInfo_ItemPotency"].ToString());
                                if (linedt.Rows[0]["Project"].ToString() != "0")
                                {
                                    RollBackPickInfo.m_project = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                    RollBackPickInfo.m_project.m_iD = long.Parse(linedt.Rows[0]["Project"].ToString());
                                }
                                RollBackPickInfo.m_recedeReason = -1;
                                RollBackPickInfo.m_storageType = int.Parse(linedt.Rows[0]["StorageType"].ToString());
                                RollBackPickInfo.m_supplier = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_supplier.m_iD = long.Parse(linedt.Rows[0]["Supplier"].ToString());
                                RollBackPickInfo.m_whUOM = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                RollBackPickInfo.m_whUOM.m_iD = long.Parse(linedt.Rows[0]["WhUOM"].ToString());
                                RollBackPickInfo.m_whUOMQty = Convert.ToDecimal(linedt.Rows[0]["IssueQty"].ToString());
                                RollBackPickList.Add(RollBackPickInfo);
                            }
                        }
                        LL.m_issueDTO.m_pickListDTOs = PickList.ToArray();
                        LLlist.Add(LL);
                        RollBackLL.m_issueDTO.m_pickListDTOs = RollBackPickList.ToArray();
                        RollBackLLlist.Add(RollBackLL);
                    }
                }

                context = CreateContextObj(OrgID);
                bool issuccess = false;
                if (LLlist.Count > 0)
                {
                    issuccess = client.Do(out message, context, LLlist.ToArray());
                }
                else
                {
                    issuccess = true;
                }
                if (issuccess == false)
                {
                    throw new Exception("生产订单修改失败");
                }
                else
                {
                    int Count = 0;
                    string chksql = @"select B.IssueQty,B.IssuedQty from MO_IssueDoc A
                                      LEFT JOIN MO_IssueDocLine B ON B.IssueDoc=A.ID
                                      where A.DocNo='{0}' AND A.Org='{1}'";
                    chksql = string.Format(chksql, infos[0].SourceCode, OrgID);
                    DataTable chkdt = DBhlper.Query(chksql, connString);
                    foreach (DataRow dr in chkdt.Rows)
                    {
                        if (Convert.ToDecimal(dr["IssueQty"]) <= Convert.ToDecimal(dr["IssuedQty"]))
                        {
                            Count++;
                        }
                    }
                    if (chkdt.Rows.Count != 0 && chkdt.Rows.Count == Count)
                    {
                        List<string> DocList = new List<string>();
                        DocList.Add(infos[0].SourceCode);
                        ApproveIssue approve = new ApproveIssue();
                        bool ApproveResult = approve.Approve(DocList, infos[0].WorkPoint);
                        if (ApproveResult == true)
                        {
                            #region 审核后修改单据审核人
                            string usersql = @"select Name from Base_User
                                               where Code='{0}'";
                            usersql = string.Format(usersql, infos[0].User);
                            DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                            if (userdt.Rows.Count != 0)
                            {
                                usersql = @"update MO_IssueDoc set ApproveBy='{0}',ModifiedBy='{0}'
                                where ID='{1}'
                                update MO_IssueDocLine set ModifiedBy='{0}'
                                where IssueDoc='{1}'";
                                usersql = string.Format(usersql, userdt.Rows[0]["Name"].ToString(), infos[0].ID);
                                DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                            }
                            #endregion
                            return true;
                        }
                        else
                        {
                            if (RollBackLLlist.Count > 0)
                            {
                                client.Do(out message, context, RollBackLLlist.ToArray());
                            }
                            throw new Exception("生产领料单审核失败");
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }



        }

        public Result ActionCreateMaterialDelivery(List<ICSRdrecord11> infos)
        {
            Result result = new Result();
            var datalist = new List<ICSRdrecord11>();
            foreach (var info in infos)
            {
                try
                {
                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, connString);
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("组织编码错误!");
                    }

                    var UserCode = "";

                    string sql = "select ID from Base_User where Code ='" + info.User + "'";
                    DataTable dt = DBhlper.Query(sql, connString);
                    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();
                    }
                    else
                    {
                        UserCode = info.User;
                    }

                    bool NeedOverIssue = false;
                    string docHeadsql = @"select IsOverIssue,IssueDepartment from Issue_IssueApplyDoc
                                          where DocNo='{0}' and Org='{1}'";

                    docHeadsql = string.Format(docHeadsql, info.SourceCode, OrgID);
                    DataTable docHeaddt = DBhlper.Query(docHeadsql, connString);
                    if (docHeaddt.Rows.Count != 0)
                    {
                        NeedOverIssue = Convert.ToBoolean(docHeaddt.Rows[0]["IsOverIssue"]);
                    }
                    else
                    {
                        throw new Exception("领料申请单不存在!");
                    }
                    List<CreateMaterialDeliveryDocAPIModel> HeadList = new List<CreateMaterialDeliveryDocAPIModel>();
                    CreateMaterialDeliveryDocAPIModel HeadInfo = new CreateMaterialDeliveryDocAPIModel();
                    List<LineData> BodyList = new List<LineData>();
                    LineData BodyInfo = new LineData();
                    int SourceType = 0;

                    HeadInfo = new CreateMaterialDeliveryDocAPIModel();
                    BodyList = new List<LineData>();
                    HeadInfo.IssueType = 0;
                    HeadInfo.BusinessDate = DateTime.Now;
                    if (NeedOverIssue == true)
                    {
                        #region 获取类型为超额的材料出库单类型
                        string docsql = @"select ID,Code from Issue_MaterialDeliveryDocType
                                          where IsOverIssue='true'";
                        DataTable docdt = DBhlper.Query(docsql, connString);
                        if (docdt.Rows.Count == 0)
                        {
                            throw new Exception("未维护超额类型的材料出库单!");
                        }

                        HeadInfo.MaterialDeliveryDocType = new DocType();
                        HeadInfo.MaterialDeliveryDocType.ID = long.Parse(docdt.Rows[0]["ID"].ToString());
                        HeadInfo.MaterialDeliveryDocType.Code = docdt.Rows[0]["Code"].ToString();
                        SourceType = int.Parse(docdt.Rows[0]["Code"].ToString());

                        #endregion
                    }
                    foreach (rdrecords11 line in info.details)
                    {
                        //根据传入行ID查询申请单行信息
                        string linesql = @"select A.ID,MOPick,SupplyWh,Project,LotMaster,ItemInfo,B.Code AS ItemCode from Issue_IssueApplyDocLine A
                                           LEFT JOIN CBO_ItemMaster B ON B.ID=A.ItemInfo
                                           where A.ID='{0}'";
                        linesql = string.Format(linesql, line.SourceDetailID);
                        DataTable linedt = DBhlper.Query(linesql, connString);
                        if (linedt.Rows.Count == 0)
                        {
                            throw new Exception("传入领料申请单行的ID:" + line.SourceDetailID + "无法在U9查询到相关信息!");
                        }

                        string whsql = @"select IsLot,ID from CBO_Wh where Code ='" + line.WHCode + "' and Org=" + OrgID;
                        DataTable whdt = DBhlper.Query(whsql, connString);

                        DataTable infodt = new DataTable();
                        if (whdt.Rows.Count == 0)
                        {
                            throw new Exception("传入仓库不存在，仓库：" + line.WHCode);
                        }

                        long WhID = long.Parse(whdt.Rows[0]["ID"].ToString());

                        //long LotID = 0;
                        //if (line.BatchCode != "")
                        //{
                        //    //批号ID获取
                        //    string infosql = @"select ID from Lot_LotMaster
                        //                               where LotCode='{0}' and ItemCode='{1}'";
                        //    infosql = string.Format(infosql, line.BatchCode, line.InvCode);
                        //    infodt = DBhlper.Query(infosql, connString);
                        //    if (infodt.Rows.Count == 0)
                        //    {
                        //        throw new Exception("传入批号:" + line.BatchCode + "无法在U9查询到相关信息!");
                        //    }
                        //    else
                        //    {
                        //        LotID = long.Parse(infodt.Rows[0]["ID"].ToString());
                        //    }
                        //}



                        BodyInfo = new LineData();
                        BodyInfo.SourceDocType = 1;
                        BodyInfo.IssueApplyDocLine = new IssueApplyDocLine();
                        BodyInfo.IssueApplyDocLine.ID = long.Parse(line.SourceDetailID);
                        BodyInfo.Wh = new Wh();
                        BodyInfo.Wh.ID = WhID;
                        BodyInfo.IssuedQty = line.Quantity;
                        BodyInfo.WhUOMQty = line.WarehouseQuantity;


                        BodyInfo.Lot = new Lot { Code = line.BatchCode };
                        //if (LotID != 0)
                        //{
                        //    BodyInfo.Lot = new Lot();
                        //    BodyInfo.Lot.ID = LotID;
                        //    BodyInfo.Lot.Code = line.BatchCode;
                        //}
                        BodyInfo.Item = new Item();
                        BodyInfo.Item.ID = long.Parse(linedt.Rows[0]["ItemInfo"].ToString());
                        BodyInfo.Item.Code = linedt.Rows[0]["ItemCode"].ToString();
                        

                        BodyInfo.DescFlexField = new DescFlexField();
                        BodyInfo.DescFlexField.PrivateDescSeg30 = line.LogIds;

                        BodyList.Add(BodyInfo);

                    }
                    HeadInfo.MaterialDeliveryDocLines = BodyList;
                    HeadList.Add(HeadInfo);

                    string postJson = JsonConvert.SerializeObject(HeadList);
                    APIreturnInfo value = new APIreturnInfo();
                    value = PostJsonToMaterialDelivery(postJson, UserCode, info.WorkPoint);
                    if (value.IsSuccess == true)
                    {
                        string rtnsql = @"  
                            select DISTINCT a.ID,a.DocNo,b.ID LineID,b.DocLineNo,c.Code,b.IssueQty,
                            b.SourceDoc_SrcDocLine_EntityID,b.DescFlexField_PrivateDescSeg30
                            from Issue_MaterialDeliveryDoc a		
							left join Issue_MaterialDeliveryDocLine b on a.ID = b.MaterialDeliveryDoc
							left join CBO_ItemMaster c on b.ItemInfo = c.ID
                            WHERE a.DocNo='{0}' and a.Org='{1}'";
                        rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                        DataTable mdt = DBhlper.Query(rtnsql, connString);
                        if (mdt.Rows.Count > 0)
                        {
                            var linelist = new List<rdrecords11>();

                            foreach (DataRow dr in mdt.Rows)
                            {
                                linelist.Add(new rdrecords11
                                {
                                    DetailID = dr["LineID"].ToString(),
                                    SourceDetailID = dr["SourceDoc_SrcDocLine_EntityID"].ToString(),
                                    LogIds = dr["DescFlexField_PrivateDescSeg30"].ToString(),
                                    Sequence = dr["DocLineNo"].ToString(),
                                    InvCode = dr["Code"].ToString(),
                                    Quantity = decimal.Parse(dr["IssueQty"].ToString())
                                });
                            }

                            datalist.Add(new ICSRdrecord11
                            {
                                IsSuccess = true,
                                Message = "成功",
                                ID = mdt.Rows[0]["ID"].ToString(),
                                IssueCode = mdt.Rows[0]["DocNo"].ToString(),
                                details = linelist
                            });
                        }
                        else
                        {
                            throw new Exception("未获取到U9标准接口返回的单据编码");
                        }
                    }
                    else
                    {
                        throw new Exception(value.Message);
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<rdrecords11>();

                    foreach (var item in info.details)
                    {
                        linelist.Add(new rdrecords11
                        {
                            SourceDetailID = item.SourceDetailID,
                            LogIds = item.LogIds,
                            Sequence = item.Sequence
                        });
                    }

                    datalist.Add(new ICSRdrecord11
                    {
                        IsSuccess = false,
                        Message = ex.Message,
                        details = linelist
                    });
                }
            }

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

        public  APIreturnInfo PostJsonToMaterialDelivery(string DataJson, string CreateByCode, string ORGCode)
        {
            APIreturnInfo valueRet = new APIreturnInfo();
            bool IsDelete = false;
            string DocNo = "";
            long ID = -1;
            try
            {
                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Create";
                    CreateUrl = string.Format(CreateUrl, U9IP);

                    Appconfig.WriteLogFile("创建材料出库单调用接口Json：" + DataJson, LogName);

                    string resultCreateSoFile = PostData.APT(CreateUrl, DataJson, TokenCode);

                    Appconfig.WriteLogFile("创建材料出库单返回Json：" + resultCreateSoFile, LogName);

                    CreateMaterialDeliveryWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultCreateSoFile);
                    if (RetModel.Success == true &&
                        RetModel.Data != null && RetModel.Data.Count > 0)
                    {
                        var IsTrues = RetModel.Data.Where(a => a.m_isSucess == false).ToList();
                        if (IsTrues != null && IsTrues.Count() > 0)
                        {
                            throw new Exception(IsTrues[0].m_errorMsg);
                        }
                        else
                        {
                            IsDelete = true;
                            DocNo = RetModel.Data[0].m_code;
                            if (!string.IsNullOrEmpty(RetModel.Data[0].m_iD))
                            {
                                ID = long.Parse(RetModel.Data[0].m_iD);
                            }
                            else
                            {
                                ID = GetDocID(DocNo, ORGCode);
                            }

                            #region 审核材料出库单
                            List<OperateMaterialDeliveryModel> ListDoc = new List<OperateMaterialDeliveryModel>();
                            OperateMaterialDeliveryModel subm = new OperateMaterialDeliveryModel();
                            int Version = GetMaterialDeliveryDocSysVersion(ID);
                            subm.ID = ID;
                            subm.DocNo = RetModel.Data[0].m_code;
                            subm.CurrentSysVersion = Version;
                            subm.isAutoApp = true;
                            ListDoc.Add(subm);
                            string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                            TokenCode = GetToken(CreateByCode, ORGCode);

                            string SubmitUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Approve";
                            SubmitUrl = string.Format(SubmitUrl, U9IP);

                            Appconfig.WriteLogFile("审核材料出库单调用接口Json：" + postSubmitJson, LogName);

                            string resultSubmFile = PostData.APT(SubmitUrl, postSubmitJson, TokenCode);

                            Appconfig.WriteLogFile("审核材料出库单返回Json：" + resultSubmFile, LogName);


                            RetModel = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultSubmFile);

                            if (RetModel.Success == true &&
                        RetModel.Data != null && RetModel.Data.Count > 0)
                            {
                                IsTrues = RetModel.Data.Where(a => a.m_isSucess == false).ToList();
                                if (IsTrues != null && IsTrues.Count() > 0)
                                {
                                    throw new Exception("审核失败：" + IsTrues[0].m_errorMsg);
                                }
                                else
                                {
                                    valueRet.IsSuccess = true;
                                    valueRet.DocNo = DocNo;
                                    valueRet.Message = "创建成功";
                                }
                            }
                            else
                            {
                                throw new Exception("审核失败：" + RetModel.ResMsg);
                            }

                            #endregion
                        }
                    }
                    else
                    {
                        throw new Exception(RetModel.ResMsg);
                    }
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                if (IsDelete)
                {
                    //删除材料出库
                    try
                    {
                        List<OperateMaterialDeliveryModel> ListDoc4 = new List<OperateMaterialDeliveryModel>();
                        OperateMaterialDeliveryModel delm = new OperateMaterialDeliveryModel();
                        int Version = GetDocSysVersion(ID);
                        delm.ID = ID;
                        delm.DocNo = DocNo;
                        delm.CurrentSysVersion = Version;
                        delm.isAutoApp = true;
                        ListDoc4.Add(delm);
                        string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                        string TokenCode = GetToken(CreateByCode, ORGCode);

                        string DelUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Delete";
                        DelUrl = string.Format(DelUrl, ConfigurationManager.AppSettings["U9IP"].ToString());
                        Appconfig.WriteLogFile("删除材料出库单调用接口Json：" + postDelJson, LogName);
                        string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                        Appconfig.WriteLogFile("删除材料出库单返回Json：" + resultDelFile, LogName);

                        CreateMaterialDeliveryWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultDelFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.m_isSucess == false).ToList();
                            if (IsTrues != null && IsTrues.Count() > 0)
                            {
                                throw new Exception("单据创建成功，删除失败：" + IsTrues[0].m_errorMsg + "，单据异常：" + ex.Message);
                            }

                            throw new Exception("创建成功，提交审核失败，单据已删除，异常：" + ex.Message);
                        }
                        else
                        {
                            throw new Exception("单据创建成功，删除失败：" + RetModel.ResMsg + "，单据异常：" + ex.Message);
                        }
                    }
                    catch (Exception exdelte)
                    {
                        valueRet.IsSuccess = false;
                        valueRet.Message = exdelte.Message;
                    }
                }
                else
                {
                    valueRet.IsSuccess = false;
                    valueRet.Message = "创建失败：" + ex.Message;
                }
            }
            return valueRet;
        }

        public static string GetToken(string CreateByCode, string ORGCode)
        {
            Appconfig.WriteLogFile("调用接口CreateByCode：" + CreateByCode + ORGCode + ",ORGCode:" + ORGCode, LogName);

            if (ConfigurationManager.AppSettings["clientid"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["clientid"].ToString()))
            {
                throw new Exception("请联系管理员，未配置clientid。");
            }
            if (ConfigurationManager.AppSettings["clientsecret"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["clientsecret"].ToString()))
            {
                throw new Exception("请联系管理员，未配置clientsecret。");
            }
            if (ConfigurationManager.AppSettings["U9IP"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["U9IP"].ToString()))
            {
                throw new Exception("请联系管理员，未配置U9IP。");
            }
            if (ConfigurationManager.AppSettings["enterpriseID"] == null || string.IsNullOrEmpty(ConfigurationManager.AppSettings["enterpriseID"].ToString()))
            {
                throw new Exception("请联系管理员，未配置enterpriseID。");
            }

            string clientid = ConfigurationManager.AppSettings["clientid"].ToString();
            string clientsecret = ConfigurationManager.AppSettings["clientsecret"].ToString();
            string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
            string enterpriseID = ConfigurationManager.AppSettings["enterpriseID"].ToString();
            DateTime dateTime = DateTime.Now;
            string url = "http://{2}/u9c/webapi/OAuth2/GetAuthorizeCode?clientid={0}&clientsecret={1}";
            url = string.Format(url, clientid, clientsecret, U9IP);
            string resultuu = PostData.GetInfo("", url);

            Appconfig.WriteLogFile("授权返回Json：" + resultuu, LogName);

            JObject objuu = new JObject();
            objuu = JObject.Parse(resultuu);

            string keyCode = objuu["Data"].ToString();
            if (!string.IsNullOrWhiteSpace(keyCode))
            {
                string ToeknUrl = "http://{4}/u9c/webapi/OAuth2/Login?userCode={0}&entcode={1}&orgcode={2}&code={3}";
                ToeknUrl = string.Format(ToeknUrl, CreateByCode, enterpriseID, ORGCode, keyCode, U9IP);
                string resultToken = PostData.GetInfo("", ToeknUrl);

                Appconfig.WriteLogFile("Token返回Json：" + resultToken, LogName);
                JObject objToken = new JObject();
                objuu = JObject.Parse(resultToken);
                string TokenCode = objuu["Data"].ToString();
                return TokenCode;
            }
            else
            {
                throw new Exception("获取token失败");
            }


        }

        public static int GetMaterialDeliveryDocSysVersion(long ID)
        {
            try
            {
                int version = 0;
                string sqsql = @"select SysVersion from Issue_MaterialDeliveryDoc
                                  where ID='{0}'";
                sqsql = string.Format(sqsql, ID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    version = int.Parse(sqdt.Rows[0]["SysVersion"].ToString());
                }
                return version;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static long GetDocID(string DocNO, string OrgCode)
        {
            try
            {
                long ID = 0;
                string sqsql = @"select A.ID from Issue_IssueApplyDoc A
                                 LEFT JOIN Base_Organization B ON B.ID=A.Org
                                 where A.DocNo='{0}' AND B.Code='{1}'";
                sqsql = string.Format(sqsql, DocNO, OrgCode);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    ID = long.Parse(sqdt.Rows[0]["ID"].ToString());
                }
                return ID;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static string GetDocStatus(long ID)
        {
            try
            {
                string Status = "";
                string sqsql = @"select DocState from Issue_IssueApplyDoc
                                  where ID='{0}'";
                sqsql = string.Format(sqsql, ID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    Status = sqdt.Rows[0]["DocState"].ToString();
                }
                return Status;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        public static int GetDocSysVersion(long ID)
        {
            try
            {
                int version = 0;
                string sqsql = @"select SysVersion from Issue_IssueApplyDoc
                                  where ID='{0}'";
                sqsql = string.Format(sqsql, ID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    version = int.Parse(sqdt.Rows[0]["SysVersion"].ToString());
                }
                return version;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        public string CheckERPDocKind(string DocNO, string OrgCode)
        {
            try
            {
                string str = "";
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, OrgCode);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                string sqsql = @"select ID from Issue_IssueApplyDoc
                                  where DocNo='{0}' and Org='{1}'";
                sqsql = string.Format(sqsql, DocNO, OrgID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (sqdt.Rows.Count != 0)
                {
                    str = "领料申请单";
                }
                else
                {
                    str = "生产领料单";
                }
                return str;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// 创建上下文
        /// </summary>
        /// <returns></returns>
        private static ThreadContext CreateContextObj(string OrgID)
        {
            // 实例化应用上下文对象
            ThreadContext thContext = new ThreadContext();

            System.Collections.Generic.Dictionary<object, object> ns = new Dictionary<object, object>();
            ns.Add("OrgID", OrgID);
            ns.Add("UserID", ConfigurationManager.AppSettings["userID"].ToString());
            ns.Add("UserCode", ConfigurationManager.AppSettings["userCode"].ToString());
            ns.Add("Datetime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            ns.Add("CultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("EnterpriseID", ConfigurationManager.AppSettings["enterpriseID"].ToString());
            ns.Add("DefaultCultureName", ConfigurationManager.AppSettings["cultureName"].ToString());
            ns.Add("acttype", ConfigurationManager.AppSettings["acttype"].ToString());
            thContext.nameValueHas = ns;

            return thContext;

            return thContext;
        }

        public class rtnMaterialDeliveryInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public object Data { get; set; }
        }

        #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 APIreturnInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }

    }


}
