using ICS.CreateLotMaster;
using ICS.WCF.Base;
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 UFIDA.ISV.CreateLotMaster;
using UFSoft.UBF.Service;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;

namespace UFIDA.ISV.CreateCheckDiffDoc
{

    public class CustCreateCheckDiffDoc
    {
        private static string LogName = "创建盘点差异单";
        /// <summary>
        /// 创建盘点差异单OpenAPI
        /// </summary>
        /// <param name="InfoList"></param>
        /// <returns></returns>
        public rtnChkInfo CreateByOpenAPI(List<CheckDiffInfo> InfoList)
        {
            StringBuilder beginstrlog = new StringBuilder();
            beginstrlog.AppendLine("创建盘点差异单(传入数据开始)");
            beginstrlog.AppendLine("*****************************************************");
            foreach (var item in InfoList)
            {
                beginstrlog.AppendLine("组织编码:" + item.WorkPoint);
                beginstrlog.AppendLine("--------------------------------------------------");
                foreach (var line in item.details)
                {
                    beginstrlog.AppendLine("物料编码:" + line.InvCode);
                    beginstrlog.AppendLine("盘点仓库:" + line.WHCode);
                    beginstrlog.AppendLine("批号:" + line.BatchCode);
                    beginstrlog.AppendLine("盘点数量:" + line.Quantity);
                    beginstrlog.AppendLine("LogId:" + line.LogId);
                }
                beginstrlog.AppendLine("--------------------------------------------------");

            }
            beginstrlog.AppendLine("*****************************************************");
            beginstrlog.AppendLine("创建盘点差异单(传入数据结束)");
            Appconfig.WriteLogFile(beginstrlog.ToString(), "创建盘点差异单");
            #region 服务调用框架结构
            //空
            string[] splitBy = new string[] { };
            string UserID = "";
            string UserCode = "";
            string UserName = "";
            string OrgID = "";
            int StorageType = 0;
            string DeptID = "";
            long WHID = 0;
            long ItemID = 0;
            long MOID = 0;
            try
            {
                rtnChkInfo rtnpo = new rtnChkInfo();
                if (InfoList == null || InfoList.Count == 0)
                {
                    rtnpo = new rtnChkInfo();
                    rtnpo.Success = false;
                    rtnpo.Message = "传入参数不能为空";
                    return rtnpo;
                }

                foreach (var item in InfoList)
                {
                    string orgsql = @"select ID from Base_Organization
                                  where Code='{0}'";
                    orgsql = string.Format(orgsql, item.WorkPoint);
                    DataTable orgdt = DBhlper.Query(orgsql, Appconfig.GetU9ConnStr());
                    if (orgdt.Rows.Count != 0)
                    {
                        OrgID = orgdt.Rows[0]["ID"].ToString();
                    }
                    else
                    {
                        rtnpo.Message = "传入的组织编码有误！";
                        rtnpo.Success = false;
                        return rtnpo;
                    }
                    foreach (var line in item.details)
                    {
                        if (line.InvCode == "")
                        {
                            rtnpo = new rtnChkInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入物料编码不能为空";
                            return rtnpo;
                        }
                    }
                }


                //给传入参数赋值

                //pOList = SetrCVDtos(rCVInfoList);
                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建盘点差异单");
                strlog.AppendLine("*****************************************************");

                List<CreateCheckDiffDocAPIModel> chkInfoList = new List<CreateCheckDiffDocAPIModel>();
                CreateCheckDiffDocAPIModel chkInfo = new CreateCheckDiffDocAPIModel();
                List<LineData> chklinelist = new List<LineData>();
                foreach (var Info in InfoList)
                {
                    chkInfo = new CreateCheckDiffDocAPIModel();
                    string typesql = @"select ID,Code from InvDoc_CheckDiffBillType
                                    where Effective_IsEffective=1 and Effective_DisableDate>GETDATE()
                                    and Org='{0}'";
                    typesql = string.Format(typesql, OrgID);
                    DataTable typedt = DBhlper.Query(typesql, Appconfig.GetU9ConnStr());
                    if (typedt.Rows.Count != 0)
                    {
                        chkInfo.DocumentType_Code = typedt.Rows[0]["Code"].ToString();
                    }
                    else
                    {
                        rtnpo = new rtnChkInfo();
                        rtnpo.Success = false;
                        rtnpo.Message = "未获取到生效的盘点差异单单据类型!";
                        return rtnpo;
                    }
                    chkInfo.BusinessDate = DateTime.Now;
                    LineData chklineinfo = new LineData();

                    strlog.AppendLine("组织编码:" + Info.WorkPoint);
                    strlog.AppendLine("--------------------------------------------------");

                    foreach (var line in Info.details)
                    {
                        chklineinfo = new LineData();
                        strlog.AppendLine("物料编码:" + line.InvCode);
                        strlog.AppendLine("盘点仓库:" + line.WHCode);
                        strlog.AppendLine("批号:" + line.BatchCode);
                        strlog.AppendLine("盘点数量:" + line.Quantity);
                        strlog.AppendLine("--------------------------------------------------");
                        #region 获取料品信息
                        string sqlItem = @"select ID from CBO_ItemMaster
                                       WHERE Code='{0}' AND Org='{1}'";
                        sqlItem = string.Format(sqlItem, line.InvCode, OrgID);
                        DataTable _dtItem = DBhlper.Query(sqlItem, Appconfig.GetU9ConnStr());
                        if (_dtItem != null && _dtItem.Rows.Count > 0)
                        {
                            ItemID = long.Parse(_dtItem.Rows[0]["ID"].ToString());
                        }
                        else
                        {
                            rtnpo = new rtnChkInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入料品编码未在U9获取到有效的料品ID";
                            return rtnpo;
                        }
                        #endregion
                        #region 获取仓库信息
                        string sqlWH = @"select ID,IsLot from CBO_Wh
                                     WHERE Code='{0}' AND Org='{1}' ";
                        sqlWH = string.Format(sqlWH, line.WHCode, OrgID);
                        DataTable _dtWH = DBhlper.Query(sqlWH, Appconfig.GetU9ConnStr());
                        string WHCode = string.Empty;
                        string IsLot = string.Empty;
                        if (_dtWH != null && _dtWH.Rows.Count > 0)
                        {
                            WHID = long.Parse(_dtWH.Rows[0]["ID"].ToString());
                            IsLot = _dtWH.Rows[0]["IsLot"].ToString();
                        }
                        else
                        {
                            rtnpo = new rtnChkInfo();
                            rtnpo.Success = false;
                            rtnpo.Message = "传入存储地点未在U9获取到有效的存储地点ID";
                            return rtnpo;
                        }
                        #endregion
                        chklineinfo.ItemInfo = new ItemInfo();
                        chklineinfo.ItemInfo.ItemID = ItemID;
                        chklineinfo.ItemInfo.ItemCode = line.InvCode;
                        chklineinfo.Wh_Code = line.WHCode;
                        chklineinfo.Org_Code = Info.WorkPoint;
                        if (IsLot == "True")
                        {
                            if (line.BatchCode == "")
                            {

                                rtnpo = new rtnChkInfo();
                                rtnpo.Success = false;
                                rtnpo.Message = "传入存储地点打开了批号管控,传入批号不能为空";
                                return rtnpo;
                            }
                            //string sqlLot = @"SELECT ID,LotCode FROM Lot_LotMaster WHERE item='{0}'  AND LotCode ='{1}'";
                            //sqlLot = string.Format(sqlLot, ItemID, line.BatchCode);
                            //DataTable dtLot = DBhlper.Query(sqlLot, Appconfig.GetU9ConnStr());
                            //if (dtLot.Rows.Count > 0)
                            //{
                                chklineinfo.LotCode = line.BatchCode;
                            //}
                            //else
                            //{
                            //    rtnpo = new rtnChkInfo();
                            //    rtnpo.Success = false;
                            //    rtnpo.Message = "传入料号："+ line.InvCode + "，批号:"+line.BatchCode+"未能在U9查到对应数据，请确认U9是否存在该批号!";
                            //    return rtnpo;
                            //}
                        }
                        if (line.Quantity >= 0)
                        {
                            chklineinfo.PlusQtyCU = line.Quantity;
                            chklineinfo.PlusQtySU = line.Quantity;
                            chklineinfo.MinusQtyCU = 0;
                            chklineinfo.MinusQtySU = 0;
                            chklineinfo.AdjustType = 0;
                        }
                        else
                        {
                            chklineinfo.PlusQtyCU = 0;
                            chklineinfo.PlusQtySU = 0;
                            chklineinfo.MinusQtyCU = line.Quantity*-1;
                            chklineinfo.MinusQtySU = line.Quantity*-1;
                            chklineinfo.AdjustType = 1;
                        }
                        chklinelist.Add(chklineinfo);
                    }
                }
                chkInfo.CheckDiffBilLineRData = chklinelist;
                chkInfoList.Add(chkInfo);
                string postJson = JsonConvert.SerializeObject(chkInfoList);
                rtnChkInfo value = new rtnChkInfo();
                value = PostJsonToCheckDiff(postJson, "admin", InfoList[0].WorkPoint);
                if (value.Success == true)
                {
                    List<Data> _datalist = new List<Data>();
                    string DocTypeName = string.Empty;
                    Data _data = new Data();
                    if (value != null)
                    {
                        List<DataLine> list = new List<DataLine>();
                        string Selsql = @" SELECT a.ID,a.DocNo as DocNo,a.CreatedBy as cMaker,a.CreatedOn as dnmaketime,a.ModifiedBy as cHandler
		                                ,a.ModifiedOn as dnverifytime,b.ID as DetailID,b.DocLineNo as Sequence,c.Code as InvCode,b.PlusQtySU as PlusQuantity
		                                ,b.MinusQtySU as MinusQuantity,E.Code AS WHCode,EE.Name AS WHName
		                                ,F.Code AS ProjectCode,0 AS Amount,G.LotCode AS cBatch,'' AS brand,
                                        '' cFree1,'' cFree2,'' cFree3,
                                        '' cFree4,'' cFree5,'' cFree6,
                                        '' cFree7,'' cFree8,'' cFree9,
                                        '' cFree10,'' LogId
                                        FROM InvDoc_CheckDiffBill a
                                        LEFT JOIN InvDoc_CheckDiffBillLine b ON b.CheckDiffBill=a.ID
                                        LEFT JOIN CBO_ItemMaster c ON c.ID=b.ItemInfo_ItemID
		                                LEFT JOIN CBO_Wh E ON E.ID=B.Wh
		                                LEFT JOIN CBO_Wh_Trl EE ON EE.ID=E.ID
		                                LEFT JOIN CBO_Project F ON F.ID=B.Project
		                                LEFT JOIN Lot_LotMaster G ON G.ID=B.LotInfo_LotMaster
		                                WHERE A.DocNo='" + value.DocNo + "' AND A.Org='" + OrgID + "'";
                        DataTable Seldt = DBhlper.Query(Selsql, Appconfig.GetU9ConnStr());
                        if (Seldt != null && Seldt.Rows.Count > 0)
                        {
                            foreach (DataRow item in Seldt.Rows)
                            {
                                DataLine _DataLine = new DataLine();
                                _data.ID = item["ID"].ToString();
                                _data.DocNo = item["DocNo"].ToString();
                                _data.cMaker = item["cMaker"].ToString();
                                _data.dnmaketime = Convert.ToDateTime(item["dnmaketime"].ToString());
                                _data.cHandler = item["cHandler"].ToString();
                                _data.dnverifytime = Convert.ToDateTime(item["dnverifytime"].ToString());

                                _DataLine.DetailID = item["DetailID"].ToString();
                                _DataLine.Sequence = Int32.Parse(item["Sequence"].ToString());
                                _DataLine.InvCode = item["InvCode"].ToString();
                                _DataLine.PlusQuantity = Decimal.Parse(item["PlusQuantity"].ToString());
                                _DataLine.MinusQuantity = Decimal.Parse(item["MinusQuantity"].ToString());
                                _DataLine.WHCode = item["WHCode"].ToString();
                                _DataLine.WHName = item["WHName"].ToString();
                                _DataLine.Amount = Convert.ToDecimal(item["Amount"].ToString());
                                _DataLine.ProjectCode = item["ProjectCode"].ToString();
                                _DataLine.cBatch = item["cBatch"].ToString();
                                _DataLine.brand = item["brand"].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();
                                _DataLine.LogId = item["LogId"].ToString();

                                list.Add(_DataLine);
                            }
                            _data.details = list;
                            _datalist.Add(_data);
                        }
                    }
                    rtnpo.DocNo = value.DocNo;
                    rtnpo.Success = true;
                    rtnpo.Data = _datalist;
                }
                else
                {
                    throw new Exception(value.Message);
                }
                strlog.AppendLine("返回数据:");
                strlog.AppendLine("单号:" + rtnpo.DocNo);
                strlog.AppendLine("结果:" + rtnpo.Success);
                strlog.AppendLine("返回消息:" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建盘点差异单");

                return rtnpo;
            }
            catch (Exception ex)
            {
                //异常信息捕获
                rtnChkInfo rtnpo = new rtnChkInfo();
                rtnpo.Success = false;
                rtnpo.Message = GetExceptionMessage(ex);

                StringBuilder strlog = new StringBuilder();
                strlog.AppendLine("创建盘点差异单");
                strlog.AppendLine("*****************************************************");
                foreach (var item in InfoList)
                {
                    strlog.AppendLine("组织编码:" + item.WorkPoint);
                    strlog.AppendLine("--------------------------------------------------");
                    foreach (var line in item.details)
                    {
                        strlog.AppendLine("物料编码:" + line.InvCode);
                        strlog.AppendLine("盘点仓库:" + line.WHCode);
                        strlog.AppendLine("批号:" + line.BatchCode);
                        strlog.AppendLine("盘点数量:" + line.Quantity);
                    }
                    strlog.AppendLine("--------------------------------------------------");

                }
                strlog.AppendLine("返回消息：" + rtnpo.Message);
                strlog.AppendLine("*****************************************************");
                Appconfig.WriteLogFile(strlog.ToString(), "创建盘点差异单");

                return rtnpo;
            }
            #endregion
        }
        public static rtnChkInfo PostJsonToCheckDiff(string DataJson, string CreateByCode, string ORGCode)
        {
            rtnChkInfo valueRet = new rtnChkInfo();
            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/CheckDiffBill/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")
                    {
                        CreateCheckDiffWebApiReturnModel RetModel = JsonConvert.DeserializeObject<CreateCheckDiffWebApiReturnModel>(resultCreateSoFile);
                        if (RetModel.Success == true &&
                            RetModel.Data != null && RetModel.Data.Count > 0)
                        {
                            var IsTrues = RetModel.Data.Where(a => a.IsSucess == false);
                            if (IsTrues != null && IsTrues.Count() > 0)
                            {

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

                                DocNo = RetModel.Data[0].Code;
                                ID = RetModel.Data[0].ID;
                                Message += "创建盘点差异单：" + DocNo + "成功。";
                                IsSucess = true;
                                #region 提交 盘点差异单
                                //List<SubmtiOrApproveCheckDiffModel> ListDoc = new List<SubmtiOrApproveCheckDiffModel>();
                                //SubmtiOrApproveCheckDiffModel subm = new SubmtiOrApproveCheckDiffModel();
                                //subm.ID = RetModel.Data[0].ID;
                                //subm.Code = RetModel.Data[0].Code;
                                //ListDoc.Add(subm);
                                //string postSubmitJson = JsonConvert.SerializeObject(ListDoc);

                                //TokenCode = GetToken(CreateByCode, ORGCode);

                                //string SubmitUrl = "http://{0}/u9c/webapi/CheckDiffBill/Submit";
                                //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")
                                //{
                                //    CreateCheckDiffWebApiReturnModel RetModel2 = JsonConvert.DeserializeObject<CreateCheckDiffWebApiReturnModel>(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)
                                //        {
                                //            Message += RetModel2.Data[0].ErrorMsg;
                                //        }
                                //        else
                                //        {

                                //            #region 审核 盘点差异单
                                //            List<SubmtiOrApproveCheckDiffModel> ListDoc3 = new List<SubmtiOrApproveCheckDiffModel>();
                                //            SubmtiOrApproveCheckDiffModel Apprm = new SubmtiOrApproveCheckDiffModel();
                                //            Apprm.ID = RetModel.Data[0].ID;
                                //            Apprm.Code = RetModel.Data[0].Code;
                                //            ListDoc3.Add(Apprm);
                                //            string postApproveJson = JsonConvert.SerializeObject(ListDoc3);

                                //            TokenCode = GetToken(CreateByCode, ORGCode);

                                //            string ApproveUrl = "http://{0}/u9c/webapi/CheckDiffBill/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")
                                //            {
                                //                CreateCheckDiffWebApiReturnModel RetModel3 = JsonConvert.DeserializeObject<CreateCheckDiffWebApiReturnModel>(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)
                                //                    {
                                //                        Message += RetModel3.Data[0].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();
                                //                }
                                //            }
                                //            #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<SubmtiOrApproveCheckDiffModel> ListDoc4 = new List<SubmtiOrApproveCheckDiffModel>();
                                    SubmtiOrApproveCheckDiffModel delm = new SubmtiOrApproveCheckDiffModel();
                                    delm.ID = RetModel.Data[0].ID;
                                    delm.Code = RetModel.Data[0].Code;
                                    ListDoc4.Add(delm);
                                    string postDelJson = JsonConvert.SerializeObject(ListDoc4);

                                    TokenCode = GetToken(CreateByCode, ORGCode);

                                    string DelUrl = "http://{0}/u9c/webapi/CheckDiffBill/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")
                                    {
                                        CreateCheckDiffWebApiReturnModel RetModel4 = JsonConvert.DeserializeObject<CreateCheckDiffWebApiReturnModel>(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)
                                            {
                                                Message += RetModel4.Data[0].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.Success = IsSucess;
                    valueRet.DocNo = DocNo;
                    valueRet.Message = Message;
                }
                else
                {
                    throw new Exception("获取token值失败。");
                }

            }
            catch (Exception ex)
            {
                Appconfig.WriteLogFile("Error：" + ex.ToString(), LogName);
                valueRet.Success = 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失败");
            }


        }

        #region 传入参数类
        public class CheckDiffInfo
        {

            private string _OrgCode;
            /// <summary>
            /// 传入组织编码
            /// </summary>
            public string WorkPoint
            {
                get { return _OrgCode; }
                set { _OrgCode = value; }
            }
            public List<CheckDiffLine> details { get; set; }
        }

        public class CheckDiffLine
        {
            public string InvCode { get; set; }
            public string WHCode { get; set; }

            public decimal Quantity { get; set; }

            public decimal Amount { get; set; }

            public string BatchCode { get; set; }

            public string LogId { get; set; }
        }
        #endregion

        #region 提取异常信息
        /// <summary>
        /// 提取异常信息
        /// </summary>
        /// <param name="ex"></param>
        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;
        }
        #endregion

        #region 给上下文信息赋值
        /// <summary>
        /// 给上下文信息赋值
        /// </summary>
        /// <returns></returns>
        private 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());
            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

        #region 返回信息类
        public class rtnChkInfo
        {
            public string DocNo { get; set; }
            public bool Success { get; set; }
            public string Message { get; set; }
            public List<Data> Data { get; set; }
        }

        public class Data
        {
            public string ID { get; set; }
            public string DocNo { get; set; }
            public string WHCode { get; set; }
            public string WHName { get; set; }
            public string cMaker { get; set; }
            public DateTime dnmaketime { get; set; }
            public string cHandler { get; set; }
            public DateTime dnverifytime { 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 PlusQuantity { get; set; }
            public Decimal MinusQuantity { get; set; }
            public string WHCode { get; set; }
            public string WHName { get; set; }
            public string ProjectCode { 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 string LogId { get; set; }
        }
        #endregion
    }

    #region 上下文类信息
    public class contextInfo
    {
        private long _OrgID;
        private string _OrgCode;
        private long _UserID;
        private string _UserCode;
        private DateTime _Datetime;
        private string _CultureName;
        private string _EnterpriseID;


        /// <summary>
        /// 组织ID
        /// </summary>
        public long OrgID
        {
            get { return _OrgID; }
            set { _OrgID = value; }
        }

        /// <summary>
        /// 组织编码
        /// </summary>
        public string WorkPoint
        {
            get { return _OrgCode; }
            set { _OrgCode = value; }
        }

        /// <summary>
        /// 操作员ID
        /// </summary>
        public long UserID
        {
            get { return _UserID; }
            set { _UserID = value; }
        }

        /// <summary>
        /// 操作员编码
        /// </summary>
        public string UserCode
        {
            get { return _UserCode; }
            set { _UserCode = value; }
        }

        /// <summary>
        /// 时间
        /// </summary>
        public DateTime Datetime
        {
            get { return _Datetime; }
            set { _Datetime = value; }
        }

        /// <summary>
        /// 语言
        /// </summary>
        public string CultureName
        {
            get { return _CultureName; }
            set { _CultureName = value; }
        }

        /// <summary>
        /// 企业ID号
        /// </summary>
        public string EnterpriseID
        {
            get { return _EnterpriseID; }
            set { _EnterpriseID = value; }
        }

        public contextInfo()
        {
            CultureName = "zh_CN";
            Datetime = DateTime.Now;
        }
    }
    #endregion


    #region 表体类
    //public class rCVLine
    //{
    //    /// <summary>
    //    ///  来源采购订单
    //    /// </summary>
    //    public string srcDocPONo { get; set; }

    //    private int _srcDocPOLineNo;
    //    private decimal _reqQty;
    //    public string WhCode { get; set; }

    //    /// <summary>
    //    /// 炉号
    //    /// </summary>
    //    public string FurnaceNo { get; set; }

    //    /// <summary>
    //    /// 数量
    //    /// </summary>
    //    public decimal ReqQty
    //    {
    //        get { return _reqQty; }
    //        set { _reqQty = value; }
    //    }

    //    /// <summary>
    //    /// 来源采购订单行
    //    /// </summary>
    //    public int srcDocPOLineNo
    //    {
    //        get { return _srcDocPOLineNo; }
    //        set { _srcDocPOLineNo = value; }
    //    }
    //}
    #endregion


}
