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

namespace ICSSoft.APICreateMaterialDelivery
{
    public class CreateMaterialDelivery
    {
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string connString = System.Configuration.ConfigurationManager.AppSettings["ERPConnStr"];
        private static string ERPDB = System.Configuration.ConfigurationManager.AppSettings["ERPDB"];
        private static string LogName = "创建材料出库单";


        public rtnMaterialDeliveryInfo ActionCreateMaterialDelivery(List<ICSRdrecord11> infos)
        {
            rtnMaterialDeliveryInfo rtninfo = new rtnMaterialDeliveryInfo();
            try
            {
                MessageBase[] message = null;
                string OrgID = "";
                string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                orgsql = string.Format(orgsql, infos[0].WorkPoint);
                DataTable orgdt = DBhlper.Query(orgsql, connString);
                if (orgdt.Rows.Count != 0)
                {
                    OrgID = orgdt.Rows[0]["ID"].ToString();
                }
                else
                {
                    throw new Exception("传入组织编码错误!");
                }
                List<UFIDAU9ISVMOMaterialDeliveryDocDTOData> HeadList = new List<UFIDAU9ISVMOMaterialDeliveryDocDTOData>();
                UFIDAU9ISVMOMaterialDeliveryDocDTOData HeadInfo = new UFIDAU9ISVMOMaterialDeliveryDocDTOData();
                List<UFIDAU9ISVMOMaterialDeliveryDocLineDTOData> BodyList = new List<UFIDAU9ISVMOMaterialDeliveryDocLineDTOData>();
                UFIDAU9ISVMOMaterialDeliveryDocLineDTOData BodyInfo = new UFIDAU9ISVMOMaterialDeliveryDocLineDTOData();
                foreach (ICSRdrecord11 Info in infos)
                {
                    long UserID = 0;
                    long DeptID = 0;
                    bool NeedOverIssue = false;
                    string usersql = @" select A.ID from Base_User A
                                        where A.Code='{0}'";
                    usersql = string.Format(usersql, Info.User);
                    DataTable userdt = DBhlper.Query(usersql, connString);
                    if (userdt.Rows.Count != 0)
                    {
                        UserID = long.Parse(userdt.Rows[0]["ID"].ToString());
                    }
                    String docHeadsql = @"select IsOverIssue,IssueDepartment from Issue_IssueApplyDoc
                                          where DocNo='{0}' and Org='{1}'";

                    docHeadsql = string.Format(docHeadsql, Info.SourceCode, OrgID);
                    DataTable docHeaddt = DBhlper.Query(docHeadsql, connString);
                    if (docHeaddt.Rows.Count != 0)
                    {
                        NeedOverIssue = Convert.ToBoolean(docHeaddt.Rows[0]["IsOverIssue"]);
                        DeptID = long.Parse(docHeaddt.Rows[0]["IssueDepartment"].ToString());
                    }
                    HeadInfo = new UFIDAU9ISVMOMaterialDeliveryDocDTOData();
                    BodyList = new List<UFIDAU9ISVMOMaterialDeliveryDocLineDTOData>();
                    HeadInfo.m_issueType = 0;
                    HeadInfo.m_issuePerson = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    HeadInfo.m_issuePerson.m_iD = UserID;
                    HeadInfo.m_issuePerson.m_code = Info.User;
                    HeadInfo.m_issueDepartment = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                    HeadInfo.m_issueDepartment.m_iD = DeptID;
                    foreach (rdrecords11 line in Info.details)
                    {
                        //根据传入行ID查询申请单行信息
                        string linesql = @"select ID,MOPick,SupplyWh,Project,LotMaster,ItemInfo from Issue_IssueApplyDocLine
                                           where ID='{0}'";
                        linesql = string.Format(linesql, line.SourceDetailID);
                        DataTable linedt = DBhlper.Query(linesql, connString);
                        if (linedt.Rows.Count == 0)
                        {
                            throw new Exception("传入领料申请单行的ID:" + line.SourceDetailID + "无法在U9查询到相关信息!");
                        }
                        else
                        {
                            //验证仓库是否启用批号管理
                            string whsql = @"select IsLot,Code from CBO_Wh
                                             where ID='{0}'";
                            whsql = string.Format(whsql, linedt.Rows[0]["SupplyWh"].ToString());
                            DataTable whdt = DBhlper.Query(whsql, connString);
                            long LotID = 0;
                            DataTable infodt = new DataTable();
                            if (whdt.Rows[0]["IsLot"].ToString().ToUpper() == "TRUE")
                            {
                                if (line.BatchCode != "")
                                {
                                    //批号ID获取
                                    string infosql = @"select ID from Lot_LotMaster
                                                       where LotCode='{0}' and ItemCode='{1}'";
                                    infosql = string.Format(infosql, line.BatchCode, line.InvCode);
                                    infodt = DBhlper.Query(infosql, connString);
                                    if (infodt.Rows.Count == 0)
                                    {
                                        throw new Exception("传入批号:" + line.BatchCode + "无法在U9查询到相关信息!");
                                    }
                                    else
                                    {
                                        LotID = long.Parse(infodt.Rows[0]["ID"].ToString());
                                    }
                                }
                                else
                                {
                                    throw new Exception("单据行维护仓库:" + whdt.Rows[0]["Code"].ToString() + "启用批号管控，传入批号不能为空!");
                                }
                            }
                            BodyInfo = new UFIDAU9ISVMOMaterialDeliveryDocLineDTOData();
                            if (NeedOverIssue == true)
                            {
                                #region 获取类型为超额的材料出库单类型
                                string docsql = @"select Code from Issue_MaterialDeliveryDocType
                                                  where IsOverIssue='true'";
                                DataTable docdt = DBhlper.Query(docsql, connString);
                                if (infodt.Rows.Count == 0)
                                {
                                    throw new Exception("未维护超额类型的材料出库单!");
                                }
                                else
                                {
                                    BodyInfo.m_sourceDocType = int.Parse(docdt.Rows[0]["Code"].ToString());
                                }
                                #endregion
                            }
                            else
                            {
                                BodyInfo.m_sourceDocType = 1;
                            }
                            BodyInfo.m_issueApplyDocLine = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            BodyInfo.m_issueApplyDocLine.m_iD = long.Parse(line.SourceDetailID);
                            BodyInfo.m_wh = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            BodyInfo.m_wh.m_iD = long.Parse(linedt.Rows[0]["SupplyWh"].ToString());
                            BodyInfo.m_issuedQty = line.Quantity;
                            if (LotID != 0)
                            {
                                BodyInfo.m_lot = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                                BodyInfo.m_lot.m_iD = LotID;
                                BodyInfo.m_lot.m_code = line.BatchCode;
                            }
                            BodyInfo.m_item = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                            BodyInfo.m_item.m_iD = long.Parse(linedt.Rows[0]["ItemInfo"].ToString());
                            BodyList.Add(BodyInfo);
                        }
                    }
                    HeadInfo.m_materialDeliveryDocLines = BodyList.ToArray();
                    HeadList.Add(HeadInfo);
                }

                ThreadContext context = CreateContextObj(OrgID);
                UFIDAU9ISVMONewIssueDocKeyDTOData[] ResultList = null;
                UFIDAU9ISVMOICreateMaterialDeliveryDocOut4ExternalClient client = new UFIDAU9ISVMOICreateMaterialDeliveryDocOut4ExternalClient();
                ResultList = client.Do(context, HeadList.ToArray(), out message);
                string xxx = "";
                //         string postJson = JsonConvert.SerializeObject(HeadList);
                //         APIreturnInfo value = new APIreturnInfo();
                //         value = PostJsonToMaterialDelivery(postJson, "admin", infos[0].WorkPoint);
                //         if (value.IsSuccess == true)
                //         {
                //             DataSet ds = new DataSet();
                //             rtninfo.DocNo = value.DocNo;
                //             rtninfo.IsSuccess = true;
                //             #region 查询
                //             string rtnsql = @"  
                //                     select DISTINCT a.ID as ID,a.ID as IDs,SourceDoc_SrcDocNo as SourceCode ,
                //                    a.DocNo as IssueCode,'' AS cDepCode,'' as cDepName,'' WHCode,'' WHName,
                //                     a.SourceDoc_SrcDocType as SourceType,a.CreatedBy as CreateUser,a.CreatedOn as CreateDateTime,
                //                     a.ApproveBy as Checker,a.ApproveOn as CheckDateTime
                //                     from Issue_MaterialDeliveryDoc a
                //                     WHERE a.DocNo='{0}' and a.Org='{1}'";
                //             rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                //             DataTable mdt = DBhlper.Query(rtnsql, connString);
                //             ds.Tables.Add(mdt);
                //             rtnsql = @" select DISTINCT a.ID as IDs,b.ID as DetailID,b.DocLineNo as Sequence,c.Code as InvCode 
                //,b.IssuedQtyUOM as Quantity,b.SourceDoc_SrcDocLineID as SourceDetailID,0 as Amount
                //,d.Code as cDepCode,dd.Name as cDepName,e.Code as WHCode,ee.Name as WHName
                //,isnull(f.Code,'') ProjectCode,isnull(g.LotCode,'') cBatch,'' version ,'' brand,
                //'' as cFree1,
                //'' as cFree2,
                //'' as cFree3,
                //'' as cFree4,
                //'' as cFree5,
                //'' as cFree6,
                //'' as cFree7,
                //'' as cFree8,
                //'' as cFree9,
                //'' as cFree10
                //from Issue_MaterialDeliveryDoc a
                //left join Issue_MaterialDeliveryDocLine b on b.MaterialDeliveryDoc=a.ID
                //left join CBO_ItemMaster c on c.ID=b.ItemInfo
                //left join CBO_Department d on d.ID=b.IssueDept
                //left join CBO_Department_Trl dd on dd.ID=d.ID
                //left join CBO_Wh e on e.ID=b.SupplyWh
                //left join CBO_Wh_Trl ee on ee.ID=e.ID
                //left join CBO_Project f on f.ID=b.Project
                //left join Lot_LotMaster g on g.ID=b.LotMaster
                //   WHERE a.DocNo='{0}' and a.Org='{1}'";
                //             rtnsql = string.Format(rtnsql, value.DocNo, OrgID);
                //             DataTable sdt = DBhlper.Query(rtnsql, connString);
                //             ds.Tables.Add(sdt);
                //             #endregion
                //             rtninfo.Data = JSON.DataSetToJson(ds, "details", "IDs");
                //         }
                //         else
                //         {
                //             throw new Exception(value.Message);
                //         }
                return rtninfo;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
                throw new Exception(ex.Message);
            }
        }

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

