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 ICS.WCF.Base;
using ICSSoft.Entity;
using UFIDA.ISV.BFRCVApprove;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using ICSSoft.DataProject;
using ICSSoft.Common;

namespace ICS.CreateRtnTORcv
{
    public class CreateRtnToRCV
    {

        //private static string ORGCode = ConfigurationManager.AppSettings["orgCode"].ToString();
        private static string ERPConStr = Appconfig.GetU9ConnStr();
        private static string UserCode = ConfigurationManager.AppSettings["userCode"].ToString();
        private static string LogName = "创建U9退货单";
        //该接口有问题，修改成调U9API接口 Modify On 20240604
        public RtnToRcvReturnValue CustCreateRtnToRcvold20240605(List<ICSPurchaseReceiveDoc> Data, string DocType)
        {
            #region 服务调用框架结构
            //实例化代理类 UFIDAU9ISVItemIBatchCreateItemByDTOSRVClient 
            UFIDAU9PMRtnIRTNToRtnRcvSVClient client = new UFIDAU9PMRtnIRTNToRtnRcvSVClient();
            //服务返回结果

            //UFIDAU9ISVPRSVPRBizKeyDTOData[] returnItems;
            UFSoft.UBF.Exceptions.MessageBase[] returnItems;
            //返回异常信息，目前还没有使用此属性
            //UFSoft.UBF.Exceptions1.MessageBase[] returnMsg;
            //上下文信息
            object context;
            //传入 参数

            string[] splitBy = new string[] { };

            try
            {
                if (Data == null || Data.Count == 0)
                {
                    throw new Exception("传入数据为空");
                }

                string ORGID = "";
                string ORGCode = Data[0].WorkPoint;

                ORGID = Appconfig.IsExistsCode(ORGCode, "Base_Organization");

                if (string.IsNullOrEmpty(ORGID))
                {
                    throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                }
                UFIDAU9PMPubRcvDocTypeData docTypeInfo = new UFIDAU9PMPubRcvDocTypeData();
                long rcvtype = 0L;
                string DocTypeCode = "";
                //private static string DocTypeCode = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                if (DocType == "采购")
                {
                    if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["PORtnDocType"].ToString(), ORGID)))
                    {
                        DocTypeCode = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                        docTypeInfo.m_iD = Convert.ToInt64(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["PORtnDocType"].ToString(), ORGID));
                        docTypeInfo.Org = long.Parse(ORGID);
                    }
                    else
                    {
                        throw new Exception("单据类型不存在");
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["WWPORtnDocType"].ToString(), ORGID)))
                    {
                        DocTypeCode = ConfigurationManager.AppSettings["WWPORtnDocType"].ToString();
                        docTypeInfo.m_iD = Convert.ToInt64(Appconfig.GetRCVDocType(ConfigurationManager.AppSettings["PORtnDocType"].ToString(), ORGID));
                        docTypeInfo.Org = long.Parse(ORGID);
                    }
                    else
                    {
                        throw new Exception("单据类型不存在");
                    }
                }
                List<UFSoft.UBF.Business.BusinessEntity.EntityKey> entityKeys = new List<UFSoft.UBF.Business.BusinessEntity.EntityKey>();
                foreach (ICSPurchaseReceiveDoc head in Data)
                {
                    foreach (ICSPurchaseReceiveDocs line in head.details)
                    {
                        UFSoft.UBF.Business.BusinessEntity.EntityKey entity = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                        entity.ID = long.Parse(line.DNRTDetailID);
                        entityKeys.Add(entity);
                    }
                }
                //给上下文信息赋值
                context = CreateContextObj();

                //给传入参数赋值



                UFIDAU9PMDTOsRtnToRcvDTOData[] itemDatas = setDataForItem(Data, ORGID, ORGCode);

                StringBuilder beginstrlog = new StringBuilder();
                beginstrlog.AppendLine("参数获取完毕");
                Appconfig.WriteLogFile(beginstrlog.ToString(), "创建U9退货单");

                //服务调用
                string[] splitBy1 = null;
                (client.Endpoint.Binding as BasicHttpBinding).MaxReceivedMessageSize = int.MaxValue;
                (client.Endpoint.Binding as BasicHttpBinding).MaxBufferSize = int.MaxValue;
                UFIDAU9PMRtnRcvFromRTNData data = client.Do(context, entityKeys.ToArray(), splitBy, docTypeInfo, itemDatas, out returnItems);

                StringBuilder str = new StringBuilder();

                RtnToRcvReturnValue value = new RtnToRcvReturnValue();

                List<Data> values = new List<Data>();
                int msgnumber = 0;
                List<string> docno = new List<string>();

                //docno.Add(data.m_rcvDocNos[0].ToString());
                //if (string.IsNullOrEmpty(data.m_rcvDocNos[0].ToString()))
                //{
                //    value.IsSuccess = false;
                //    value.Message = "退货单创建失败";
                //}
                //else
                //{
                //    value.DocNo = data.m_rcvDocNos[0].ToString();
                //    value.IsSuccess = true;
                //    value.Message = "退货单创建成功";
                //}

                //foreach (string item in docno)
                //{
                //    UFIDA.ISV.BFRCVApprove.CustBFRCVApprove.ReturnValue1 TJ = CustBFRCVApprove.CustApproveRec(item, ORGCode, "审核");
                //    if (!TJ.IsSuccess)
                //        throw new Exception("单据：" + item + "审核错误，错误提示：" + TJ.Mes + "！");
                //}
                Data _data = new Data();
                List<DataLine> list = new List<DataLine>();
                //     string Selsql = @"SELECT a.ID,d.Code AS DeptCode,e.Name AS DeptName,a.DocNo,g.DocNo AS POCode,c.Code cWHCode,cc.Name cWHName,a.Supplier_Supplier,a.Org
                //               ,a.CreatedBy,a.CreatedOn,b.id DetailID,b.DocLineNo Sequence,b.ItemInfo_ItemCode InvCode
                //                                 ,b.ArriveQtyTU AS Quantity,0 AS Amount,b.ArriveQtyTU as RCVQuantity,g.ID as POLineID,
                //               b.RcvLotCode AS cBatch,
                //                                 '' cFree1,'' cFree2,'' cFree3,
                //                                 '' cFree4,'' cFree5,'' cFree6,
                //                                 '' cFree7,'' cFree8,'' cFree9,
                //                                 '' cFree10
                //                                   FROM PM_Receivement a
                //                                 LEFT JOIN PM_RcvLine b ON b.Receivement=a.ID
                //                                 LEFT JOIN CBO_Wh c ON b.Wh=c.ID
                //                                 LEFT JOIN CBO_Wh_Trl cc ON c.ID=cc.ID
                //               LEFT JOIN CBO_Department d on d.ID=b.RcvDept and d.Org=a.Org
                //               LEFT JOIN CBO_Department_Trl e on e.ID=d.ID
                //LEFT JOIN PM_RcvLine h on h.ID=b.SrcDoc_SrcDocLine_EntityID
                //               LEFT JOIN PM_POLine f on f.ID=h.SrcDoc_SrcDocLine_EntityID
                //               LEFT JOIN PM_PurchaseOrder g on g.ID=f.PurchaseOrder
                //                                 WHERE a.DocNO='" + data.m_rcvDocNos[0].ToString() + "' AND a.Org='" + ORGID + "'";
                //     DataTable Seldt = DBhlper.Query(Selsql, Appconfig.GetU9ConnStr());
                //     if (Seldt != null && Seldt.Rows.Count > 0)
                //     {
                //         foreach (DataRow item in Seldt.Rows)
                //         {
                //             string Supplier_Supplier = item["Supplier_Supplier"].ToString();
                //             string Org = item["Org"].ToString();

                //             DataLine _DataLine = new DataLine();
                //             _data.ID = item["ID"].ToString();
                //             _data.DNCode = item["DocNo"].ToString();
                //             _data.cDepCode = item["DeptCode"].ToString();
                //             _data.cDepName = item["DeptName"].ToString();
                //             _data.POCode = item["POCode"].ToString();
                //             _data.CreateUser = item["CreatedBy"].ToString();
                //             _data.CreateDateTime = Convert.ToDateTime(item["CreatedOn"].ToString());
                //             _DataLine.DetailID = item["DetailID"].ToString();
                //             _DataLine.Sequence = Int32.Parse(item["Sequence"].ToString());
                //             _DataLine.Quantity = Decimal.Parse(item["Quantity"].ToString());
                //             _DataLine.InvCode = item["InvCode"].ToString();
                //             _DataLine.PODetailID = item["POLineID"].ToString();
                //             _DataLine.cBatch = item["cBatch"].ToString();
                //             _DataLine.cFree1 = item["cFree1"].ToString();
                //             _DataLine.cFree2 = item["cFree2"].ToString();
                //             _DataLine.cFree3 = item["cFree3"].ToString();
                //             _DataLine.cFree4 = item["cFree4"].ToString();
                //             _DataLine.cFree5 = item["cFree5"].ToString();
                //             _DataLine.cFree6 = item["cFree6"].ToString();
                //             _DataLine.cFree7 = item["cFree7"].ToString();
                //             _DataLine.cFree8 = item["cFree8"].ToString();
                //             _DataLine.cFree9 = item["cFree9"].ToString();
                //             _DataLine.cFree10 = item["cFree10"].ToString();
                //             list.Add(_DataLine);
                //         }
                //         _data.details = list;
                //         value.Data = _data;
                //     }
                Appconfig.WriteLogFile("成功", "创建U9退货单");
                return value;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                string HeadList = string.Empty;

                //string message=    GetExceptionMessage(ex);
                StringBuilder str = new StringBuilder();
                foreach (ICSPurchaseReceiveDoc data in Data)
                {
                    str.AppendLine("创建U9退货单");
                    str.AppendLine(ex.ToString());
                    HeadList += "\r\n 退货申请单号：" + data.DNRTCode;
                }
                str.AppendLine(HeadList);
                str.AppendLine("结果:" + "False");


                Appconfig.WriteLogFile(str.ToString(), "创建U9退货单");

                RtnToRcvReturnValue value = new RtnToRcvReturnValue();
                value.IsSuccess = false;
                value.Message = GetExceptionMessage(ex);
                return value;
            }
            #endregion
        }



        public Result CustCreateRtnToRcv(List<ICSPurchaseReceiveDoc> Data, string DocType)
        {
            var res = new Result();

            var datalist = new List<ICSPurchaseReceiveDoc>();

            foreach (ICSPurchaseReceiveDoc Doc in Data)
            {
                try
                {
                    string ORGID = "";
                    string ORGCode = Doc.WorkPoint;

                    ORGID = Appconfig.IsExistsCode(ORGCode, "Base_Organization");

                    if (string.IsNullOrEmpty(ORGID))
                    {
                        throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                    }
                    UFIDAU9PMPubRcvDocTypeData docTypeInfo = new UFIDAU9PMPubRcvDocTypeData();
                    long rcvtype = 0L;
                    string DocTypeCode = "";
                    string PORtnDocType = "";
                    if (ConfigurationManager.AppSettings["PORtnDocType"] != null)
                    {
                        PORtnDocType = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                    }
                    else
                    {
                        throw new Exception("采购退货单据类型未维护。");
                    }

                    string WWPORtnDocType = "";
                    if (ConfigurationManager.AppSettings["WWPORtnDocType"] != null)
                    {
                        WWPORtnDocType = ConfigurationManager.AppSettings["WWPORtnDocType"].ToString();
                    }
                    else
                    {
                        throw new Exception("委外采购退货单据类型未维护。");
                    }

                    if (DocType == "采购")
                    {
                        if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(PORtnDocType, ORGID)))
                        {
                            DocTypeCode = PORtnDocType;
                            docTypeInfo.m_iD = Convert.ToInt64(Appconfig.GetRCVDocType(PORtnDocType, ORGID));
                            docTypeInfo.Org = long.Parse(ORGID);
                        }
                        else
                        {
                            throw new Exception("单据类型不存在");
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(WWPORtnDocType, ORGID)))
                        {
                            DocTypeCode = WWPORtnDocType;
                            docTypeInfo.m_iD = Convert.ToInt64(Appconfig.GetRCVDocType(WWPORtnDocType, ORGID));
                            docTypeInfo.Org = long.Parse(ORGID);
                        }
                        else
                        {
                            throw new Exception("单据类型不存在");
                        }
                    }


                    var UserCode = "";

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


                    List<string> lineList = new List<string>();



                    foreach (ICSPurchaseReceiveDocs linedr in Doc.details)
                    {
                        lineList.Add(linedr.DNRTDetailID);
                    }



                    string sql2 = @"   select  ss.code SupplierCode,cast(ll.id as varchar(200)) id ,
                        cast( ll.RtnLineNO as varchar(200)) RtnLineNO,hh.docno,
                        ll.RtnOrderQtyRU TuiBuQty,ll.RtnARQtyRU TuiKouQty
                        from  pm_rtn hh
                inner join PM_RtnLine ll on ll.rtn=hh.id
                left join CBO_Supplier ss on ss.id=hh.RtnToSupplier_supplier
                where ll.id in ('" + string.Join("','", lineList.ToArray()) + @"')  ";
                    DataTable dt2 = DBhlper.Query(sql2, ERPConStr);
                    if (dt2.Rows.Count == 0)
                    {
                        throw new Exception("未查到相关退货信息");
                    }


                    DataTable disData = dt2.DefaultView.ToTable(true, new string[] { "SupplierCode" });
                    if (disData.Rows.Count > 1)
                    {
                        throw new Exception("只能同时创建相同供应商的退货数据");
                    }
                    string VenCode = disData.Rows[0]["SupplierCode"].ToString();

                    CreateRtnWebApiModel Model = new CreateRtnWebApiModel(); ;
                    Model.ConfirmDate = DateTime.Now; ;
                    Model.srcDocType = 6;//来源类型 5 收货单； 6 采购退货申请单
                    Model.itemType = 0;//Product 不针对原工序 0 WorkingProcedure 针对原工序 1
                    Model.Memo = "";
                    Model.OtherID = "";//第三方数据唯一性标识，此字段需要返回
                                       // Model.rcvDocTypeCode = "";//暂不支持传入，所以不传就行
                    Model.rcvDocTypeID = docTypeInfo.m_iD;//单据类型（暂不支持传入）
                    Model.splitTerm = new List<string>();








                    List<CreateRtnWebApiModel> ModelList = new List<CreateRtnWebApiModel>();

                    List<TransformDTOsItem> transformDTOs = new List<TransformDTOsItem>();
                    foreach (ICSPurchaseReceiveDocs linedr in Doc.details)
                    {
                        #region 获取传入仓库ID
                        long WHID = 0;
                        string whsql = @"select ID from CBO_Wh
                                         where Code='{0}' and Org='{1}'";
                        whsql = string.Format(whsql, linedr.WHCode, ORGID);
                        DataTable whdt = DBhlper.Query(whsql, ERPConStr);
                        if (whdt.Rows.Count == 0)
                        {
                            throw new Exception("传入仓库编码:" + linedr.WHCode + "不存在,请确认!");
                        }
                        else
                        {
                            WHID = long.Parse(whdt.Rows[0]["ID"].ToString());
                        }
                        #endregion
                        TransformDTOsItem dto = new TransformDTOsItem();

                        dto.DescFlexSegments = new DescFlexSegments();
                        dto.Memo = "";
                        dto.RcvBusinessDate = DateTime.Now;
                        dto.RejectQty = new RejectQty();
                        dto.RejectQty.Amount1 = linedr.Quantity;
                        dto.RejectQty.Amount2 = 0;

                        DataRow[] drs = dt2.Select("id='" + linedr.DNRTDetailID + "'");
                        if (drs == null || drs.Count() == 0)
                        {
                            throw new Exception("未查到相关退货信息,行ID=" + linedr.DNRTDetailID);
                        }
                        dto.RtnBinCode = "";


                        if (!string.IsNullOrEmpty(drs[0]["TuiBuQty"].ToString()) && Convert.ToDecimal(drs[0]["TuiBuQty"].ToString()) != 0)
                        {
                            dto.RtnDeductQty = new RtnDeductQty();
                            dto.RtnDeductQty.Amount1 = 0;
                            dto.RtnDeductQty.Amount2 = 0;
                            dto.RtnFillQty = new RtnFillQty();
                            dto.RtnFillQty.Amount1 = linedr.Quantity;
                            dto.RtnFillQty.Amount2 = 0;
                        }
                        else
                        {
                            dto.RtnDeductQty = new RtnDeductQty();
                            dto.RtnDeductQty.Amount1 = linedr.Quantity;
                            dto.RtnDeductQty.Amount2 = 0;
                            dto.RtnFillQty = new RtnFillQty();
                            dto.RtnFillQty.Amount1 = 0;
                            dto.RtnFillQty.Amount2 = 0;
                        }
                        dto.RtnWh = WHID;
                        dto.InvLotCode = linedr.BatchCode;

                        dto.SrcRcvDocLineNo = Convert.ToInt32(drs[0]["RtnLineNO"].ToString());

                        dto.SrcRcvDocNo = drs[0]["docno"].ToString();

                        dto.DescFlexSegments.PrivateDescSeg30 = linedr.LogIds;


                        transformDTOs.Add(dto);
                    }
                    Model.transformDTOs = transformDTOs;
                    ModelList.Add(Model);
                    string postJson = JsonConvert.SerializeObject(ModelList);

                    PostJsonToRCV(postJson, UserCode, ORGCode, Doc, datalist);
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSPurchaseReceiveDocs>();
                    foreach (var item in Doc.details)
                    {
                        linelist.Add(new ICSPurchaseReceiveDocs
                        {
                            DNRTDetailID = item.DNRTDetailID,
                            LogIds = item.LogIds
                        });
                    }


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

            }

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

            return res;
        }


        public string CustOutCreateRtnToRcv(List<ICSOutsourcingReceiveDocNegative> Bills)
        {
            #region 服务调用框架结构


            try
            {
                string DocType = "委外";
                if (Bills == null || Bills.Count == 0)
                {
                    throw new Exception("传入数据为空");
                }

                string ORGID = "";
                string ORGCode = Bills[0].WorkPoint;

                ORGID = Appconfig.IsExistsCode(ORGCode, "Base_Organization");

                if (string.IsNullOrEmpty(ORGID))
                {
                    throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                }
                UFIDAU9PMPubRcvDocTypeData docTypeInfo = new UFIDAU9PMPubRcvDocTypeData();
                long rcvtype = 0L;
                string DocTypeCode = "";
                string PORtnDocType = "";
                if (ConfigurationManager.AppSettings["PORtnDocType"] != null)
                {
                    PORtnDocType = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                }
                else
                {
                    throw new Exception("采购退货单据类型未维护。");
                }

                string WWPORtnDocType = "";
                if (ConfigurationManager.AppSettings["WWPORtnDocType"] != null)
                {
                    WWPORtnDocType = ConfigurationManager.AppSettings["WWPORtnDocType"].ToString();
                }
                else
                {
                    throw new Exception("委外采购退货单据类型未维护。");
                }
                //private static string DocTypeCode = ConfigurationManager.AppSettings["PORtnDocType"].ToString();
                if (DocType == "采购")
                {
                    if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(PORtnDocType, ORGID)))
                    {
                        DocTypeCode = PORtnDocType;
                        docTypeInfo.m_iD = Convert.ToInt64(Appconfig.GetRCVDocType(PORtnDocType, ORGID));
                        docTypeInfo.Org = long.Parse(ORGID);
                    }
                    else
                    {
                        throw new Exception("单据类型不存在");
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(Appconfig.GetRCVDocType(WWPORtnDocType, ORGID)))
                    {
                        DocTypeCode = WWPORtnDocType;
                        docTypeInfo.m_iD = Convert.ToInt64(Appconfig.GetRCVDocType(WWPORtnDocType, ORGID));
                        docTypeInfo.Org = long.Parse(ORGID);
                    }
                    else
                    {
                        throw new Exception("单据类型不存在");
                    }
                }
                #region 整理数据
                string UserCode = Bills.First().User;
                if (string.IsNullOrEmpty(UserCode))
                {
                    UserCode = ConfigurationManager.AppSettings["userCode"].ToString();
                }
                else
                {
                    string sql = @"    select a.ID,a.Code,a.Name from Base_User a WHERE A.Code='" + UserCode + "'  ";
                    DataTable dt = DBhlper.Query(sql, ERPConStr);
                    if (dt != null && dt.Rows.Count > 0)
                    {

                    }
                    else
                    {
                        UserCode = ConfigurationManager.AppSettings["userCode"].ToString();
                    }
                }

                List<CreateRtnWebApiModel> ModelList = new List<CreateRtnWebApiModel>();
                //List<string> VenCodeList = Data.Select(a => a.VenCode).Distinct().ToList();//按照供应商分组
                //if (VenCodeList != null && VenCodeList.Count > 1)
                //{
                //    throw new Exception("只能同时创建相同供应商的数据");
                //}

                List<string> lineList = new List<string>();


                foreach (ICSOutsourcingReceiveDocNegative Doc in Bills)
                {
                    foreach (ICSOutsourcingReceiveDocNegatives linedr in Doc.details)
                    {
                        lineList.Add(linedr.ODNRTDetailID);
                    }
                }


                string sql2 = @"   select  ss.code SupplierCode,cast(ll.id as varchar(200)) id ,
