using ICSSoft.Common;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ICSSoft.Entity;
using UFSoft.UBF.Util.Context;
using System.ServiceModel;
using ICSSoft.DataProject;
using ICS.WCF.Base;
using UFIDA.ISV.WCRCVLineApprove;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace ICSSoft.APIApproveRCV
{
    public class ApproveRCV
    {
        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 = "创建材料出库单";

        public Result Approve(List<ICSPurchaseReceiveDoc> infos)
        {
            var datalist = new List<ICSPurchaseReceiveDoc>();
            var res = new Result();
            foreach (ICSPurchaseReceiveDoc 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, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }

                    var UserID = "";
                    var UserCode = "";
                    var UserName = "";
                    string usersql = @"select Name,ID,Code from Base_User
                                   where Code='{0}'";
                    usersql = string.Format(usersql, Info.User);
                    DataTable userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    if (userdt.Rows.Count == 0)
                    {
                        usersql = @"select Name,ID,Code from Base_User
                                   where Code='{0}'";
                        usersql = string.Format(usersql, Appconfig.GetDefaultUser());
                        userdt = DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                        if (userdt.Rows.Count == 0)
                        {
                            throw new Exception("未获取到用户ID");
                        }
                    }

                    UserID = userdt.Rows[0]["ID"].ToString();
                    UserCode = userdt.Rows[0]["Code"].ToString();
                    UserName = userdt.Rows[0]["Name"].ToString();

                    long DocID = 0;
                    string EntityType = "";
                    Decimal RCVQty = 0;
                    string DocNO = "";
                    DataTable dt = GetRCVDataByIdOrCode(Info.ID, Info.RCVTCode, OrgID);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("传入的单据ID：" + Info.ID + "及单据号:" + Info.RCVTCode + "找不到对应的收货单!");
                    }
                    else
                    {
                        if (dt.Rows[0]["Status"].ToString() == "4" || dt.Rows[0]["Status"].ToString() == "5")
                        {
                            throw new Exception("该单据在U9已关闭");
                        }
                        DocID = long.Parse(dt.Rows[0]["ID"].ToString());
                        DocNO = dt.Rows[0]["DocNO"].ToString();
                    }
                    bool IsLineApprove = false;
                    DataTable chkdt = new DataTable();
                    string chksql = @"select IsLineApprove from PM_Receivement
	                                  where ID='" + DocID + "'";
                    chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                    if (chkdt.Rows.Count != 0)
                    {
                        IsLineApprove = Convert.ToBoolean(chkdt.Rows[0]["IsLineApprove"].ToString());
                    }
                    List<ICSOutsourcingReceiveDocssapprove> DCDataLineList = new List<ICSOutsourcingReceiveDocssapprove>();
                    if (!Info.IsLineApprove)
                    {
                        if (IsLineApprove)
                        {
                            throw new Exception("该单据是行审单据");
                        }


                        //实例化代理类 
                        UFIDAU9PMRcvIRcvApprovedSVClient client = new UFIDAU9PMRcvIRcvApprovedSVClient();
                        //服务返回结果
                        //UFIDAU9PMPOPurchaseOrderData[] returnItems;
                        //返回异常信息，目前还没有使用此属性
                        UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                        //上下文信息
                        object context;
                        //传入 参数
                        //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
                        UFSoft.UBF.Business.BusinessEntity.EntityKey docHead = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                        int acttype = int.Parse(ConfigurationManager.AppSettings["acttype"].ToString());
                        //给上下文信息赋值
                        context = CreateContextObj(OrgID,UserID,UserCode);
                        //给传入参数赋值
                        docHead.ID = DocID;

                        //pOList = SetPoDtos(U9Info, poInfoList);
                        //服务调用
                        (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                        (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;


                        try
                        {
                            returnMsg = client.Do(context, acttype, docHead);
                            if (returnMsg != null)
                            {
                                if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                                {
                                    throw new Exception(returnMsg[0].localMessage);
                                }
                            }

                            #region 审核后修改单据审核人
                            usersql = @"update PM_Receivement set ApprovedBy='{0}',ModifiedBy='{0}'
                                where ID='{1}'";
                            usersql = string.Format(usersql, UserName, infos[0].ID);
                            DBhlper.Query(usersql, Appconfig.GetU9ConnStr());

                            #endregion


                            chksql = @"select DocNO,BizType,IsLineApprove from PM_Receivement
	                                  where ID='" + DocID + "'";
                            chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                            if (chkdt.Rows.Count != 0)
                            {
                                if (chkdt.Rows[0]["BizType"].ToString() == "326")
                                {
                                    DocNO = chkdt.Rows[0]["DocNO"].ToString();
                                    if (chkdt.Rows[0]["IsLineApprove"].ToString() == "0")
                                    {
                                        #region 整单倒冲
                                        string dcsql = @"select D.ID,C.ID AS DetailID,A.DocNo AS SourceCode
                                                 ,Convert(nvarchar,B.DocLineNo)+'~'+Convert(nvarchar,H.PickLineNo) AS SourceSequence
												 ,D.DocNo AS TransCode,C.LineNum AS TransSequence,C.LineNum
												 ,C.IssuedQtyByWhUOM AS IssuedQty,E.Code AS INVCode,F.Code AS WHCode
                                                 ,B.ID AS SourceDetailID ,ISNULL(G.Code,'') AS LotCode,D.CreatedOn
                                                 ,H.ID AS PickID,I.ID AS OODetailID
                                                 INTO #TEMP from PM_Receivement A
                                                 LEFT JOIN PM_RcvLine B ON B.Receivement=A.ID
                                                 LEFT JOIN PM_IssueDocLine C ON C.SourceDoc_SrcDocLine_EntityID=B.ID
                                                 LEFT JOIN PM_IssueDoc D ON D.ID=C.PMIssueDoc
                                                 LEFT JOIN CBO_ItemMaster E ON E.ID=C.Item
                                                 LEFT JOIN CBO_Wh F ON F.ID=C.Wh
											     LEFT JOIN Lot_LotMaster G ON G.ID=C.LotMaster
												 LEFT JOIN CBO_SCMPickList H ON H.ID=C.POPick
												 LEFT JOIN PM_POLine I ON I.ID=B.SrcDoc_SrcDocLine_EntityID
                                                 WHERE A.DocNo='{0}'
												 AND A.Org='{1}' AND ReverseIssue='1'
                                                 order by C.CreatedOn DESC

												 SELECT * FROM #TEMP
												 WHERE CreatedOn=(SELECT MAX(CreatedOn) FROM #TEMP)

												 DROP TABLE #TEMP";
                                        dcsql = string.Format(dcsql, DocNO, OrgID);
                                        DataTable dcdt = DBhlper.Query(dcsql, Appconfig.GetU9ConnStr());
                                        if (dcdt.Rows.Count > 0)
                                        {

                                            foreach (DataRow dr in dcdt.Rows)
                                            {
                                                ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                DCDataLine.ID = dr["ID"].ToString();
                                                DCDataLine.DetailID = dr["DetailID"].ToString();
                                                DCDataLine.SourceDetailID = dr["SourceDetailID"].ToString();
                                                DCDataLine.SourceCode = dr["SourceCode"].ToString();
                                                DCDataLine.SourceSequence = dr["SourceSequence"].ToString();
                                                DCDataLine.TransCode = dr["TransCode"].ToString();
                                                DCDataLine.TransSequence = dr["TransSequence"].ToString();
                                                DCDataLine.InvCode = dr["INVCode"].ToString();
                                                DCDataLine.WHCode = dr["WHCode"].ToString();
                                                DCDataLine.Quantity = Convert.ToDecimal(dr["IssuedQty"].ToString());
                                                DCDataLine.BatchCode = dr["LotCode"].ToString();
                                                DCDataLine.OODetailID = dr["OODetailID"].ToString();
                                                DCDataLine.PickID = dr["PickID"].ToString();
                                                DCDataLineList.Add(DCDataLine);
                                            }
                                        }
                                        else
                                        {
                                            foreach (var item in Info.details)
                                            {
                                                ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                DCDataLine.ID = "";
                                                DCDataLine.DetailID = "";
                                                DCDataLine.SourceDetailID = "";
                                                DCDataLine.SourceCode = "";
                                                DCDataLine.SourceSequence = "";
                                                DCDataLine.TransCode = "";
                                                DCDataLine.TransSequence = "";
                                                DCDataLine.InvCode = "";
                                                DCDataLine.WHCode = "";
                                                DCDataLine.Quantity = 0;
                                                DCDataLine.BatchCode = "";
                                                DCDataLine.OODetailID = "";
                                                DCDataLine.PickID = "";
                                                DCDataLineList.Add(DCDataLine);
                                            }
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        #region 行审核倒冲
                                        foreach (ICSPurchaseReceiveDocs Infos in Info.details)
                                        {
                                            string dcsql = @"select D.ID,C.ID AS DetailID,A.DocNo AS SourceCode
                                                 ,Convert(nvarchar,B.DocLineNo)+'~'+Convert(nvarchar,H.PickLineNo) AS SourceSequence
												 ,D.DocNo AS TransCode,C.LineNum AS TransSequence,C.LineNum
												 ,C.IssuedQtyByWhUOM AS IssuedQty,E.Code AS INVCode,F.Code AS WHCode
                                                 ,B.ID AS SourceDetailID ,ISNULL(G.Code,'') AS LotCode,D.CreatedOn
                                                 ,H.ID AS PickID,I.ID AS OODetailID
                                                 INTO #TEMP from PM_Receivement A
                                                 LEFT JOIN PM_RcvLine B ON B.Receivement=A.ID
                                                 LEFT JOIN PM_IssueDocLine C ON C.SourceDoc_SrcDocLine_EntityID=B.ID
                                                 LEFT JOIN PM_IssueDoc D ON D.ID=C.PMIssueDoc
                                                 LEFT JOIN CBO_ItemMaster E ON E.ID=C.Item
                                                 LEFT JOIN CBO_Wh F ON F.ID=C.Wh
											     LEFT JOIN Lot_LotMaster G ON G.ID=C.LotMaster
												 LEFT JOIN CBO_SCMPickList H ON H.ID=C.POPick
												 LEFT JOIN PM_POLine I ON I.ID=B.SrcDoc_SrcDocLine_EntityID
                                                 WHERE A.DocNo='{0}' AND B.DocLineNo='{1}'
												 AND A.Org='{2}' AND ReverseIssue='1'
                                                 order by C.CreatedOn DESC

												 SELECT * FROM #TEMP
												 WHERE CreatedOn=(SELECT MAX(CreatedOn) FROM #TEMP)

												 DROP TABLE #TEMP";
                                            dcsql = string.Format(dcsql, DocNO, Infos.DNSequence, OrgID);
                                            DataTable dcdt = DBhlper.Query(dcsql, Appconfig.GetU9ConnStr());
                                            if (dcdt.Rows.Count > 0)
                                            {
                                                foreach (DataRow dr in dcdt.Rows)
                                                {
                                                    ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                    DCDataLine.ID = dr["ID"].ToString();
                                                    DCDataLine.DetailID = dr["DetailID"].ToString();
                                                    DCDataLine.SourceDetailID = dr["SourceDetailID"].ToString();
                                                    DCDataLine.SourceCode = dr["SourceCode"].ToString();
                                                    DCDataLine.SourceSequence = dr["SourceSequence"].ToString();
                                                    DCDataLine.TransCode = dr["TransCode"].ToString();
                                                    DCDataLine.TransSequence = dr["TransSequence"].ToString();
                                                    DCDataLine.InvCode = dr["INVCode"].ToString();
                                                    DCDataLine.WHCode = dr["WHCode"].ToString();
                                                    DCDataLine.Quantity = Convert.ToDecimal(dr["IssuedQty"].ToString());
                                                    DCDataLine.BatchCode = dr["LotCode"].ToString();
                                                    DCDataLine.OODetailID = dr["OODetailID"].ToString();
                                                    DCDataLine.PickID = dr["PickID"].ToString();
                                                    DCDataLineList.Add(DCDataLine);
                                                }
                                            }
                                            else
                                            {
                                                foreach (var item in Info.details)
                                                {
                                                    ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                    DCDataLine.ID = "";
                                                    DCDataLine.DetailID = "";
                                                    DCDataLine.SourceDetailID = "";
                                                    DCDataLine.SourceCode = "";
                                                    DCDataLine.SourceSequence = "";
                                                    DCDataLine.TransCode = "";
                                                    DCDataLine.TransSequence = "";
                                                    DCDataLine.InvCode = "";
                                                    DCDataLine.WHCode = "";
                                                    DCDataLine.Quantity = 0;
                                                    DCDataLine.BatchCode = "";
                                                    DCDataLine.OODetailID = "";
                                                    DCDataLine.PickID = "";
                                                    DCDataLineList.Add(DCDataLine);
                                                }
                                            }

                                        }
                                        #endregion
                                    }
                                }
                                else
                                {
                                    foreach (var item in Info.details)
                                    {
                                        ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                        DCDataLine.ID = "";
                                        DCDataLine.DetailID = "";
                                        DCDataLine.SourceDetailID = "";
                                        DCDataLine.SourceCode = "";
                                        DCDataLine.SourceSequence = "";
                                        DCDataLine.TransCode = "";
                                        DCDataLine.TransSequence = "";
                                        DCDataLine.InvCode = "";
                                        DCDataLine.WHCode = "";
                                        DCDataLine.Quantity = 0;
                                        DCDataLine.BatchCode = "";
                                        DCDataLine.OODetailID = "";
                                        DCDataLine.PickID = "";
                                        DCDataLineList.Add(DCDataLine);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var item in Info.details)
                                {
                                    ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                    DCDataLine.ID = "";
                                    DCDataLine.DetailID = "";
                                    DCDataLine.SourceDetailID = "";
                                    DCDataLine.SourceCode = "";
                                    DCDataLine.SourceSequence = "";
                                    DCDataLine.TransCode = "";
                                    DCDataLine.TransSequence = "";
                                    DCDataLine.InvCode = "";
                                    DCDataLine.WHCode = "";
                                    DCDataLine.Quantity = 0;
                                    DCDataLine.BatchCode = "";
                                    DCDataLine.OODetailID = "";
                                    DCDataLine.PickID = "";
                                    DCDataLineList.Add(DCDataLine);
                                }

                            }

                            var linelist = new List<ICSPurchaseReceiveDocs>();
                            foreach (var item in Info.details)
                            {
                                linelist.Add(new ICSPurchaseReceiveDocs
                                {
                                    DetailID = item.DetailID,
                                    LogIds = item.LogIds,
                                    IsSuccess = true,
                                    Message = "成功",
                                    detailss = DCDataLineList
                                });
                            }

                            datalist.Add(new ICSPurchaseReceiveDoc
                            {
                                ID = Info.ID,
                                RCVTCode = Info.RCVTCode,
                                details = linelist
                            });

                        }
                        catch (Exception ex)
                        {
                            var linelist = new List<ICSPurchaseReceiveDocs>();
                            foreach (var item in Info.details)
                            {
                                linelist.Add(new ICSPurchaseReceiveDocs
                                {
                                    DetailID = item.DetailID,
                                    LogIds = item.LogIds,
                                    IsSuccess = false,
                                    Message = "失败，异常：" + ex.Message,
                                    detailss = DCDataLineList
                                });
                            }

                            datalist.Add(new ICSPurchaseReceiveDoc
                            {
                                ID = Info.ID,
                                RCVTCode = Info.RCVTCode,
                                details = linelist
                            });
                        }
                    }
                    else
                    {
                        try
                        {
                            if (!IsLineApprove)
                            {
                                throw new Exception("该单据是整单审核单据");
                            }


                            List<string> DocLineIDList = new List<string>();
                            foreach (ICSPurchaseReceiveDocs Infos in Info.details)
                            {
                                DocLineIDList.Add(Infos.DNDetailID);
                            }
                            CustWCRCVLineApprove.ReturnValue1 result = new CustWCRCVLineApprove.ReturnValue1();
                            result = CustWCRCVLineApprove.CustApproveRcvLineByID(DocLineIDList, OrgID,UserID,UserCode);
                            if (result.IsSuccess == false)
                            {
                                throw new Exception(result.Mes);
                            }


                            chksql = @"select DocNO,BizType,IsLineApprove from PM_Receivement
	                                  where ID='" + DocID + "'";
                            chkdt = DBhlper.Query(chksql, Appconfig.GetU9ConnStr());
                            if (chkdt.Rows.Count != 0)
                            {
                                if (chkdt.Rows[0]["BizType"].ToString() == "326")
                                {
                                    DocNO = chkdt.Rows[0]["DocNO"].ToString();
                                    if (chkdt.Rows[0]["IsLineApprove"].ToString() == "0")
                                    {
                                        #region 整单倒冲
                                        string dcsql = @"select D.ID,C.ID AS DetailID,A.DocNo AS SourceCode
                                                 ,Convert(nvarchar,B.DocLineNo)+'~'+Convert(nvarchar,H.PickLineNo) AS SourceSequence
												 ,D.DocNo AS TransCode,C.LineNum AS TransSequence,C.LineNum
												 ,C.IssuedQtyByWhUOM AS IssuedQty,E.Code AS INVCode,F.Code AS WHCode
                                                 ,B.ID AS SourceDetailID ,ISNULL(G.Code,'') AS LotCode,D.CreatedOn
                                                 ,H.ID AS PickID,I.ID AS OODetailID
                                                 INTO #TEMP from PM_Receivement A
                                                 LEFT JOIN PM_RcvLine B ON B.Receivement=A.ID
                                                 LEFT JOIN PM_IssueDocLine C ON C.SourceDoc_SrcDocLine_EntityID=B.ID
                                                 LEFT JOIN PM_IssueDoc D ON D.ID=C.PMIssueDoc
                                                 LEFT JOIN CBO_ItemMaster E ON E.ID=C.Item
                                                 LEFT JOIN CBO_Wh F ON F.ID=C.Wh
											     LEFT JOIN Lot_LotMaster G ON G.ID=C.LotMaster
												 LEFT JOIN CBO_SCMPickList H ON H.ID=C.POPick
												 LEFT JOIN PM_POLine I ON I.ID=B.SrcDoc_SrcDocLine_EntityID
                                                 WHERE A.DocNo='{0}'
												 AND A.Org='{1}' AND ReverseIssue='1'
                                                 order by C.CreatedOn DESC

												 SELECT * FROM #TEMP
												 WHERE CreatedOn=(SELECT MAX(CreatedOn) FROM #TEMP)

												 DROP TABLE #TEMP";
                                        dcsql = string.Format(dcsql, DocNO, OrgID);
                                        DataTable dcdt = DBhlper.Query(dcsql, Appconfig.GetU9ConnStr());
                                        if (dcdt.Rows.Count > 0)
                                        {

                                            foreach (DataRow dr in dcdt.Rows)
                                            {
                                                ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                DCDataLine.ID = dr["ID"].ToString();
                                                DCDataLine.DetailID = dr["DetailID"].ToString();
                                                DCDataLine.SourceDetailID = dr["SourceDetailID"].ToString();
                                                DCDataLine.SourceCode = dr["SourceCode"].ToString();
                                                DCDataLine.SourceSequence = dr["SourceSequence"].ToString();
                                                DCDataLine.TransCode = dr["TransCode"].ToString();
                                                DCDataLine.TransSequence = dr["TransSequence"].ToString();
                                                DCDataLine.InvCode = dr["INVCode"].ToString();
                                                DCDataLine.WHCode = dr["WHCode"].ToString();
                                                DCDataLine.Quantity = Convert.ToDecimal(dr["IssuedQty"].ToString());
                                                DCDataLine.BatchCode = dr["LotCode"].ToString();
                                                DCDataLine.OODetailID = dr["OODetailID"].ToString();
                                                DCDataLine.PickID = dr["PickID"].ToString();
                                                DCDataLineList.Add(DCDataLine);
                                            }
                                        }
                                        else
                                        {
                                            foreach (var item in Info.details)
                                            {
                                                ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                DCDataLine.ID = "";
                                                DCDataLine.DetailID = "";
                                                DCDataLine.SourceDetailID = "";
                                                DCDataLine.SourceCode = "";
                                                DCDataLine.SourceSequence = "";
                                                DCDataLine.TransCode = "";
                                                DCDataLine.TransSequence = "";
                                                DCDataLine.InvCode = "";
                                                DCDataLine.WHCode = "";
                                                DCDataLine.Quantity = 0;
                                                DCDataLine.BatchCode = "";
                                                DCDataLine.OODetailID = "";
                                                DCDataLine.PickID = "";
                                                DCDataLineList.Add(DCDataLine);
                                            }
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        #region 行审核倒冲
                                        foreach (ICSPurchaseReceiveDocs Infos in Info.details)
                                        {
                                            string dcsql = @"select D.ID,C.ID AS DetailID,A.DocNo AS SourceCode
                                                 ,Convert(nvarchar,B.DocLineNo)+'~'+Convert(nvarchar,H.PickLineNo) AS SourceSequence
												 ,D.DocNo AS TransCode,C.LineNum AS TransSequence,C.LineNum
												 ,C.IssuedQtyByWhUOM AS IssuedQty,E.Code AS INVCode,F.Code AS WHCode
                                                 ,B.ID AS SourceDetailID ,ISNULL(G.Code,'') AS LotCode,D.CreatedOn
                                                 ,H.ID AS PickID,I.ID AS OODetailID
                                                 INTO #TEMP from PM_Receivement A
                                                 LEFT JOIN PM_RcvLine B ON B.Receivement=A.ID
                                                 LEFT JOIN PM_IssueDocLine C ON C.SourceDoc_SrcDocLine_EntityID=B.ID
                                                 LEFT JOIN PM_IssueDoc D ON D.ID=C.PMIssueDoc
                                                 LEFT JOIN CBO_ItemMaster E ON E.ID=C.Item
                                                 LEFT JOIN CBO_Wh F ON F.ID=C.Wh
											     LEFT JOIN Lot_LotMaster G ON G.ID=C.LotMaster
												 LEFT JOIN CBO_SCMPickList H ON H.ID=C.POPick
												 LEFT JOIN PM_POLine I ON I.ID=B.SrcDoc_SrcDocLine_EntityID
                                                 WHERE A.DocNo='{0}' AND B.DocLineNo='{1}'
												 AND A.Org='{2}' AND ReverseIssue='1'
                                                 order by C.CreatedOn DESC

												 SELECT * FROM #TEMP
												 WHERE CreatedOn=(SELECT MAX(CreatedOn) FROM #TEMP)

												 DROP TABLE #TEMP";
                                            dcsql = string.Format(dcsql, DocNO, Infos.DNSequence, OrgID);
                                            DataTable dcdt = DBhlper.Query(dcsql, Appconfig.GetU9ConnStr());
                                            if (dcdt.Rows.Count > 0)
                                            {
                                                foreach (DataRow dr in dcdt.Rows)
                                                {
                                                    ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                    DCDataLine.ID = dr["ID"].ToString();
                                                    DCDataLine.DetailID = dr["DetailID"].ToString();
                                                    DCDataLine.SourceDetailID = dr["SourceDetailID"].ToString();
                                                    DCDataLine.SourceCode = dr["SourceCode"].ToString();
                                                    DCDataLine.SourceSequence = dr["SourceSequence"].ToString();
                                                    DCDataLine.TransCode = dr["TransCode"].ToString();
                                                    DCDataLine.TransSequence = dr["TransSequence"].ToString();
                                                    DCDataLine.InvCode = dr["INVCode"].ToString();
                                                    DCDataLine.WHCode = dr["WHCode"].ToString();
                                                    DCDataLine.Quantity = Convert.ToDecimal(dr["IssuedQty"].ToString());
                                                    DCDataLine.BatchCode = dr["LotCode"].ToString();
                                                    DCDataLine.OODetailID = dr["OODetailID"].ToString();
                                                    DCDataLine.PickID = dr["PickID"].ToString();
                                                    DCDataLineList.Add(DCDataLine);
                                                }
                                            }
                                            else
                                            {
                                                foreach (var item in Info.details)
                                                {
                                                    ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                                    DCDataLine.ID = "";
                                                    DCDataLine.DetailID = "";
                                                    DCDataLine.SourceDetailID = "";
                                                    DCDataLine.SourceCode = "";
                                                    DCDataLine.SourceSequence = "";
                                                    DCDataLine.TransCode = "";
                                                    DCDataLine.TransSequence = "";
                                                    DCDataLine.InvCode = "";
                                                    DCDataLine.WHCode = "";
                                                    DCDataLine.Quantity = 0;
                                                    DCDataLine.BatchCode = "";
                                                    DCDataLine.OODetailID = "";
                                                    DCDataLine.PickID = "";
                                                    DCDataLineList.Add(DCDataLine);
                                                }
                                            }

                                        }
                                        #endregion
                                    }
                                }
                                else
                                {
                                    foreach (var item in Info.details)
                                    {
                                        ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                        DCDataLine.ID = "";
                                        DCDataLine.DetailID = "";
                                        DCDataLine.SourceDetailID = "";
                                        DCDataLine.SourceCode = "";
                                        DCDataLine.SourceSequence = "";
                                        DCDataLine.TransCode = "";
                                        DCDataLine.TransSequence = "";
                                        DCDataLine.InvCode = "";
                                        DCDataLine.WHCode = "";
                                        DCDataLine.Quantity = 0;
                                        DCDataLine.BatchCode = "";
                                        DCDataLine.OODetailID = "";
                                        DCDataLine.PickID = "";
                                        DCDataLineList.Add(DCDataLine);
                                    }
                                }
                            }
                            else
                            {
                                foreach (var item in Info.details)
                                {
                                    ICSOutsourcingReceiveDocssapprove DCDataLine = new ICSOutsourcingReceiveDocssapprove();
                                    DCDataLine.ID = "";
                                    DCDataLine.DetailID = "";
                                    DCDataLine.SourceDetailID = "";
                                    DCDataLine.SourceCode = "";
                                    DCDataLine.SourceSequence = "";
                                    DCDataLine.TransCode = "";
                                    DCDataLine.TransSequence = "";
                                    DCDataLine.InvCode = "";
                                    DCDataLine.WHCode = "";
                                    DCDataLine.Quantity = 0;
                                    DCDataLine.BatchCode = "";
                                    DCDataLine.OODetailID = "";
                                    DCDataLine.PickID = "";
                                    DCDataLineList.Add(DCDataLine);
                                }

                            }

                            var linelist = new List<ICSPurchaseReceiveDocs>();
                            foreach (var item in Info.details)
                            {
                                linelist.Add(new ICSPurchaseReceiveDocs
                                {
                                    DetailID = item.DetailID,
                                    LogIds = item.LogIds,
                                    IsSuccess = true,
                                    Message = "成功",
                                    detailss = DCDataLineList
                                });
                            }

                            datalist.Add(new ICSPurchaseReceiveDoc
                            {
                                ID = Info.ID,
                                RCVTCode = Info.RCVTCode,
                                details = linelist
                            });
                        }
                        catch (Exception ex)
                        {
                            var linelist = new List<ICSPurchaseReceiveDocs>();
                            foreach (var item in Info.details)
                            {
                                linelist.Add(new ICSPurchaseReceiveDocs
                                {
                                    DetailID = item.DetailID,
                                    LogIds = item.LogIds,
                                    IsSuccess = false,
                                    Message = "失败，异常：" + ex.Message
                                });
                            }

                            datalist.Add(new ICSPurchaseReceiveDoc
                            {
                                ID = Info.ID,
                                RCVTCode = Info.RCVTCode,
                                details = linelist
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSPurchaseReceiveDocs>();
                    foreach (var item in Info.details)
                    {
                        linelist.Add(new ICSPurchaseReceiveDocs
                        {
                            DetailID = item.DetailID,
                            LogIds = item.LogIds,
                            IsSuccess = false,
                            Message = "失败，异常：" + ex.Message
                        });
                    }

                    datalist.Add(new ICSPurchaseReceiveDoc
                    {
                        ID = Info.ID,
                        RCVTCode = Info.RCVTCode,
                        details = linelist
                    });
                }

            }

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


            return res;
        }

        public bool Approve(List<ICSSalesShipmentDocNegative> infos)
        {
            bool ResultFlag = false;
            if (infos.Count <= 0)
            {
                throw new Exception("传送数据为空！");
            }
            string res = string.Empty;
            string sql = string.Empty;

            foreach (ICSSalesShipmentDocNegative Info in infos)
            {
                try
                {
                    long DocID = 0;
                    string EntityType = "";
                    //实例化代理类 
                    UFIDAU9PMRcvIRcvApprovedSVClient client = new UFIDAU9PMRcvIRcvApprovedSVClient();
                    //服务返回结果
                    //UFIDAU9PMPOPurchaseOrderData[] returnItems;
                    //返回异常信息，目前还没有使用此属性
                    UFSoft.UBF.Exceptions.MessageBase[] returnMsg;
                    //上下文信息
                    object context;
                    //传入 参数
                    //UFIDAU9PMDTOsOBAPurchaseOrderDTOData[] pOList;
                    UFSoft.UBF.Business.BusinessEntity.EntityKey docHead = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                    string OrgID = "";
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, Info.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        throw new Exception("传入组织编码错误!");
                    }
                    DataTable dt = GetData(Info.SDNRTCode, OrgID);
                    if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()) || !string.IsNullOrEmpty(dt.Rows[0][1].ToString()))
                    {
                        DocID = long.Parse(dt.Rows[0][0].ToString());
                        EntityType = dt.Rows[0][1].ToString();
                    }
                    else
                    {
                        throw new Exception("传入的单据号不正确!");
                    }
                    int acttype = int.Parse(ConfigurationManager.AppSettings["acttype"].ToString());
                    //给上下文信息赋值
                    context = CreateContextObj(OrgID,"","");
                    //给传入参数赋值
                    docHead.EntityType = EntityType;
                    docHead.ID = DocID;

                    //pOList = SetPoDtos(U9Info, poInfoList);
                    //服务调用
                    (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                    (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;

                    returnMsg = client.Do(context, acttype, docHead);
                    if (returnMsg != null)
                    {
                        if (!string.IsNullOrWhiteSpace(returnMsg[0].localMessage))
                        {
                            throw new Exception(returnMsg[0].localMessage);
                        }
                    }
                    #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 PM_Receivement set ApprovedBy='{0}',ModifiedBy='{0}'
                            where ID='{1}'
                            update PM_RcvLine set ModifiedBy='{0}'
                            where Receivement='{1}'";
                        usersql = string.Format(usersql, userdt.Rows[0]["Name"].ToString(), DocID);
                        DBhlper.Query(usersql, Appconfig.GetU9ConnStr());
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    throw new Exception(ex.Message);
                }
            }
            ResultFlag = true;
            return ResultFlag;
        }

        public Result ActionCreateRMAToRCV(List<ICSSalesShipmentDocNegative> infos)
        {
            Result rtninfo = new Result();
            var datalist = new List<ICSSalesShipmentDocNegative>();
            foreach (var info in infos)
            {
                try
                {
                    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("传入组织编码错误!");
                    }


                    var UserCode = "";

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



                    List<CreateRMAToRCVAPIModel> HeadList = new List<CreateRMAToRCVAPIModel>();
                    CreateRMAToRCVAPIModel HeadInfo = new CreateRMAToRCVAPIModel();
                    List<LineData> BodyList = new List<LineData>();
                    LineData BodyInfo = new LineData();

                    HeadInfo = new CreateRMAToRCVAPIModel();
                    HeadInfo.DocStatus = 2;
                    foreach (ICSSalesShipmentDocNegatives line in info.details)
                    {
                        //根据传入行ID查询单据行信息
                        string linesql = @"select ID,DocLineNo from SM_RMALine
                                           where ID='{0}'";
                        linesql = string.Format(linesql, line.SDNRTDetailID);
                        DataTable linedt = DBhlper.Query(linesql, connString);
                        if (linedt.Rows.Count == 0)
                        {
                            throw new Exception("传入退回处理单行的ID:" + line.SDNRTDetailID + "无法在U9查询到相关信息!");
                        }

                        BodyInfo = new LineData();
                        BodyInfo.BusinessDate = DateTime.Now.ToString();
                        BodyInfo.SrcDocType = 8;
                        BodyInfo.TransQty = new TransQty();
                        BodyInfo.TransQty.Amount1 = line.Quantity;
                        BodyInfo.TransQty.Amount2 = 0;
                        BodyInfo.SrcLineID = long.Parse(line.SDNRTDetailID);
                        BodyInfo.SrcDocNo = info.SDNRTCode;
                        BodyInfo.SrcDocLineNo = linedt.Rows[0]["DocLineNo"].ToString();
                        BodyInfo.DescFlexField = new DescFlexField();
                        BodyInfo.DescFlexField.PrivateDescSeg30 = line.LogIds;
                        BodyInfo.InvLotCode = line.BatchCode;

                        BodyList.Add(BodyInfo);

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

                    string postJson = JsonConvert.SerializeObject(HeadList);
                    APIreturnInfo value = new APIreturnInfo();
                    value = PostJsonToRMAToRCV(postJson, UserCode, info.WorkPoint);
                    if (value.IsSuccess == true)
                    {
                        string sql = @"select a.ID,a.DocNo,b.DocLineNo,b.ID LineID,c.Code,b.ArriveQtyPU, 
                                        b.DescFlexSegments_PrivateDescSeg30,b.SrcDoc_SrcDocLine_EntityID
                                        from PM_Receivement a
                                        left join PM_RcvLine b on a.id = b.Receivement
										left join CBO_ItemMaster c on b.ItemInfo_ItemID = c.ID
                                        where a.DocNo ='" + value.DocNo + "' and a.Org =" + OrgID;
                        DataTable dt = DBhlper.Query(sql, connString);
                        if (dt.Rows.Count > 0)
                        {
                            var linelist = new List<ICSSalesShipmentDocNegatives>();
                            foreach (DataRow dr in dt.Rows)
                            {
                                linelist.Add(new ICSSalesShipmentDocNegatives
                                {
                                    DetailID = dr["LineID"].ToString(),
                                    Sequence = dr["DocLineNo"].ToString(),
                                    InvCode = dr["Code"].ToString(),
                                    Quantity = decimal.Parse(dr["ArriveQtyPU"].ToString()),
                                    SDNRTDetailID = dr["SrcDoc_SrcDocLine_EntityID"].ToString(),
                                    LogIds = dr["DescFlexSegments_PrivateDescSeg30"].ToString()
                                });
                            }


                            datalist.Add(new ICSSalesShipmentDocNegative
                            {
                                ID = dt.Rows[0]["ID"].ToString(),
                                SDNNEGCode = dt.Rows[0]["DocNo"].ToString(),
                                IsSuccess = true,
                                Message = "成功",
                                details = linelist
                            });
                        }
                        else
                        {
                            throw new Exception("U9标准服务返回的单号未查询到相关单据信息");
                        }
                    }
                    else
                    {
                        throw new Exception(value.Message);
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSSalesShipmentDocNegatives>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSSalesShipmentDocNegatives
                        {
                            SDNRTDetailID = item.SDNRTDetailID,
                            LogIds = item.LogIds
                        });
                    }

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

            rtninfo.Success = true;
            rtninfo.Message = "成功";
            rtninfo.Data = datalist;

            return rtninfo;
        }
        public rtnRMAToRCVInfo ActionCreateRMRToRCV(List<ICSSalesShipmentDocNegative> infos)
        {
            rtnRMAToRCVInfo rtninfo = new rtnRMAToRCVInfo();
            try
            {
                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("传入组织编码错误!");
                }
                List<CreateRMAToRCVAPIModel> HeadList = new List<CreateRMAToRCVAPIModel>();
                CreateRMAToRCVAPIModel HeadInfo = new CreateRMAToRCVAPIModel();
                List<LineData> BodyList = new List<LineData>();
                LineData BodyInfo = new LineData();
                foreach (ICSSalesShipmentDocNegative Info in infos)
                {
                    HeadInfo = new CreateRMAToRCVAPIModel();
                    HeadInfo.DocStatus = 2;
                    foreach (ICSSalesShipmentDocNegatives line in Info.details)
                    {
                        //根据传入行ID查询单据行信息
                        string linesql = @"select ID,DocLineNo from SM_RMRLine
                                           where ID='{0}'";
                        linesql = string.Format(linesql, line.SDNRTDetailID);
                        DataTable linedt = DBhlper.Query(linesql, connString);
                        if (linedt.Rows.Count == 0)
                        {
                            throw new Exception("传入退回申请单子行的ID:" + line.SDNRTDetailID + "无法在U9查询到相关信息!");
                        }
                        else
                        {
                            BodyInfo = new LineData();
                            BodyInfo.BusinessDate = DateTime.Now.ToString();
                            BodyInfo.SrcDocType = 4;
                            BodyInfo.TransQty = new TransQty();
                            BodyInfo.TransQty.Amount1 = line.Quantity;
                            BodyInfo.TransQty.Amount2 = 0;
                            BodyInfo.SrcLineID = long.Parse(line.SDNRTDetailID);
                            BodyInfo.SrcDocNo = Info.SDNRTCode;
                            BodyInfo.SrcDocLineNo = linedt.Rows[0]["DocLineNo"].ToString();
                            BodyList.Add(BodyInfo);
                        }
                    }
                    HeadInfo.sMToRcvDTOs = BodyList;
                    HeadList.Add(HeadInfo);
                }
                string postJson = JsonConvert.SerializeObject(HeadList);
                APIreturnInfo value = new APIreturnInfo();
                value = PostJsonToRMAToRCV(postJson, infos[0].User, infos[0].WorkPoint);
                if (value.IsSuccess == true)
                {
                    DataSet ds = new DataSet();
                    rtninfo.DocNo = value.DocNo;
                    rtninfo.IsSuccess = true;
                    #region 查询
                    string rtnsql = @"  
                            select DISTINCT a.ID as ID,a.ID as IDs,'' as SourceCode ,
                            a.DocNo as IssueCode,'' AS cDepCode,'' as cDepName,'' WHCode,'' WHName,
                            a.SrcDocType as SourceType,a.CreatedBy as CreateUser,a.CreatedOn as CreateDateTime,
                            a.ApprovedBy as Checker,a.ApprovedOn as CheckDateTime
                            from PM_Receivement a
                            WHERE a.DocNo='{0}' and a.Org='{1}'";
                    rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                    DataTable mdt = DBhlper.Query(rtnsql, connString);
                    ds.Tables.Add(mdt);
                    rtnsql = @" select DISTINCT a.ID as IDs,b.ID as DetailID,b.DocLineNo as Sequence,c.Code as InvCode 
                                ,b.RcvQtyCU as Quantity,b.SrcDoc_SrcDocLine_EntityID as SourceDetailID,0 as Amount
                                ,d.Code as cDepCode,dd.Name as cDepName,e.Code as WHCode,ee.Name as WHName
                                ,isnull(f.Code,'') ProjectCode,isnull(g.LotCode,'') cBatch,'' version ,'' brand,
                                '' as cFree1,
                                '' as cFree2,
                                '' as cFree3,
                                '' as cFree4,
                                '' as cFree5,
                                '' as cFree6,
                                '' as cFree7,
                                '' as cFree8,
                                '' as cFree9,
                                '' as cFree10
                                from PM_Receivement a
                                left join PM_RcvLine b on b.Receivement=a.ID
                                left join CBO_ItemMaster c on c.ID=b.ItemInfo_ItemID
                                left join CBO_Department d on d.ID=b.RcvDept
                                left join CBO_Department_Trl dd on dd.ID=d.ID
                                left join CBO_Wh e on e.ID=b.Wh
                                left join CBO_Wh_Trl ee on ee.ID=e.ID
                                left join CBO_Project f on f.ID=b.Project
                                left join Lot_LotMaster g on g.ID=b.RcvLot
                                WHERE a.DocNo='{0}' and a.Org='{1}'";
                    rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                    DataTable sdt = DBhlper.Query(rtnsql, connString);
                    ds.Tables.Add(sdt);
                    #endregion
                    rtninfo.Data = JSON.DataSetToJson(ds, "details", "IDs");
                }
                else
                {
                    throw new Exception(value.Message);
                }
                return rtninfo;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
        }

        public static APIreturnInfo PostJsonToRMAToRCV(string DataJson, string CreateByCode, string ORGCode)
        {
            APIreturnInfo valueRet = new APIreturnInfo();
            try
            {


                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/Receivement/CreateSaleRcvBySrc";
                    CreateUrl = string.Format(CreateUrl, U9IP);

                    DBHelper.WriteLogFile("调用API传入参数：" + DataJson, "销售退货-销售退货单");

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

                    DBHelper.WriteLogFile("调用API返回参数：" + resultCreateSoFile, "销售退货-销售退货单");

                    JObject objuu = JObject.Parse(resultCreateSoFile);
                    bool IsSucess = false;
                    string DocNo = "";
                    long ID = -1;
                    string Message = "";
                    if (objuu["Success"] != null && objuu["Data"] != null && objuu["Success"].ToString().ToUpper() == "TRUE")
                    {
                        CreateRMAToRCVReturnModel RetModel = JsonConvert.DeserializeObject<CreateRMAToRCVReturnModel>(resultCreateSoFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.IsSucess == false);
                            if (IsTrues != null && IsTrues.Count() > 0)
                            {

                                Message += RetModel.Data[0].ErrorMsg;
                            }
                            else
                            {

                                DocNo = RetModel.Data[0].Code;
                                if (!string.IsNullOrEmpty(RetModel.Data[0].ID))
                                {
                                    ID = long.Parse(RetModel.Data[0].ID);
                                }
                                else
                                {
                                    ID = GetDocID(DocNo, ORGCode);
                                }
                                IsSucess = true;
                                Message += "销售退回收货单：" + DocNo + "创建成功。";
                            }
                        }
                        else
                        {
                            Message += RetModel.ResMsg; ;
                        }
                    }
                    else
                    {
                        IsSucess = false;
                        string ErrorMessage = "";
                        if (objuu["Message"] != null && !string.IsNullOrEmpty(objuu["Message"].ToString()))
                        {
                            ErrorMessage += objuu["Message"].ToString();
                        }
                        if (objuu["ResMsg"] != null && !string.IsNullOrEmpty(objuu["ResMsg"].ToString()))
                        {
                            ErrorMessage += objuu["ResMsg"].ToString();
                        }
                        throw new Exception("调用OpenAPI创建销售退回收货单失败." + ErrorMessage);

                    }

                    valueRet.IsSuccess = IsSucess;
                    valueRet.DocNo = DocNo;
                    valueRet.Message = Message;
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                valueRet.IsSuccess = false;
                valueRet.DocNo = "";
                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 long GetDocID(string DocNO, string OrgCode)
        {
            try
            {
                long ID = 0;
                string sqsql = @"select A.ID from SM_RMA 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);
            }
        }

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


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

            return thContext;
        }
        #endregion

        #region 返回信息类
        public class rtnRcvInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
            public List<ICSOutsourcingReceiveDocss> detailss { get; set; }
        }

        public class ICSOutsourcingReceiveDocss
        {
            public string ID { get; set; }
            public string DetailID { get; set; }
            public string SourceDetailID { get; set; }
            public string SourceCode { get; set; }
            public string SourceSequence { get; set; }
            public string TransCode { get; set; }
            public string TransSequence { get; set; }
            public string InvCode { get; set; }
            public decimal Quantity { get; set; }
            public decimal Amount { get; set; }
            public string Currency { get; set; }
            public decimal UnitPrice { get; set; }
            public string ODNDetailID { get; set; }
            public string OOID { get; set; }
            public string OODetailID { get; set; }
            public string PickID { get; set; }
            public string WHCode { get; set; }
            public string ProjectCode = string.Empty;//项目号
            public string Version = string.Empty;//版本
            public string Brand = string.Empty;//厂牌
            public string BatchCode = string.Empty;//批次号
            public string cFree1 = string.Empty;//自由项1
            public string cFree2 = string.Empty;//自由项2
            public string cFree3 = string.Empty;//自由项3
            public string cFree4 = string.Empty;//自由项4
            public string cFree5 = string.Empty;//自由项5
            public string cFree6 = string.Empty;//自由项6
            public string cFree7 = string.Empty;//自由项7
            public string cFree8 = string.Empty;//自由项8
            public string cFree9 = string.Empty;//自由项9
            public string cFree10 = string.Empty;//自由项10

        }
        #endregion

        private static DataTable GetData(string DocCode, string OrgID)
        {
            string sql = @" select  A.ID,A1.[Code] as [Receivement_RcvDocType_Code],A.Status
                            ,CASE WHEN A.ReceivementType=0 THEN SUM(A3.ArriveQtyCU) ELSE SUM(A3.RejectQtyTU) END AS RcvQtyCU
                            from  PM_Receivement as A  
                            left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
                            left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
							left join [PM_RcvLine] A3 ON A3.Receivement=A.ID
                            where A.DocNo='" + DocCode + "' AND A.Org='" + OrgID + @"'
                            GROUP BY A.ID,A1.[Code],A.Status,A.ReceivementType";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }

        private static DataTable GetRCVData(string DocID, string OrgID)
        {
            string sql = @" select  A.ID,A.DocNo AS DocNO,A1.[Code] as [Receivement_RcvDocType_Code],A.Status
                            from  PM_Receivement as A  
                            left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
                            left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
							left join [PM_RcvLine] A3 ON A3.Receivement=A.ID
                            where A.ID='" + DocID + "' AND A.Org='" + OrgID + @"'
                            GROUP BY A.ID,A.DocNo,A1.[Code],A.Status,A.ReceivementType";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }
        private static DataTable GetRCVDataByIdOrCode(string DocID, string DocNo, string OrgID)
        {
            string sql = @" select  A.ID,A.DocNo AS DocNO,A1.[Code] as [Receivement_RcvDocType_Code],A.Status
                            from  PM_Receivement as A  
                            left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
                            left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
							left join [PM_RcvLine] A3 ON A3.Receivement=A.ID
                            where A.ID='" + DocID + "' AND A.Org='" + OrgID + @"'
                            GROUP BY A.ID,A.DocNo,A1.[Code],A.Status,A.ReceivementType
							UNION ALL
							select  A.ID,A.DocNo AS DocNO,A1.[Code] as [Receivement_RcvDocType_Code],A.Status
                            from  PM_Receivement as A  
                            left join [PM_RcvDocType] as A1 on (A.[RcvDocType] = A1.[ID])  
                            left join [PM_RcvDocType_Trl] as A2 on (A2.SysMlFlag = 'zh-CN') and (A1.[ID] = A2.[ID])
							left join [PM_RcvLine] A3 ON A3.Receivement=A.ID
                            where A.DocNo='" + DocNo + "' AND A.Org='" + OrgID + @"'
                            GROUP BY A.ID,A.DocNo,A1.[Code],A.Status,A.ReceivementType";
            return DBhlper.Query(sql, Appconfig.GetU9ConnStr());
        }
        public string CheckERPRcvOrRtn(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 PM_Receivement
                                  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);
            }
        }
        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 clsql = @"select ID from SM_RMA
                                  where DocNo='{0}' and Org='{1}'";
                clsql = string.Format(clsql, DocNO, OrgID);
                DataTable cldt = DBhlper.Query(clsql, connString);
                string sqsql = @"select ID from SM_RMRHead
                                 where DocNo='{0}' and Org='{1}'";
                sqsql = string.Format(sqsql, DocNO, OrgID);
                DataTable sqdt = DBhlper.Query(sqsql, connString);
                if (cldt.Rows.Count != 0)
                {
                    str = "退回处理单";
                }
                else if (sqdt.Rows.Count != 0)
                {
                    str = "退回申请单";
                }
                else
                {
                    str = "入库单";
                }
                return str;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

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

        public class APIreturnInfo
        {
            public string DocNo { get; set; }
            public bool IsSuccess { get; set; }
            public string Message { get; set; }
        }
    }
}