                Appconfig.WriteLogFile("调用接口Json：" + DataJson, LogName);
                string TokenCode = GetToken(CreateByCode, ORGCode);
                if (!string.IsNullOrWhiteSpace(TokenCode))
                {
                    string U9IP = ConfigurationManager.AppSettings["U9IP"].ToString();
                    string CreateUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Create";
                    CreateUrl = string.Format(CreateUrl, U9IP);

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

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

                    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")
                    {
                        CreateMaterialDeliveryWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultCreateSoFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.m_isSucess == false);
                            if (IsTrues != null && IsTrues.Count() > 0)
                            {

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

                                DocNo = RetModel.Data[0].m_code;
                                if (!string.IsNullOrEmpty(RetModel.Data[0].m_iD))
                                {
                                    ID = long.Parse(RetModel.Data[0].m_iD);
                                }
                                else
                                {
                                    ID = GetDocID(DocNo, ORGCode);
                                }
                                Message += "材料出库单：" + DocNo + "创建成功。";
                                #region 提交/审核材料出库单
                                List<OperateMaterialDeliveryModel> ListDoc = new List<OperateMaterialDeliveryModel>();
                                OperateMaterialDeliveryModel subm = new OperateMaterialDeliveryModel();
                                int Version = GetDocSysVersion(ID);
                                subm.ID = ID;
                                subm.DocNo = RetModel.Data[0].m_code;
                                subm.CurrentSysVersion = Version;
                                subm.isAutoApp = true;
                                ListDoc.Add(subm);
                                string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                                TokenCode = GetToken(CreateByCode, ORGCode);

                                string SubmitUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Approve";
                                SubmitUrl = string.Format(SubmitUrl, U9IP);
                                Appconfig.WriteLogFile("提交调用接口Json：" + postSubmitJson, LogName);
                                string resultSubmFile = PostData.APT(SubmitUrl, postSubmitJson, TokenCode);

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

                                JObject objuu2 = JObject.Parse(resultSubmFile);


                                if (objuu2["Success"] != null && objuu2["Data"] != null && objuu2["Success"].ToString().ToUpper() == "TRUE")
                                {
                                    CreateMaterialDeliveryWebApiReturnModel RetModel2 = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultSubmFile);
                                    if (RetModel2.Success == true &&
                                        RetModel2.Data != null && RetModel2.Data.Count > 0)
                                    {
                                        var IsTrues2 = RetModel2.Data.Where(a => a.m_isSucess == false);
                                        if (IsTrues2 != null && IsTrues2.Count() > 0)
                                        {
                                            Message += RetModel2.Data[0].m_errorMsg;
                                        }
                                        else
                                        {

                                            #region 审核材料出库单
                                            List<OperateMaterialDeliveryModel> ListDoc3 = new List<OperateMaterialDeliveryModel>();
                                            OperateMaterialDeliveryModel Apprm = new OperateMaterialDeliveryModel();
                                            Version = GetDocSysVersion(ID);
                                            string Status = GetDocStatus(ID);
                                            if (Status == "1")
                                            {
                                                Apprm.ID = ID;
                                                Apprm.DocNo = RetModel.Data[0].m_code;
                                                Apprm.CurrentSysVersion = Version;
                                                Apprm.isAutoApp = true;
                                                ListDoc3.Add(Apprm);
                                                string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

                                                TokenCode = GetToken(CreateByCode, ORGCode);

                                                string ApproveUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Approve";
                                                ApproveUrl = string.Format(ApproveUrl, U9IP);
                                                Appconfig.WriteLogFile("审核调用接口Json：" + postApproveJson, LogName);
                                                string resultappmFile = PostData.APT(ApproveUrl, postApproveJson, TokenCode);

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

                                                JObject objuu3 = JObject.Parse(resultappmFile);


                                                if (objuu3["Success"] != null && objuu3["Data"] != null && objuu3["Success"].ToString().ToUpper() == "TRUE")
                                                {
                                                    CreateMaterialDeliveryWebApiReturnModel RetModel3 = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultappmFile);
                                                    if (RetModel3.Success == true &&
                                                        RetModel3.Data != null && RetModel3.Data.Count > 0)
                                                    {
                                                        var IsTrues3 = RetModel3.Data.Where(a => a.m_isSucess == false);
                                                        if (IsTrues3 != null && IsTrues3.Count() > 0)
                                                        {
                                                            Message += RetModel3.Data[0].m_errorMsg;
                                                        }
                                                        else
                                                        {

                                                            IsSucess = true;
                                                            Message += "审核材料出库单：" + DocNo + "成功。";
                                                        }
                                                    }
                                                }
                                                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();
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                IsSucess = true;
                                                Message += "审核材料出库单：" + DocNo + "成功。";
                                            }
                                            #endregion
                                        }
                                    }
                                }
                                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

