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 Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using ICSSoft.DataProject;

namespace ICS.SpecialApproveTransferOut
{
    public class ApproveSpecialTransferOutDoc
    {

        //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 = "审核调出单并自动审核调入单";



        public Result ApproveTransferOut(List<ICSTransferDoc> Data)
        {
            var res = new Result();
            var datalist = new List<ICSTransferDoc>();

            foreach (var info in Data)
            {
                try
                {
                    string ORGID = "";
                    string ORGCode = Data[0].WorkPoint;

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

                    if (string.IsNullOrEmpty(ORGID))
                    {
                        throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                    }
                    #region 整理数据
                    string sql = @"select a.ID,a.Code,a.Name from Base_User a WHERE A.Code='" + info.User + "'  ";
                    DataTable dt = DBhlper.Query(sql, ERPConStr);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("用户编码：" + info.User + "在U9中不存在。");
                    }


                    List<TransferOutApproveModel> ModelList = new List<TransferOutApproveModel>();
                    TransferOutApproveModel Model = new TransferOutApproveModel();

                    string docsql = @"select DocNo from InvDoc_TransferOut
                                      where ID='{0}'";
                    docsql = string.Format(docsql, info.ID);
                    DataTable docdt = DBhlper.Query(docsql, ERPConStr);
                    if (docdt.Rows.Count == 0)
                    {
                        throw new Exception("传入调出单ID：" + info.ID + "无法查询到对应调出单信息,请确认数据!");
                    }
                    Model = new TransferOutApproveModel();
                    Model.OtherID = "";
                    Model.ID = long.Parse(info.ID);
                    Model.Code = docdt.Rows[0]["DocNo"].ToString();
                    ModelList.Add(Model);




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


                    res = PostJsonToRCV(postJson, info.User, ORGCode);
                    if (res.Success)
                    {
                        var linelist = new List<ICSTransferLineDoc>();
                        foreach (var item in info.details)
                        {
                            linelist.Add(new ICSTransferLineDoc
                            {
                                DetailID = item.DetailID,
                                IsSuccess = true,
                                Message = "成功",
                                LogIds = item.LogIds
                            });
                        }

                        datalist.Add(new ICSTransferDoc
                        {
                            ID = info.ID,
                            IsSuccess = true,
                            Message = "成功",
                            details = linelist
                        });
                    }
                    else
                    {
                        throw new Exception(res.Message);
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSTransferLineDoc>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSTransferLineDoc
                        {
                            DetailID = item.DetailID,
                            IsSuccess = false,
                            Message = "失败：" + ex.Message,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new ICSTransferDoc
                    {
                        ID = info.ID,
                        IsSuccess = false,
                        Message = "失败：" + GetExceptionMessage(ex),
                        details = linelist
                    });
                }
            }

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


        public Result SpecialApproveTransferOut(List<ICSTransferDoc> Data)
        {
            var res = new Result();
            var datalist = new List<ICSTransferDoc>();

            foreach (var info in Data)
            {
                try
                {
                    string ORGID = "";
                    string ORGCode = Data[0].WorkPoint;

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

                    if (string.IsNullOrEmpty(ORGID))
                    {
                        throw new Exception("组织编码：" + ORGCode + "在U9中不存在。");
                    }
                    #region 整理数据
                    string sql = @"select a.ID,a.Code,a.Name from Base_User a WHERE A.Code='" + info.User + "'  ";
                    DataTable dt = DBhlper.Query(sql, ERPConStr);
                    if (dt.Rows.Count == 0)
                    {
                        throw new Exception("用户编码：" + info.User + "在U9中不存在。");
                    }


                    List<TransferOutApproveModel> ModelList = new List<TransferOutApproveModel>();
                    TransferOutApproveModel Model = new TransferOutApproveModel();

                    string docsql = @"select DocNo from InvDoc_TransferOut
                                      where ID='{0}'";
                    docsql = string.Format(docsql, info.ID);
                    DataTable docdt = DBhlper.Query(docsql, ERPConStr);
                    if (docdt.Rows.Count == 0)
                    {
                        throw new Exception("传入调出单ID：" + info.ID + "无法查询到对应调出单信息,请确认数据!");
                    }
                    Model = new TransferOutApproveModel();
                    Model.OtherID = "";
                    Model.ID = long.Parse(info.ID);
                    Model.Code = docdt.Rows[0]["DocNo"].ToString();
                    ModelList.Add(Model);




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


                    res = SpecialApprovePostJsonToRCV(postJson, info.User, ORGCode);
                    if (res.Success)
                    {
                        var linelist = new List<ICSTransferLineDoc>();
                        foreach (var item in info.details)
                        {
                            linelist.Add(new ICSTransferLineDoc
                            {
                                DetailID = item.DetailID,
                                IsSuccess = true,
                                Message = "成功",
                                LogIds = item.LogIds
                            });
                        }

                        datalist.Add(new ICSTransferDoc
                        {
                            ID = info.ID,
                            IsSuccess = true,
                            Message = "成功",
                            details = linelist
                        });
                    }
                    else
                    {
                        throw new Exception(res.Message);
                    }
                }
                catch (Exception ex)
                {
                    var linelist = new List<ICSTransferLineDoc>();
                    foreach (var item in info.details)
                    {
                        linelist.Add(new ICSTransferLineDoc
                        {
                            DetailID = item.DetailID,
                            IsSuccess = false,
                            Message = "失败：" + ex.Message,
                            LogIds = item.LogIds
                        });
                    }

                    datalist.Add(new ICSTransferDoc
                    {
                        ID = info.ID,
                        IsSuccess = false,
                        Message = "失败：" + GetExceptionMessage(ex),
                        details = linelist
                    });
                }
            }

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

            return res;
        }


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

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


                    JObject objuu = JObject.Parse(resultCreateSoFile);
                    if (objuu["Success"] != null && objuu["Data"] != null && objuu["Success"].ToString().ToUpper() == "TRUE")
                    {
                        TransferOutApproveReturnModel RetModel = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultCreateSoFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.IsSucess == false).ToList();
                            if (IsTrues.Count() > 0)
                            {
                                throw new Exception(RetModel.Data[0].ErrorMsg);
                            }
                            else
                            {
                                res.Success = true;
                                res.Message = "成功";
                            }
                        }
                        else
                        {
                            throw new Exception(RetModel.ResMsg);
                        }
                    }
                    else
                    {
                        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(ErrorMessage);
                    }
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = "调用OpenAPI审核调出单失败." + ex.Message;
            }
            return res;
        }


        public static Result SpecialApprovePostJsonToRCV(string DataJson, string CreateByCode, string ORGCode)
        {
            Result res = new Result();
            try
            {
                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/TransferOut/Approve";
                    CreateUrl = string.Format(CreateUrl, U9IP);

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

                    TransferOutApproveReturnModel RetModel = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultCreateSoFile);
                    if (RetModel.Success == true &&
                        RetModel.Data != null && RetModel.Data.Count > 0)
                    {
                        var IsTrues = RetModel.Data.Where(a => a.IsSucess == false).ToList();
                        if (IsTrues.Count() > 0)
                        {
                            throw new Exception(RetModel.Data[0].ErrorMsg);
                        }
                        else
                        {
                            long TransInID = 0;
                            string TransInCode = "";
                            string DocNo = RetModel.Data[0].Code;
                            long ID = RetModel.Data[0].ID;
                            try
                            {
                                #region 查询生成的调入单并提交审核
                                string linesql = @" select A.DocNo,A.ID from InvDoc_TransferIn A
                                                    LEFT JOIN InvDoc_TransInLine B ON B.TransferIn=A.ID
                                                    WHERE B.SrcDocInfo_SrcDoc_EntityID='{0}'";
                                linesql = string.Format(linesql, ID);
                                DataTable linedt = DBhlper.Query(linesql, Appconfig.GetU9ConnStr());
                                if (linedt.Rows.Count == 0)
                                {
                                    throw new Exception("调出单审核后调入单查询失败，请确认是否配置审核后自动生成调入单");
                                }

                                TransInCode = linedt.Rows[0]["DocNo"].ToString();
                                TransInID = long.Parse(linedt.Rows[0]["ID"].ToString());

                                List<TransferOutApproveModel> ListDoc = new List<TransferOutApproveModel>();
                                TransferOutApproveModel subm = new TransferOutApproveModel();
                                subm.OtherID = "";
                                subm.ID = long.Parse(linedt.Rows[0]["ID"].ToString());
                                subm.Code = linedt.Rows[0]["DocNo"].ToString();
                                ListDoc.Add(subm);
                                string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                                TokenCode = GetToken(CreateByCode, ORGCode);

                                string SubmitUrl = "http://{0}/u9c/webapi/TransferIn/Submit";
                                SubmitUrl = string.Format(SubmitUrl, U9IP);
                                string resultSubmFile = PostData.APT(SubmitUrl, postSubmitJson, TokenCode);

                                TransferOutApproveReturnModel RetModel2 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(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
                                    {
                                        #region 审核调入单
                                        List<TransferOutApproveModel> ListDoc3 = new List<TransferOutApproveModel>();
                                        TransferOutApproveModel Apprm = new TransferOutApproveModel();
                                        Apprm.OtherID = "";
                                        Apprm.ID = long.Parse(linedt.Rows[0]["ID"].ToString());
                                        Apprm.Code = linedt.Rows[0]["DocNo"].ToString();
                                        ListDoc3.Add(Apprm);
                                        string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

                                        TokenCode = GetToken(CreateByCode, ORGCode);
                                        string ApproveUrl = "http://{0}/u9c/webapi/TransferIn/Approve";
                                        ApproveUrl = string.Format(ApproveUrl, U9IP);
                                        string resultappmFile = PostData.APT(ApproveUrl, postApproveJson, TokenCode);


                                        TransferOutApproveReturnModel RetModel3 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(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);
                                            }
                                            else
                                            {
                                                res.Success = true;
                                                res.Message = "审核调出单，提交审核对应调入单成功";
                                            }
                                        }
                                        else
                                        {
                                            throw new Exception("审核调入单失败：" + RetModel3.ResMsg);
                                        }

                                        #endregion
                                    }
                                }
                                else
                                {
                                    throw new Exception("提交调入单失败：" + RetModel2.ResMsg);
                                }

                                #endregion
                            }
                            catch (Exception exapp)
                            {
                                if (!string.IsNullOrEmpty(TransInCode))
                                {
                                    List<TransferOutApproveModel> ListDoc4 = new List<TransferOutApproveModel>();
                                    TransferOutApproveModel delm = new TransferOutApproveModel();
                                    delm.OtherID = "";
                                    delm.ID = TransInID;
                                    delm.Code = TransInCode;
                                    ListDoc4.Add(delm);
                                    string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                    string DelUrl = "http://{0}/u9c/webapi/TransferIn/Delete";
                                    DelUrl = string.Format(DelUrl, U9IP);
                                    string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

                                    TransferOutApproveReturnModel RetModel4 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultDelFile);
                                    if (RetModel4.Success == true &&
                                        RetModel4.Data != null && RetModel4.Data.Count > 0)
                                    {
                                        var IsTrues4 = RetModel4.Data.Where(a => a.IsSucess == false).ToList();
                                        if (IsTrues4 != null && IsTrues4.Count() > 0)
                                        {
                                            throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除失败：" + RetModel4.Data[0].ErrorMsg);
                                        }
                                        else
                                        {
                                            #region 弃审调出单
                                            List<TransferOutApproveModel> ListDoc5 = new List<TransferOutApproveModel>();
                                            TransferOutApproveModel unapprovem = new TransferOutApproveModel();
                                            unapprovem.OtherID = "";
                                            unapprovem.ID = ID;
                                            unapprovem.Code = DocNo;
                                            ListDoc5.Add(unapprovem);
                                            string postunapproveJson = JsonConvert.SerializeObject(ListDoc5);

                                            TokenCode = GetToken(CreateByCode, ORGCode);

                                            string UapproveUrl = "http://{0}/u9c/webapi/TransferOut/UnApprove";
                                            UapproveUrl = string.Format(UapproveUrl, U9IP);
                                            string resultUnapproveFile = PostData.APT(UapproveUrl, postunapproveJson, TokenCode);

                                            TransferOutApproveReturnModel RetModel5 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultUnapproveFile);
                                            if (RetModel5.Success == true &&
                                                RetModel5.Data != null && RetModel5.Data.Count > 0)
                                            {
                                                var IsTrues5 = RetModel5.Data.Where(a => a.IsSucess == false).ToList();
                                                if (IsTrues5 != null && IsTrues5.Count() > 0)
                                                {
                                                    throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除成功，调出单弃审失败：" + RetModel5.Data[0].ErrorMsg);
                                                }
                                                else
                                                {
                                                    #region 提交调出单
                                                    List<TransferOutApproveModel> ListDoc6 = new List<TransferOutApproveModel>();
                                                    TransferOutApproveModel submitm = new TransferOutApproveModel();
                                                    submitm.OtherID = "";
                                                    submitm.ID = ID;
                                                    submitm.Code = DocNo;
                                                    ListDoc6.Add(submitm);
                                                    string submitJson = JsonConvert.SerializeObject(ListDoc6);

                                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                                    string submitUrl = "http://{0}/u9c/webapi/TransferOut/Submit";
                                                    submitUrl = string.Format(submitUrl, U9IP);
                                                    string resultsubmitFile = PostData.APT(submitUrl, submitJson, TokenCode);
                                                    TransferOutApproveReturnModel RetModel6 = JsonConvert.DeserializeObject<TransferOutApproveReturnModel>(resultsubmitFile);
                                                    if (RetModel6.Success == true &&
                                                                   RetModel6.Data != null && RetModel6.Data.Count > 0)
                                                    {
                                                        var IsTrues6 = RetModel6.Data.Where(a => a.IsSucess == false).ToList();
                                                        if (IsTrues6 != null && IsTrues6.Count() > 0)
                                                        {
                                                            throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除成功，调出单弃审成功，提交失败" + RetModel6.Data[0].ErrorMsg);
                                                        }

                                                        throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除成功，调出单弃审成功，提交成功");
                                                    }
                                                    else
                                                    {
                                                        throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除成功，调出单弃审成功，提交失败" + RetModel6.ResMsg);
                                                    }
                                                    #endregion
                                                }
                                            }
                                            else
                                            {
                                                throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除成功，调出单弃审失败：" + RetModel5.ResMsg);
                                            }
                                            #endregion
                                        }
                                    }
                                    else
                                    {
                                        throw new Exception("调入单提交审核失败：" + exapp.Message + "，调入单删除失败：" + RetModel4.ResMsg);
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception(RetModel.ResMsg);
                    }
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = "调用OpenAPI审核调出单失败." + ex.Message;
            }
            return res;
        }



        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

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

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

                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 ReturnValue
    {
        public string DocNo { get; set; }
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public Line[] rtnLines { get; set; }
        public Data Data { get; set; }

        public string LogId { get; set; }
    }

    public class Line
    {
        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; }//	组织 


    }
}
