using JiaZhiQuan.Common.Config;
using JiaZhiQuan.Common.Utils;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Wicture.DbRESTFul;
using static JiaZhiQuan.Common.YCTech.YCTechModel;

namespace JiaZhiQuan.Common.YCTech {
    public static class YCTechCommon {
        internal static async Task<YCTechBaseResponse<TData>> YCTechExeReqeust<TData>(this YCTechBaseRequest<TData> request,
            ConfigFromDb config, HttpClient httpClient) {
            request.InitRequest(config);
            IDictionary<string, object> reqParam = ExpandoUtils.ConvertToDynamic(request);
            reqParam.Add("AgentId", request.BaseInfo.AgentId);
            reqParam.Add("SignKey", request.BaseInfo.SignKey);
            //排序
            IDictionary<string, object> sortParam = reqParam.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
            StringBuilder sb = new StringBuilder();
            int i = 0;
            foreach (var x in sortParam) {
                if (x.Key == "BaseInfo" || x.Key == "Response" || x.Value == null ||
                    string.IsNullOrEmpty(x.Value.ToString())) {
                } else {
                    sb.Append(i == 0 ? string.Empty : "&").Append($"{x.Key}={x.Value}");
                }
                i++;
            }
            string sign = EncryptUtils.Md5EncryptTolower(sb.ToString());
            string paramStr = $"{sb}&Sign={sign}";
            string url = request.BaseInfo.Host + request.BaseInfo.RequestUrl;
            LoggerManager.Logger.Info($"请求url:{url} 请求参数:{paramStr}");
            YCTechBaseResponse<TData> resp = new YCTechBaseResponse<TData>();
            try {
                var content = new StringContent(paramStr, Encoding.UTF8, "application/x-www-form-urlencoded");
                var response = await httpClient.PostAsync(url, content);
                if (response.IsSuccessStatusCode) {
                    string responseContent = await response.Content.ReadAsStringAsync();
                    resp = JsonConvert.DeserializeObject<YCTechBaseResponse<TData>>(responseContent);
                    resp.Sucess = true;
                } else {
                    LoggerManager.Logger.Error($"调用于初科技接口失败，url:{url} resp: {response}");
                    resp = new YCTechBaseResponse<TData> {
                        Code = "-99",
                        raw = await response.Content.ReadAsStringAsync()
                    };
                }
                return resp;
            } catch (Exception ex) {
                LoggerManager.Logger.Error($"调用于初科技接口失败，url:{url}  msg: {ex.Message}");
                return resp;
            }
        }

        private static void InitRequest<TData>(this YCTechBaseRequest<TData> request,ConfigFromDb config) {
            request.BaseInfo.SignKey = config.YCTechSignKey;
            request.BaseInfo.AgentId= config.YCTechAgentId;
            request.BaseInfo.Host= config.YCTechHost;
        }
    }
}
