using ICS.WCF.Base;
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.Text;
using System.Threading.Tasks;

namespace UFIDA.U9.Cust.ApproveLendBackTrans
{
    public class ApproveLendBackTransSrv
    {
        public Result ApproveLendBackTrans(List<ICSReturnInDocApprove> Infos)
        {
            var res = new Result();
            var datalist = new List<ICSReturnInDocApprove>();
            foreach (var info in Infos)
            {
                try
                {
                    string sql = "select COUNT(*) Qty from InvDoc_LendBackLine where LendBackTrans ='" + info.ID + "'";
                    DataTable dt = DBhlper.Query(sql, Appconfig.GetU9ConnStr());
                    var LineCount = int.Parse(dt.Rows[0]["Qty"].ToString());
                    if (LineCount == 0)
                    {
                        throw new Exception("归还单ID不存在");
                    }

                    if (info.details == null)
                    {
                        throw new Exception("明细行数为0");
                    }

                    if (LineCount != info.details.Count)
                    {
                        throw new Exception("明细行数与单据行数不一致");
                    }

                    res = PostToOpenAPI(SetData(info.ID), info.WorkPoint,info.User);

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

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

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

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

        private string SetData(string ID)
        {
            var DataList = new List<ApproveLendBackTransPostModel>();

            DataList.Add(new ApproveLendBackTransPostModel
            {
                ID = long.Parse(ID)
            });
            return JsonConvert.SerializeObject(DataList);
        }

        private Result PostToOpenAPI(string JsonPost, string OrgCode,string UserCode)
        {
            var res = new Result();

            try
            {
                //获取授权
                string url = "http://{2}/u9c/webapi/OAuth2/GetAuthorizeCode?clientid={0}&clientsecret={1}";
                url = string.Format(url, ConfigurationManager.AppSettings["clientid"].ToString(), ConfigurationManager.AppSettings["clientsecret"].ToString(), ConfigurationManager.AppSettings["U9IP"].ToString());
                string resultuu = PostData.GetInfo("", url);

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

                JObject objuu = JObject.Parse(resultuu);

                if (objuu["Success"].ToString().ToUpper() == "TRUE")
                {
                    string keyCode = objuu["Data"].ToString();
                    //获取Token
                    string ToeknUrl = "http://{4}/u9c/webapi/OAuth2/Login?userCode={0}&entcode={1}&orgcode={2}&code={3}";
                    ToeknUrl = string.Format(ToeknUrl, UserCode, ConfigurationManager.AppSettings["enterpriseID"].ToString(), OrgCode, keyCode, ConfigurationManager.AppSettings["U9IP"].ToString());
                    string resultToken = PostData.GetInfo("", ToeknUrl);

                    Appconfig.WriteLogFile("Token返回Json：" + resultToken, "归还");

                    objuu = JObject.Parse(resultToken);

                    if (objuu["Success"].ToString().ToUpper() == "TRUE")
                    {
                        string TokenCode = objuu["Data"].ToString();
                        //创建单据
                        string Url = "http://{0}/u9c/webapi/LendBackTrans/Approve";
                        Url = string.Format(Url, ConfigurationManager.AppSettings["U9IP"].ToString());


                        string File = PostData.APT(Url, JsonPost, TokenCode);

                        Appconfig.WriteLogFile("操作单据返回Json：" + File, "归还");

                        objuu = JObject.Parse(File);

                        if (objuu["Success"].ToString().ToUpper() != "TRUE")
                        {
                            throw new Exception("调用OpenAPI操作单据失败：" + objuu["ResMsg"].ToString());
                        }
                        else
                        {

                            foreach (JObject item in objuu["Data"])
                            {
                                if (item["IsSucess"].ToString().ToUpper() == "TRUE")
                                {
                                    res.Success = true;
                                    res.Message = "成功";
                                }
                                else
                                {
                                    throw new Exception("操作推送数据到U9API失败：" + item["ErrorMsg"].ToString());
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("获取Token失败：" + objuu["ResMsg"].ToString());
                    }
                }
                else
                {
                    throw new Exception("获取授权失败：" + objuu["ResMsg"].ToString());
                }
            }
            catch (Exception ex)
            {
                res.Success = false;
                res.Message = ex.Message;
            }


            return res;
        }
    }

    public class ICSReturnInDocApprove
    {
        public string User { get; set; }
        public string WorkPoint { get; set; }
        public string ID { get; set; }
        public string DocNO { get; set; }
        public DateTime MTime { get; set; }

        public bool IsSuccess { get; set; }

        public string Message { get; set; }
        public List<ICSReturnInDocLineApprove> details { get; set; }
    }

    public class ICSReturnInDocLineApprove
    {
        public string DetailID { get; set; }
        public string Sequence { get; set; }
        public string LogIds { get; set; }
        public bool IsSuccess { get; set; }

        public string Message { get; set; }
    }

    public class ApproveLendBackTransPostModel
    {
        public long ID { get; set; }
    }
}
