using Kingdee.CDP.WebApi.SDK;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RB_MES_API.Context;
using RB_MES_API.Models.Cloud;
using RB_MES_API.Models.Pangu;
using RB_MES_APICore.Models.Cloud;
using System.Drawing;
using System.Net;
using System.Text;

namespace RB_MES_API.Controllers
{
    /// <summary>
    /// 金蝶云API接口实现
    /// </summary>
    public class KDCloudHttpClient : IKDCloudHttpClient
    {
        private readonly IHttpClientFactory _httpClient;
        /// <summary>
        ///  Cookie，保证登录后，所有访问持有一个Cookie；
        /// </summary>
        public static CookieContainer cookie = new CookieContainer();
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="httpClient"></param>
        public KDCloudHttpClient(IHttpClientFactory httpClient)
        {
            _httpClient = httpClient;
        }

        /// <summary>
        /// Cloud身份认证
        /// </summary>
        /// <returns></returns>
        public async Task<bool> LoginErp()
        {
            string result = string.Empty;
            try
            {
                string acctid = ApiSettingsHelper.GetConfig("X-KDApi-AcctID");
                string username = LocalStaticRequest.GetSystemProfile(4, "TokenUserName");
                string passod = LocalStaticRequest.GetSystemProfile(4, "TokenPWD");
                int lcid = 0;
                int.TryParse(ApiSettingsHelper.GetConfig("X-KDApi-LCID"), out lcid);
                string apiurl = ApiSettingsHelper.GetConfig("X-KDApi-ServerUrl");
                //var tmpPwd = AESHelp.Encrypt("Aa123456..");
                //passod = tmpPwd;
                List<object> Parameters = new List<object>
                {
                    acctid,//帐套Id
                    username,//用户名
                    AESHelp.Decrypt(passod),//密码    //必须先通过解密
                    lcid
                };
                string _myurl = apiurl + "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc"; //登录地址       

                string content = JsonConvert.SerializeObject(Parameters);

                JObject jObj = new JObject
                {
                    { "format", 1 },
                    { "useragent", "ApiClient" },
                    { "rid", Guid.NewGuid().ToString().GetHashCode().ToString() },
                    { "parameters", content },
                    { "timestamp", DateTime.Now },
                    { "v", "1.0" }
                };
                string sContent = jObj.ToString();
                StringContent scontent = new StringContent(sContent, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.CreateClient("enpower").PostAsync(_myurl, scontent);
                result = await response.Content.ReadAsStringAsync();
                if (result.StartsWith("MsgCode:"))
                {
                    var resultJObject = JObject.Parse(result);
                    var loginstatus = resultJObject.SelectToken("$..MsgCode");
                    if (loginstatus != null)
                    {
                        if (loginstatus.Value<int>() == 1)
                        {
                            return false;
                        }
                    }
                }
                Uri uri = new Uri(_myurl);
                cookie.SetCookies(uri, JObject.Parse(result)["KDSVCSessionId"].ToString());
                int status = await Task.FromResult(JObject.Parse(result)["LoginResultType"]!.Value<int>());
                LocalStaticRequest.Islogin = status == 1 || status == 5 ? true : false;      //如果账号不是administrator就只能==1
            }
            catch (Exception ex)
            {
                LocalStaticRequest.Islogin = false;
                LogHelper.WriteLog(string.Format("Cloud身份认证的LoginErp发生错误：{0}", string.IsNullOrEmpty(result) ? ex.Message : result));
            }
            return LocalStaticRequest.Islogin;
        }
        /// <inheritdoc/>

        public async Task<string> AsyncClientRequest(string myurl, string content)
        {
            string result = string.Empty;
            try
            {
                JObject jObj = new JObject
                {
                    { "format", 1 },
                    { "useragent", "ApiClient" },
                    { "rid", Guid.NewGuid().ToString().GetHashCode().ToString() },
                    { "parameters", content },
                    { "timestamp", DateTime.Now },
                    { "v", "1.0" }
                };
                string sContent = jObj.ToString();
                StringContent scontent = new StringContent(sContent, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.CreateClient("enpower").PostAsync(myurl, scontent);
                result = await response.Content.ReadAsStringAsync();
                if (result.StartsWith("MsgCode:"))
                {
                    var resultJObject = JObject.Parse(result);
                    var loginstatus = resultJObject.SelectToken("$..MsgCode");
                    if (loginstatus != null)
                    {
                        if (loginstatus.Value<int>() == 1)
                        {
                            result = "-1";
                            LocalStaticRequest.Islogin = false;
                        }
                    }
                }
                result = await Task.FromResult(ValidateResult(result));
            }
            catch (Exception e)
            {
                LocalStaticRequest.Islogin = false;
                LogHelper.WriteLog(string.Format("HttpClient访问，.NET CORE推荐使用的AsyncClientRequest发生错误：{0}", string.IsNullOrEmpty(result) ? e.Message : result));
            }
            return result;
        }
        private static string ValidateResult(string responseText)
        {
            try
            {
                if (responseText.StartsWith("response_error:"))
                {
                    return responseText.TrimStart("response_error:".ToCharArray());
                }
            }
            catch (Exception)
            {
                throw;
            }
            return responseText;
        }

        /// <summary>
        /// 向MES系统推送数据
        /// </summary>
        /// <param name="inputdata">推送的JSON文本</param>
        /// <returns></returns>
        public async Task<PanguBreakJson> PushMesData(string inputdata)
        {
            PanguBreakJson breadJson = new PanguBreakJson() { Status = false };
            //string mesurl = _config.GetConnectionString("MesUrl");
            string mesurl = ApiSettingsHelper.GetConfig("MesUrl");
            mesurl += mesurl.Substring(mesurl.Length - 1, 1) == "/" ? "" : "/";         //如果最后一个字符不是"/"就添加上去
            mesurl += "updateimsdata";
            HttpWebRequest reqest = (HttpWebRequest)WebRequest.Create(mesurl);
            reqest.Timeout = 20 * 60 * 1000;
            reqest.Method = "POST";
            reqest.ContentType = "application/json";
            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(inputdata);
                reqest.ContentLength = bytes.Length;
                string result = string.Empty;
                reqest.GetRequestStream().Write(bytes, 0, bytes.Length);
                HttpWebResponse webResponse = (HttpWebResponse)await reqest.GetResponseAsync();
                //读取返回数据
                StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8);
                result = streamReader.ReadToEnd();
                streamReader.Dispose();
                webResponse.Dispose();

                breadJson = JsonConvert.DeserializeObject<PanguBreakJson>(result);
            }
            catch (Exception ex)
            {
                breadJson.Message = ex.Message;
            }
            return breadJson;
        }
        /// <inheritdoc/>
        public string SDKBillQuery(BillQuery query)
        {
            string json = JsonConvert.SerializeObject(query);
            return LocalStaticRequest.cloudApi.BillQuery(json);
        }
        public string SDKBatchSaveRequest(string formid, string data)
        {
            return LocalStaticRequest.cloudApi.BatchSave(formid, data);
        }

        public bool SDKRequestStatus(string resultJson)
        {
            var resultJObject = JObject.Parse(resultJson);
            var queryNode = resultJObject.SelectToken("$..IsSuccess");      //这里使用的是JsonPatch，是否异常固定在这个位置
            if (queryNode == null)
            {
                return true;
            }
            var isSuccess = queryNode.Value<bool>();
            return isSuccess;
        }

        public bool SDKBillQueryStatus(string resultJson)
        {
            bool isSuccess = false;
            if (string.IsNullOrEmpty(resultJson)) return isSuccess;
            try
            {
                JArray jArray = (JArray)JsonConvert.DeserializeObject(resultJson.ToString());
                if (jArray != null && jArray.Count > 0)
                {
                    isSuccess = true;
                }
            }
            catch (Exception)
            {

            }
            return isSuccess;
        }
    }
}