cast( ll.RtnLineNO as varchar(200)) RtnLineNO,hh.docno,
                        ll.RtnOrderQtyRU TuiBuQty,ll.RtnARQtyRU TuiKouQty
                        from  pm_rtn hh
                inner join PM_RtnLine ll on ll.rtn=hh.id
                left join CBO_Supplier ss on ss.id=hh.RtnToSupplier_supplier
                where ll.id in ('" + string.Join("','", lineList.ToArray()) + @"')  ";
                DataTable dt2 = DBhlper.Query(sql2, ERPConStr);
                if (dt2 != null && dt2.Rows.Count > 0)
                {

                }
                else
                {
                    throw new Exception("未查到相关退货信息");
                }
                DataTable disData = dt2.DefaultView.ToTable(true, new string[] { "SupplierCode" });
                if (disData.Rows.Count > 1)
                {
                    throw new Exception("只能同时创建相同供应商的退货数据");
                }
                string VenCode = disData.Rows[0]["SupplierCode"].ToString();

                CreateRtnWebApiModel Model = new CreateRtnWebApiModel(); ;
                Model.ConfirmDate = DateTime.Now; ;
                Model.srcDocType = 6;//来源类型 5 收货单； 6 采购退货申请单
                Model.itemType = 0;//Product 不针对原工序 0 WorkingProcedure 针对原工序 1
                Model.Memo = "";
                Model.OtherID = "";//第三方数据唯一性标识，此字段需要返回
                                   // Model.rcvDocTypeCode = "";//暂不支持传入，所以不传就行
                Model.rcvDocTypeID = docTypeInfo.m_iD;//单据类型（暂不支持传入）
                Model.splitTerm = new List<string>();


                //var HHs = Data.Where(A => A.VenCode == VenCode);
                List<TransformDTOsItem> transformDTOs = new List<TransformDTOsItem>();
                foreach (ICSOutsourcingReceiveDocNegative Doc in Bills)
                {
                    foreach (ICSOutsourcingReceiveDocNegatives linedr in Doc.details)
                    {

                        TransformDTOsItem dto = new TransformDTOsItem();
                        // dto.CooperateFromRcv//抛砖来源收货
                        //   dto.CooperateFromRcvLine//抛砖来源收货行
                        dto.DescFlexSegments = new DescFlexSegments();
                        dto.Memo = "";
                        dto.RcvBusinessDate = DateTime.Now;
                        dto.RejectQty = new RejectQty();
                        dto.RejectQty.Amount1 = linedr.Quantity;
                        dto.RejectQty.Amount2 = 0;

                        //dto.RtnBin //应该不是必填
                        dto.RtnBinCode = "";


                        DataRow[] drs = dt2.Select("id='" + linedr.ODNRTDetailID + "'");
                        if (drs == null || drs.Count() == 0)
                        {
                            throw new Exception("未查到相关退货信息,行ID=" + linedr.ODNRTDetailID);
                        }


                        if (!string.IsNullOrEmpty(drs[0]["TuiBuQty"].ToString()) && Convert.ToDecimal(drs[0]["TuiBuQty"].ToString()) != 0)
                        {
                            dto.RtnDeductQty = new RtnDeductQty();
                            dto.RtnDeductQty.Amount1 = 0;
                            dto.RtnDeductQty.Amount2 = 0;
                            dto.RtnFillQty = new RtnFillQty();
                            dto.RtnFillQty.Amount1 = linedr.Quantity;
                            dto.RtnFillQty.Amount2 = 0;
                        }
                        else
                        {
                            dto.RtnDeductQty = new RtnDeductQty();
                            dto.RtnDeductQty.Amount1 = linedr.Quantity;
                            dto.RtnDeductQty.Amount2 = 0;
                            dto.RtnFillQty = new RtnFillQty();
                            dto.RtnFillQty.Amount1 = 0;
                            dto.RtnFillQty.Amount2 = 0;
                        }


                        dto.SrcRcvDocLineNo = Convert.ToInt32(drs[0]["RtnLineNO"].ToString());

                        dto.SrcRcvDocNo = drs[0]["docno"].ToString();
                        // dto.SrcRcvLine=Convert.ToInt64( linedr.DNDetailID);//来源收货行不是必填
                        transformDTOs.Add(dto);
                    }


                }
                Model.transformDTOs = transformDTOs;
                ModelList.Add(Model);



                #endregion
                string postJson = JsonConvert.SerializeObject(ModelList);

                RtnToRcvReturnValue value = new RtnToRcvReturnValue();
                value = PostJsonToRCV(postJson, UserCode, ORGCode);



                if (value.IsSuccess)
                {
                    Appconfig.WriteLogFile("成功", LogName);


                    string sql = @"
                      select RCV.ID , RCV.ID  IDs,RCV.DOCNO  as SourceCode ,'' OtherInCode,MAX(DEP.CODE) cDepCode,MAX(DEPT.NAME)  cDepName,
                    MAX(WW.CODE) cWhCode,MAX(WWT.NAME) cWhName,
                       '采购退货申请单' as SourceType,MAX(RCV.CreatedBy) as CreateUser,MAX(RCV.CREATEDON)  as CreateDateTime,
                       MAX(RCV.ApprovedBy) as Checker,MAX(RCV.ApprovedOn) as CheckDateTime

                    from PM_Receivement rcv
                    left join PM_RCVLINE RCVL  ON  RCVL.Receivement=RCV.ID   
                    LEFT JOIN CBO_DEPARTMENT DEP ON RCVL.RcvDept=DEP.ID
                    LEFT JOIN CBO_DEPARTMENT_TRL DEPT ON DEPT.ID=DEP.ID AND DEPT.SYSMLflag='zh-CN'
                    LEFT JOIN CBO_WH WW ON RCVL.WH=WW.ID
                    LEFT JOIN CBO_WH_TRL WWT ON WW.ID=WWT.ID AND WWT.SYSMLflag='zh-CN'
                    where 1=1
                    AND rcv.docno='" + value.DocNo + @"' and RCV.org='" + ORGID + @"' 
                    AND RCVL.SplitFlag IN (0,2)
                    GROUP BY RCV.ID,RCV.DOCNO ";

                    DataTable dt1 = DBhlper.Query(sql, ERPConStr);


                    sql = @"   select   rcv.ID as IDs,rcvl.id as DetailID,rcvl.DocLineNo as Sequence,rcvl.iteminfo_itemcode as InvCode 
                   ,rcvl.RcvQtyTU as Quantity,rcvl.SrcDoc_srcdocline_entityid as SourceDetailID,rcvl.RcvQtyTU as Amount
                ,isnull(pro.code,'') ProjectCode, ''  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 rcv
                left join PM_RCVLINE RCVL  ON  RCVL.Receivement=RCV.ID   
 
                left join cbo_project pro on pro.id=rcvl.project
                where 1=1
                AND rcv.docno='" + value.DocNo + @"' and RCV.org='" + ORGID + @"' 
                AND RCVL.SplitFlag IN (0,2)
                ";
                    DataTable dt3 = DBhlper.Query(sql, ERPConStr);
                    DataSet ds = new DataSet();
                    ds.Tables.Add(dt1);
                    ds.Tables.Add(dt3);
                    string msg = JSON.DataSetToJson(ds, "details", "IDs");
                    return msg;
                }
                else
                {
                    Appconfig.WriteLogFile("失败：" + value.Message, LogName);
                    throw new Exception(value.Message);

                }

            }
            catch (Exception ex)
            {
                //异常信息捕获
                string HeadList = string.Empty;

                //string message=    GetExceptionMessage(ex);
                StringBuilder str = new StringBuilder();
                foreach (ICSOutsourcingReceiveDocNegative data in Bills)
                {
                    str.AppendLine("创建U9退货单");
                    str.AppendLine(ex.ToString());
                    HeadList += "\r\n 退货申请单号：" + data.ODNRTCode;
                }
                str.AppendLine(HeadList);
                str.AppendLine("结果:" + "False");


                Appconfig.WriteLogFile(str.ToString(), LogName);

                throw new Exception("失败：" + ex.Message);
            }
            #endregion
        }



        public void PostJsonToRCV(string DataJson, string CreateByCode, string ORGCode, ICSPurchaseReceiveDoc data, List<ICSPurchaseReceiveDoc> datalist)
        {
            try
            {
                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/Receivement/CreateRcvBySrc";
                    CreateUrl = string.Format(CreateUrl, U9IP);

                    try
                    {
                        //创建
                        string resultCreateSoFile = PostData.APT(CreateUrl, DataJson, TokenCode);

                        string DocNo = "";
                        long ID = -1;
                        string Message = "";

                        CreateRtnWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultCreateSoFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.IsSucess == false).ToList();
                            if (IsTrues != null && IsTrues.Count() > 0)
                            {
                                throw new Exception(RetModel.Data[0].ErrorMsg);
                            }
                            else
                            {
                                try
                                {
                                    DocNo = RetModel.Data[0].Code;
                                    ID = RetModel.Data[0].ID;
                                    #region 提交审核退货单
                                    List<SubmitOrShenHeModel> ListDoc = new List<SubmitOrShenHeModel>();
                                    SubmitOrShenHeModel subm = new SubmitOrShenHeModel();
                                    subm.RcvID = RetModel.Data[0].ID;
                                    subm.RcvDocNo = RetModel.Data[0].Code;
                                    subm.OrgCode = ORGCode;
                                    ListDoc.Add(subm);
                                    string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                                    TokenCode = GetToken(CreateByCode, ORGCode);

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

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

                                    CreateRtnWebApiReturnModel RetModel2 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultSubmFile);
                                    if (RetModel2.Success == true &&
                                        RetModel2.Data != null && RetModel2.Data.Count > 0)
                                    {
                                        var IsTrues2 = RetModel2.Data.Where(a => a.IsSucess == false).ToList();
                                        if (IsTrues2 != null && IsTrues2.Count() > 0)
                                        {
                                            throw new Exception(RetModel2.Data[0].ErrorMsg);
                                        }
                                        else
                                        {
                                            List<SubmitOrShenHeModel> ListDoc3 = new List<SubmitOrShenHeModel>();
                                            SubmitOrShenHeModel Apprm = new SubmitOrShenHeModel();
                                            Apprm.RcvID = RetModel.Data[0].ID;
                                            Apprm.RcvDocNo = RetModel.Data[0].Code;
                                            Apprm.OrgCode = ORGCode;
                                            ListDoc3.Add(Apprm);
                                            string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

                                            TokenCode = GetToken(CreateByCode, ORGCode);

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

                                            string resultappmFile = PostData.APT(ApproveUrl, postApproveJson, TokenCode);


                                            CreateRtnWebApiReturnModel RetModel3 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultappmFile);
                                            if (RetModel3.Success == true &&
                                                RetModel3.Data != null && RetModel3.Data.Count > 0)
                                            {
                                                var IsTrues3 = RetModel3.Data.Where(a => a.IsSucess == false).ToList();
                                                if (IsTrues3 != null && IsTrues3.Count() > 0)
                                                {
                                                    throw new Exception(RetModel3.Data[0].ErrorMsg);
                                                }

                                                string sql = @"select b.DocLineNo,b.DescFlexSegments_PrivateDescSeg30,b.ID,
					                                        b.SrcDoc_SrcDocLine_EntityID,b.ItemInfo_ItemCode,b.ArriveQtyPU 
					                                        from PM_Receivement a
                                                            left join PM_RcvLine b on a.ID = b.Receivement
                                                    where a.ID ='" + ID + "'";
                                                DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                                                if (dt.Rows.Count > 0)
                                                {
                                                    var linelist = new List<ICSPurchaseReceiveDocs>();
                                                    foreach (DataRow item in dt.Rows)
                                                    {
                                                        linelist.Add(new ICSPurchaseReceiveDocs
                                                        {
                                                            DetailID = item["ID"].ToString(),
                                                            LogIds = item["DescFlexSegments_PrivateDescSeg30"].ToString(),
                                                            Sequence = int.Parse(item["DocLineNo"].ToString()),
                                                            InvCode = item["ItemInfo_ItemCode"].ToString(),
                                                            Quantity = decimal.Parse(item["ArriveQtyPU"].ToString()),
                                                            DNRTDetailID = item["SrcDoc_SrcDocLine_EntityID"].ToString()
                                                        });
                                                    }


                                                    datalist.Add(new ICSPurchaseReceiveDoc
                                                    {
                                                        ID = data.ID,
                                                        RCVNEGCode = DocNo,
                                                        DNRTCode = DocNo,
                                                        details = linelist,
                                                        IsSuccess = true,
                                                        Message = "成功"
                                                    });

                                                }
                                            }
                                            else
                                            {
                                                throw new Exception(RetModel3.ResMsg);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception(RetModel2.ResMsg);
                                    }
                                    #endregion

                                }
                                catch (Exception ex)
                                {
                                    //删除
                                    try
                                    {
                                        List<SubmitOrShenHeModel> ListDoc4 = new List<SubmitOrShenHeModel>();
                                        SubmitOrShenHeModel delm = new SubmitOrShenHeModel();
                                        delm.RcvID = RetModel.Data[0].ID;
                                        delm.RcvDocNo = RetModel.Data[0].Code;
                                        delm.OrgCode = ORGCode;
                                        ListDoc4.Add(delm);
                                        string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                        TokenCode = GetToken(CreateByCode, ORGCode);

                                        string DelUrl = "http://{0}/u9c/webapi/Receivement/Delete";
                                        DelUrl = string.Format(DelUrl, U9IP);

                                        string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);


                                        CreateRtnWebApiReturnModel RetModel4 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultDelFile);
                                        if (RetModel4.Success == true &&
                                            RetModel4.Data != null && RetModel4.Data.Count > 0)
                                        {
                                            var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false);
                                            if (IsTrues4 != null && IsTrues4.Count() > 0)
                                            {
                                                throw new Exception(RetModel4.Data[0].ErrorMsg);
                                            }


                                            var linelist = new List<ICSPurchaseReceiveDocs>();
                                            foreach (var item in data.details)
                                            {
                                                linelist.Add(new ICSPurchaseReceiveDocs
                                                {
                                                    DetailID = item.DetailID,
                                                    LogIds = item.LogIds
                                                });
                                            }


                                            datalist.Add(new ICSPurchaseReceiveDoc
                                            {
                                                ID = data.ID,
                                                RCVTCode = data.RCVTCode,
                                                details = linelist,
                                                IsSuccess = false,
                                                Message = "提交失败，删除成功，异常：" + ex.Message
                                            });
                                        }
                                        else
                                        {
                                            throw new Exception(RetModel4.ResMsg);
                                        }

                                    }
                                    catch (Exception exdelete)
                                    {
                                        var linelist = new List<ICSPurchaseReceiveDocs>();
                                        foreach (var item in data.details)
                                        {
                                            linelist.Add(new ICSPurchaseReceiveDocs
                                            {
                                                DNRTDetailID = item.DNRTDetailID,
                                                LogIds = item.LogIds

                                            });
                                        }


                                        datalist.Add(new ICSPurchaseReceiveDoc
                                        {
                                            details = linelist,
                                            IsSuccess = false,
                                            Message = "提交审核失败，删除失败，删除异常：" + exdelete.Message + "，提交审核异常：" + ex.Message
                                        });
                                    }
                                }
                            }
                        }
                        else
                        {
                            throw new Exception(RetModel.ResMsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        var linelist = new List<ICSPurchaseReceiveDocs>();
                        foreach (var item in data.details)
                        {
                            linelist.Add(new ICSPurchaseReceiveDocs
                            {
                                DNRTDetailID = item.DNRTDetailID,
                                LogIds = item.LogIds
                            });
                        }


                        datalist.Add(new ICSPurchaseReceiveDoc
                        {
                            details = linelist,
                            IsSuccess = false,
                            Message = "创建失败，异常：" + ex.Message
                        });
                    }
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                var linelist = new List<ICSPurchaseReceiveDocs>();
                foreach (var item in data.details)
                {
                    linelist.Add(new ICSPurchaseReceiveDocs
                    {
                        DetailID = item.DetailID,
                        LogIds = item.LogIds

                    });
                }


                datalist.Add(new ICSPurchaseReceiveDoc
                {
                    ID = data.ID,
                    RCVTCode = data.RCVTCode,
                    details = linelist,
                    IsSuccess = false,
                    Message = "异常：" + ex.Message
                });

            }
        }


        public RtnToRcvReturnValue PostJsonToRCV(string DataJson, string CreateByCode, string ORGCode)
        {
            return new RtnToRcvReturnValue();
            //try
            //{
            //    string TokenCode = GetToken(CreateByCode, ORGCode);
            //    if (!string.IsNullOrWhiteSpace(TokenCode))
            //    {
            //        string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
            //        string CreateUrl = "http://{0}/u9c/webapi/Receivement/CreateRcvBySrc";
            //        CreateUrl = string.Format(CreateUrl, U9IP);

            //        try
            //        {
            //            //创建
            //            string resultCreateSoFile = PostData.APT(CreateUrl, DataJson, TokenCode);


            //            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")
            //            {
            //                CreateRtnWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(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)
            //                    {
            //                        throw new Exception(RetModel.Data[0].ErrorMsg);
            //                    }
            //                    else
            //                    {
            //                        try
            //                        {
            //                            DocNo = RetModel.Data[0].Code;
            //                            ID = RetModel.Data[0].ID;
            //                            #region 提交 退货单
            //                            List<SubmitOrShenHeModel> ListDoc = new List<SubmitOrShenHeModel>();
            //                            SubmitOrShenHeModel subm = new SubmitOrShenHeModel();
            //                            subm.RcvID = RetModel.Data[0].ID;
            //                            subm.RcvDocNo = RetModel.Data[0].Code;
            //                            subm.OrgCode = ORGCode;
            //                            ListDoc.Add(subm);
            //                            string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

            //                            TokenCode = GetToken(CreateByCode, ORGCode);

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

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



            //                            JObject objuu2 = JObject.Parse(resultSubmFile);


            //                            if (objuu2["Success"] != null && objuu2["Data"] != null && objuu2["Success"].ToString().ToUpper() == "TRUE")
            //                            {
            //                                CreateRtnWebApiReturnModel RetModel2 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultSubmFile);
            //                                if (RetModel2.Success == true &&
            //                                    RetModel2.Data != null && RetModel2.Data.Count > 0)
            //                                {
            //                                    var IsTrues2 = RetModel2.Data.Where(a => a.IsSucess == false);
            //                                    if (IsTrues2 != null && IsTrues2.Count() > 0)
            //                                    {
            //                                        throw new Exception(RetModel2.Data[0].ErrorMsg);
            //                                    }
            //                                    else
            //                                    {
            //                                        //审核
            //                                        try
            //                                        {
            //                                            List<SubmitOrShenHeModel> ListDoc3 = new List<SubmitOrShenHeModel>();
            //                                            SubmitOrShenHeModel Apprm = new SubmitOrShenHeModel();
            //                                            Apprm.RcvID = RetModel.Data[0].ID;
            //                                            Apprm.RcvDocNo = RetModel.Data[0].Code;
            //                                            Apprm.OrgCode = ORGCode;
            //                                            ListDoc3.Add(Apprm);
            //                                            string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

            //                                            TokenCode = GetToken(CreateByCode, ORGCode);

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

            //                                            string resultappmFile = PostData.APT(ApproveUrl, postApproveJson, TokenCode);


            //                                            JObject objuu3 = JObject.Parse(resultappmFile);


            //                                            if (objuu3["Success"] != null && objuu3["Data"] != null && objuu3["Success"].ToString().ToUpper() == "TRUE")
            //                                            {
            //                                                CreateRtnWebApiReturnModel RetModel3 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultappmFile);
            //                                                if (RetModel3.Success == true &&
            //                                                    RetModel3.Data != null && RetModel3.Data.Count > 0)
            //                                                {
            //                                                    var IsTrues3 = RetModel3.Data.Where(a => a.IsSucess == false);
            //                                                    if (IsTrues3 != null && IsTrues3.Count() > 0)
            //                                                    {
            //                                                        throw new Exception(RetModel3.Data[0].ErrorMsg);
            //                                                    }

            //                                                    string sql = @"select b.DocLineNo,b.DescFlexSegments_PrivateDescSeg1,b.ID from PM_Receivement a
            //                                        left join PM_RcvLine b on a.ID = b.Receivement
            //                                        where a.ID ='" + ID + "'";
            //                                                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
            //                                                    if (dt.Rows.Count > 0)
            //                                                    {
            //                                                        var linelist = new List<ICSPurchaseReceiveDocs>();
            //                                                        foreach (DataRow item in dt.Rows)
            //                                                        {
            //                                                            linelist.Add(new ICSPurchaseReceiveDocs
            //                                                            {
            //                                                                DetailID = item["ID"].ToString(),
            //                                                                LogIds = item["DescFlexSegments_PrivateDescSeg1"].ToString(),
            //                                                                Sequence = int.Parse(item["DocLineNo"].ToString())
            //                                                            });
            //                                                        }


            //                                                        datalist.Add(new ICSPurchaseReceiveDoc
            //                                                        {
            //                                                            ID = data.ID,
            //                                                            RCVTCode = DocNo,
            //                                                            details = linelist,
            //                                                            IsSuccess = true,
            //                                                            Message = "成功"
            //                                                        });
            //                                                    }
            //                                                }
            //                                            }
            //                                            else
            //                                            {
            //                                                Message += "审核采购退货：" + DocNo + "失败：";
            //                                                if (objuu3["Message"] != null && !string.IsNullOrEmpty(objuu3["Message"].ToString()))
            //                                                {
            //                                                    Message += objuu3["Message"].ToString();
            //                                                }
            //                                                if (objuu3["ResMsg"] != null && !string.IsNullOrEmpty(objuu3["ResMsg"].ToString()))
            //                                                {
            //                                                    Message += objuu3["ResMsg"].ToString();
            //                                                }

            //                                                throw new Exception(Message);
            //                                            }
            //                                        }
            //                                        catch (Exception ex)
            //                                        {
            //                                            //删除
            //                                            try
            //                                            {
            //                                                List<SubmitOrShenHeModel> ListDoc4 = new List<SubmitOrShenHeModel>();
            //                                                SubmitOrShenHeModel delm = new SubmitOrShenHeModel();
            //                                                delm.RcvID = RetModel.Data[0].ID;
            //                                                delm.RcvDocNo = RetModel.Data[0].Code;
            //                                                delm.OrgCode = ORGCode;
            //                                                ListDoc4.Add(delm);
            //                                                string postDelJson = JsonConvert.SerializeObject(ListDoc4);

            //                                                TokenCode = GetToken(CreateByCode, ORGCode);

            //                                                string DelUrl = "http://{0}/u9c/webapi/Receivement/Delete";
            //                                                DelUrl = string.Format(DelUrl, U9IP);

            //                                                string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);


            //                                                JObject objuu4 = JObject.Parse(resultDelFile);


            //                                                if (objuu4["Success"] != null && objuu4["Data"] != null && objuu4["Success"].ToString().ToUpper() == "TRUE")
            //                                                {
            //                                                    CreateRtnWebApiReturnModel RetModel4 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultDelFile);
            //                                                    if (RetModel4.Success == true &&
            //                                                        RetModel4.Data != null && RetModel4.Data.Count > 0)
            //                                                    {
            //                                                        var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false);
            //                                                        if (IsTrues4 != null && IsTrues4.Count() > 0)
            //                                                        {
            //                                                            throw new Exception(RetModel4.Data[0].ErrorMsg);
            //                                                        }


            //                                                        var linelist = new List<ICSPurchaseReceiveDocs>();
            //                                                        foreach (var item in data.details)
            //                                                        {
            //                                                            linelist.Add(new ICSPurchaseReceiveDocs
            //                                                            {
            //                                                                DetailID = item.DetailID,
            //                                                                LogIds = item.LogIds
            //                                                            });
            //                                                        }


            //                                                        datalist.Add(new ICSPurchaseReceiveDoc
            //                                                        {
            //                                                            ID = data.ID,
            //                                                            RCVTCode = data.RCVTCode,
            //                                                            details = linelist,
            //                                                            IsSuccess = false,
            //                                                            Message = "审核失败，删除成功，异常：" + ex.Message
            //                                                        });
            //                                                    }
            //                                                }
            //                                                else
            //                                                {
            //                                                    Message += "删除采购退货：" + DocNo + "失败：";
            //                                                    if (objuu4["Message"] != null && !string.IsNullOrEmpty(objuu4["Message"].ToString()))
            //                                                    {
            //                                                        Message += objuu4["Message"].ToString();
            //                                                    }
            //                                                    if (objuu4["ResMsg"] != null && !string.IsNullOrEmpty(objuu4["ResMsg"].ToString()))
            //                                                    {
            //                                                        Message += objuu4["ResMsg"].ToString();
            //                                                    }
            //                                                    throw new Exception(Message);
            //                                                }
            //                                            }
            //                                            catch (Exception exdelete)
            //                                            {
            //                                                var linelist = new List<ICSPurchaseReceiveDocs>();
            //                                                foreach (var item in data.details)
            //                                                {
            //                                                    linelist.Add(new ICSPurchaseReceiveDocs
            //                                                    {
            //                                                        DetailID = item.DetailID,
            //                                                        LogIds = item.LogIds

            //                                                    });
            //                                                }


            //                                                datalist.Add(new ICSPurchaseReceiveDoc
            //                                                {
            //                                                    ID = data.ID,
            //                                                    RCVTCode = data.RCVTCode,
            //                                                    details = linelist,
            //                                                    IsSuccess = false,
            //                                                    Message = "审核失败，删除失败，异常：" + exdelete.Message
            //                                                });
            //                                            }
            //                                        }
            //                                    }
            //                                }
            //                            }
            //                            else
            //                            {
            //                                Message += "提交采购退货：" + DocNo + "失败：";
            //                                if (objuu2["Message"] != null && !string.IsNullOrEmpty(objuu2["Message"].ToString()))
            //                                {
            //                                    Message += objuu2["Message"].ToString();
            //                                }
            //                                if (objuu2["ResMsg"] != null && !string.IsNullOrEmpty(objuu2["ResMsg"].ToString()))
            //                                {
            //                                    Message += objuu2["ResMsg"].ToString();
            //                                }
            //                            }
            //                            #endregion

            //                        }
            //                        catch (Exception ex)
            //                        {
            //                            //删除

            //                            try
            //                            {
            //                                List<SubmitOrShenHeModel> ListDoc4 = new List<SubmitOrShenHeModel>();
            //                                SubmitOrShenHeModel delm = new SubmitOrShenHeModel();
            //                                delm.RcvID = RetModel.Data[0].ID;
            //                                delm.RcvDocNo = RetModel.Data[0].Code;
            //                                delm.OrgCode = ORGCode;
            //                                ListDoc4.Add(delm);
            //                                string postDelJson = JsonConvert.SerializeObject(ListDoc4);

            //                                TokenCode = GetToken(CreateByCode, ORGCode);

            //                                string DelUrl = "http://{0}/u9c/webapi/Receivement/Delete";
            //                                DelUrl = string.Format(DelUrl, U9IP);

            //                                string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);


            //                                JObject objuu4 = JObject.Parse(resultDelFile);


            //                                if (objuu4["Success"] != null && objuu4["Data"] != null && objuu4["Success"].ToString().ToUpper() == "TRUE")
            //                                {
            //                                    CreateRtnWebApiReturnModel RetModel4 = JsonConvert.DeserializeObject<CreateRtnWebApiReturnModel>(resultDelFile);
            //                                    if (RetModel4.Success == true &&
            //                                        RetModel4.Data != null && RetModel4.Data.Count > 0)
            //                                    {
            //                                        var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false);
            //                                        if (IsTrues4 != null && IsTrues4.Count() > 0)
            //                                        {
            //                                            throw new Exception(RetModel4.Data[0].ErrorMsg);
            //                                        }


            //                                        var linelist = new List<ICSPurchaseReceiveDocs>();
            //                                        foreach (var item in data.details)
            //                                        {
            //                                            linelist.Add(new ICSPurchaseReceiveDocs
            //                                            {
            //                                                DetailID = item.DetailID,
            //                                                LogIds = item.LogIds

            //                                            });
            //                                        }


            //                                        datalist.Add(new ICSPurchaseReceiveDoc
            //                                        {
            //                                            ID = data.ID,
            //                                            RCVTCode = data.RCVTCode,
            //                                            details = linelist,
            //                                            IsSuccess = false,
            //                                            Message = "提交失败，删除成功，异常：" + ex.Message
            //                                        });
            //                                    }
            //                                }
            //                                else
            //                                {
            //                                    Message += "删除采购退货：" + DocNo + "失败：";
            //                                    if (objuu4["Message"] != null && !string.IsNullOrEmpty(objuu4["Message"].ToString()))
            //                                    {
            //                                        Message += objuu4["Message"].ToString();
            //                                    }
            //                                    if (objuu4["ResMsg"] != null && !string.IsNullOrEmpty(objuu4["ResMsg"].ToString()))
            //                                    {
            //                                        Message += objuu4["ResMsg"].ToString();
            //                                    }
            //                                    throw new Exception(Message);
            //                                }
            //                            }
            //                            catch (Exception exdelete)
            //                            {
            //                                var linelist = new List<ICSPurchaseReceiveDocs>();
            //                                foreach (var item in data.details)
            //                                {
            //                                    linelist.Add(new ICSPurchaseReceiveDocs
            //                                    {
            //                                        DetailID = item.DetailID,
            //                                        LogIds = item.LogIds

            //                                    });
            //                                }


            //                                datalist.Add(new ICSPurchaseReceiveDoc
            //                                {
            //                                    ID = data.ID,
            //                                    RCVTCode = data.RCVTCode,
            //                                    details = linelist,
            //                                    IsSuccess = false,
            //                                    Message = "提交失败，删除失败，异常：" + exdelete.Message
            //                                });
            //                            }
            //                        }
            //                    }
            //                }
            //                else
            //                {
            //                    throw new Exception(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);

            //            }
            //        }
            //        catch (Exception ex)
            //        {
            //            var linelist = new List<ICSPurchaseReceiveDocs>();
            //            foreach (var item in data.details)
            //            {
            //                linelist.Add(new ICSPurchaseReceiveDocs
            //                {
            //                    DetailID = item.DetailID,
            //                    LogIds = item.LogIds

            //                });
            //            }


            //            datalist.Add(new ICSPurchaseReceiveDoc
            //            {
            //                ID = data.ID,
            //                RCVTCode = data.RCVTCode,
            //                details = linelist,
            //                IsSuccess = false,
            //                Message = "创建失败，异常：" + ex.Message
            //            });
            //        }
            //    }
            //    else
            //    {
            //        throw new Exception("获取token值失败。");
            //    }

            //}
            //catch (Exception ex)
            //{
            //    var linelist = new List<ICSPurchaseReceiveDocs>();
            //    foreach (var item in data.details)
            //    {
            //        linelist.Add(new ICSPurchaseReceiveDocs
            //        {
            //            DetailID = item.DetailID,
            //            LogIds = item.LogIds

            //        });
            //    }


            //    datalist.Add(new ICSPurchaseReceiveDoc
            //    {
            //        ID = data.ID,
            //        RCVTCode = data.RCVTCode,
            //        details = linelist,
            //        IsSuccess = false,
            //        Message = "异常：" + ex.Message
            //    });

            //}
        }


        private string GetExceptionMessage(Exception ex)
        {
            string faultMessage = "未知错误，请查看ERP日志！";

            System.TimeoutException timeoutEx = ex as System.TimeoutException;
            if (timeoutEx != null)
            {
                faultMessage = "访问服务超时，请修改配置信息！";
            }
            else
            {
                FaultException<ServiceException> faultEx = ex as FaultException<ServiceException>;
                if (faultEx == null)
                {
                    faultMessage = ex.Message;
                }
                else
                {
                    ServiceException serviceEx = faultEx.Detail;
                    if (serviceEx != null && !string.IsNullOrEmpty(serviceEx.Message)
                        && !serviceEx.Message.Equals("fault", StringComparison.OrdinalIgnoreCase))
                    {
                        // 错误信息在faultEx.Message中，请提取，
                        // 格式为"Fault:料品不能为空，请录入\n 在....."
                        int startIndex = serviceEx.Message.IndexOf(":");
                        int endIndex = serviceEx.Message.IndexOf("\n");
                        if (endIndex == -1)
                            endIndex = serviceEx.Message.Length;
                        if (endIndex > 0 && endIndex > startIndex + 1)
                        {
                            faultMessage = serviceEx.Message.Substring(startIndex + 1, endIndex - startIndex - 1);
                        }
                        else
                        {
                            faultMessage = serviceEx.Message;
                        }
                    }
                }
            }
            return faultMessage;
        }

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

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

            return thContext;
        }
        #endregion

        private static UFIDAU9PMDTOsRtnToRcvDTOData[] setDataForItem(List<ICSPurchaseReceiveDoc> datas, string ORGID, string OrgCode)
        {
            List<UFIDAU9PMDTOsRtnToRcvDTOData> prs = new List<UFIDAU9PMDTOsRtnToRcvDTOData>();
            List<ItemCURR> lstitem = new List<ItemCURR>();

            StringBuilder beginstrlog = new StringBuilder();
            beginstrlog.AppendLine("创建采购退货(传入数据开始)");
            foreach (ICSPurchaseReceiveDoc data in datas)
            {
                foreach (ICSPurchaseReceiveDocs linedr in data.details)
                {
                    UFIDAU9PMDTOsRtnToRcvDTOData pr = new UFIDAU9PMDTOsRtnToRcvDTOData();
                    pr.RtnLineKey = long.Parse(linedr.DNRTDetailID);
                    pr.RtnLineKey_SKey = new UFSoft.UBF.Business.BusinessEntity.EntityKey();
                    pr.RtnLineKey_SKey.ID = long.Parse(linedr.DNRTDetailID);
                    pr.m_rtnFillQty = new UFIDAU9CBODTOsDoubleQuantityData();
                    pr.m_rtnFillQty.m_amount1 = linedr.Quantity;
                    pr.m_rtnFillQty.m_amount2 = linedr.Quantity;
                    pr.m_rtnDeductQty = new UFIDAU9CBODTOsDoubleQuantityData();
                    pr.m_rtnDeductQty.m_amount1 = 0;
                    pr.m_rtnDeductQty.m_amount2 = 0;
                    pr.m_rcvBusinessDate = Convert.ToDateTime(data.MTime);

                    pr.ExtensionData = null;
                    beginstrlog.AppendLine("退货申请单号:" + data.DNRTCode);
                    beginstrlog.AppendLine("退货申请单行ID:" + linedr.DNRTDetailID);
                    beginstrlog.AppendLine("退货存储地点:" + linedr.WHCode);
                    beginstrlog.AppendLine("退货数量:" + linedr.Quantity.ToString());

                    prs.Add(pr);
                }
            }
            Appconfig.WriteLogFile(beginstrlog.ToString(), "创建采购退货");
            return prs.ToArray();
        }

        #region 时间戳方法
        private DateTime TimestampToDateTime(long timestamp)
        {
            DateTime dateTimeStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = timestamp * 10000000;
            TimeSpan nowTimeSpan = new TimeSpan(lTime);
            DateTime resultDateTime = dateTimeStart.Add(nowTimeSpan);
            return resultDateTime;
        }
        #endregion


        public static string GetToken(string CreateByCode, string ORGCode)
        {

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

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

                JObject objToken = new JObject();
                objuu = JObject.Parse(resultToken);
                string TokenCode = objuu["Data"].ToString();
                return TokenCode;
            }
            else
            {
                throw new Exception("获取token失败");
            }


        }

    }

    public class ItemCURR
    {
        public string LOTNO { get; set; }//批号
        public string ORG { get; set; }//组织编码
        public string WH { get; set; }//仓库
        public string BIN { get; set; }//库位
        public string ITEM { get; set; }//物料
        public decimal QTY { get; set; }//数量
    }
    public class ItemRatio
    {
        public long ID { get; set; }//单位编码
        public string Code { get; set; }//单位编码
        public decimal Ratio { get; set; }//位数
        public int Precision { get; set; }//精度
    }

    public class RtnToRcvReturnValue
    {
        public string DocNo { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public rtnRcvLine[] rtnLines { get; set; }
        public Data Data { get; set; }
    }

    public class rtnRcvLine
    {
        public int LineNo { get; set; }
    }

    public class Data
    {
        public string ID { get; set; }
        public string DNCode { get; set; }
        public string cVenCode { get; set; }
        public string cVenName { get; set; }
        public string cDepCode { get; set; }
        public string cDepName { get; set; }
        public string POCode { get; set; }
        public string CreateUser { get; set; }
        public DateTime CreateDateTime { get; set; }
        public string Checker { get; set; }
        public DateTime CheckDateTime { get; set; }
        public List<DataLine> details { get; set; }
    }
    public class DataLine
    {
        public string DetailID { get; set; }
        public int Sequence { get; set; }
        public string InvCode { get; set; }
        public Decimal Quantity { get; set; }
        public Decimal RCVQuantity { get; set; }
        public string PODetailID { get; set; }
        public Decimal Amount { get; set; }
        public string cBatch { get; set; }
        public string brand { get; set; }
        public string cFree1 { get; set; }
        public string cFree2 { get; set; }
        public string cFree3 { get; set; }
        public string cFree4 { get; set; }
        public string cFree5 { get; set; }
        public string cFree6 { get; set; }
        public string cFree7 { get; set; }
        public string cFree8 { get; set; }
        public string cFree9 { get; set; }
        public string cFree10 { get; set; }
    }

    public class RtnToRcvITEMREQDATA
    {
        public string DocDate { get; set; }
        public string SrcID { get; set; }//	外系统ID 
        public string POLineID { get; set; }//	采购行ID 
        public string Uom { get; set; }//	单位  
        public decimal RcvQty { get; set; }//	收货数量 
        public string BusinessDate { get; set; }//	日期 
        public string CreatedBy { get; set; }//	操作人 
        public string LotNo { get; set; }//	批号 
        public string WHCode { get; set; }//	存储地点 
        public string Bin { get; set; }//	库位 
        public string Memo { get; set; }//	备注 
        public string Mfc { get; set; }//	厂牌 
        public string Project { get; set; }//	项目 
        public string Item { get; set; }//	料品 
        public string Supplier { get; set; }//	供应商 
        public string DocTypeCode { get; set; }//	单据类型 
        public string GroupFlag { get; set; }//	分单标识       
        public string SourceCode { get; set; }//	单号 
        public string Sequence { get; set; }//	行号     
        public decimal RtnFillQty { get; set; }//	补货数量 
        public decimal Quantity { get; set; }//	退扣数量 
        public string ReceivementType { get; set; }//	收货单类型 
        public string OtherDesc { get; set; }//	弹性域 
        public decimal PriceTC { get; set; }//	价格 

        public string WorkPoint { get; set; }//	组织 


    }
}