                                #region 没有成功 就删除
                                if (!IsSucess)
                                {
                                    List<OperateMaterialDeliveryModel> ListDoc4 = new List<OperateMaterialDeliveryModel>();
                                    OperateMaterialDeliveryModel delm = new OperateMaterialDeliveryModel();
                                    Version = GetDocSysVersion(ID);
                                    delm.ID = ID;
                                    delm.DocNo = RetModel.Data[0].m_code;
                                    delm.CurrentSysVersion = Version;
                                    delm.isAutoApp = true;
                                    ListDoc4.Add(delm);
                                    string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                    string DelUrl = "http://{0}/u9c/webapi/MaterialDeliveryDoc/Delete";
                                    DelUrl = string.Format(DelUrl, U9IP);
                                    Appconfig.WriteLogFile("删除调用接口Json：" + postDelJson, LogName);
                                    string resultDelFile = PostData.APT(DelUrl, postDelJson, TokenCode);

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

                                    JObject objuu4 = JObject.Parse(resultDelFile);


                                    if (objuu4["Success"] != null && objuu4["Data"] != null && objuu4["Success"].ToString().ToUpper() == "TRUE")
                                    {
                                        CreateMaterialDeliveryWebApiReturnModel RetModel4 = JsonConvert.DeserializeObject<CreateMaterialDeliveryWebApiReturnModel>(resultDelFile);
                                        if (RetModel4.Success == true &&
                                            RetModel4.Data != null && RetModel4.Data.Count > 0)
                                        {
                                            var IsTrues4 = RetModel4.Data.Where(a => a.m_isSucess == false);
                                            if (IsTrues4 != null && IsTrues4.Count() > 0)
                                            {
                                                Message += RetModel4.Data[0].m_errorMsg;
                                            }
                                            else
                                            {
                                                Message += "删除材料出库单：" + DocNo + "成功";
                                            }
                                        }
                                    }
                                    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();
                                        }
                                    }
                                }

                                #endregion

                            }
                        }
                        else
                        {
                            Message += RetModel.ResMsg; ;
                        }


                    }
                    else
                    {
                        IsSucess = false;
                        string ErrorMessage = "";
                        if (objuu["Message"] != null && !string.IsNullOrEmpty(objuu["Message"].ToString()))
                        {
                            ErrorMessage += objuu["Message"].ToString();
                        }
                        if (objuu["ResMsg"] != null && !string.IsNullOrEmpty(objuu["ResMsg"].ToString()))
                        {
                            ErrorMessage += objuu["ResMsg"].ToString();
                        }
                        throw new Exception("调用OpenAPI创建材料出库单失败." + ErrorMessage);

                    }

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

            }
            catch (Exception ex)
            {
                Appconfig.WriteLogFile("Error：" + ex.ToString(), LogName);
                valueRet.IsSuccess = false;
                valueRet.DocNo = "";
                valueRet.Message = ex.Message;

            }
            return valueRet;
        }

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

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

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

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

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

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

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


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

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

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

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

            return thContext;

            return thContext;
        }

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

        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        private static string GetExceptionMessage(Exception ex)
        {
            string faultMessage = "未知错误，请查看ERP日志！";

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

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

    }


}
