using Hotline.Ai.Quality;
using RestSharp;
using Fw.Utility.UnifyResponse;
using Hotline.Share.Dtos.Quality;
using Hotline.CallCenter.Calls;
using Hotline.Orders;
using Newtonsoft.Json;
using System.Text;
using System.Security.Cryptography;
using Org.BouncyCastle.Tls;

namespace Hotline.Ai.Jths
{
    public class AiQualityService : IAiQualityService
    {
        private readonly RestClient _client;
        private readonly string _baseUrl;

        public AiQualityService(string baseUrl)
        {
            _client = new RestClient();
            _baseUrl = baseUrl;
        }
        public async Task<string> CreateAiOrderQualityTask(string filename, CancellationToken cancellationToken) { return ""; }


		public async Task CreateAiOrderQualityTask(
             string id,
             string audioFile,
             string fromNo,
             DateTime? callStartTime,
             string viteRecordPrefix,
             string ywlxString,
			 CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(audioFile)) return;
            var fileExtension = Path.GetExtension(audioFile);
            if (!string.IsNullOrEmpty(fileExtension) && fileExtension.StartsWith('.'))
                fileExtension = fileExtension.Substring(1);
            //var ywlx = !string.IsNullOrEmpty(ywlxString) ? ywlxString : model.Source.ToString();
            var agentChannel = "AiAnswered".Equals(ywlxString) ? "2" : "3";
			List <AiQualityDto> datalist = new List<AiQualityDto>();
            AiQualityDto aiQuality = new AiQualityDto
            {
                RecordID = id,
                RecordPath = viteRecordPrefix + audioFile,
                AgentID = "1001",
                CallNumber = fromNo,
                CallTime = callStartTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? string.Empty,
                RecordForm = fileExtension,//recordForm,
                ywlx = ywlxString,
                AgentChannel = agentChannel
			};
            datalist.Add(aiQuality);
            var data = JsonConvert.SerializeObject(datalist);
            var baseUrl = new Uri(_baseUrl);
            await ExecuteAsync(baseUrl.ToString() + "routeinfo/api", Method.Post, data, cancellationToken);
        }

        public async Task<ApiResponse<TResponse>> ExecuteAsync<TRequest, TResponse>(string path, Method httpMethod,
            TRequest request, CancellationToken cancellationToken)
            where TRequest : class
        {
            var req = new RestRequest(path, httpMethod);
            if (httpMethod is Method.Get)
            {
                req.AddObject(request);
            }
            else
            {
                req.AddJsonBody(request);
            }

            try
            {
                var response = await _client.ExecuteAsync<ApiResponse<TResponse>>(req, cancellationToken);
                return response.Data;
            }
            catch (Exception e)
            {
                throw new HttpRequestException($"智能质检平台错误，Error: {e.Message}");
            }
        }

        public async Task<ApiResponse> ExecuteAsync<TRequest>(string path, Method httpMethod, TRequest request,
            CancellationToken cancellationToken)
            where TRequest : class
        {
            var req = new RestRequest(path, httpMethod);
            req.AddHeader("content-type", "application/json");
            req.AddHeader("token", "");
            req.AddHeader("version", "V1.0");
            var sign = MD5Encrypt(request.ToString());
            req.AddHeader("sign", sign);
            req.AddHeader("signType", "md5");
            req.AddHeader("appkey", "MTAwMDAx");
            if (httpMethod is Method.Get)
            {
                req.AddObject(request);
            }
            else
            {
                req.AddJsonBody(request);
            }

            try
            {
                var response = await _client.ExecuteAsync<ApiResponse>(req, cancellationToken);
                return response.Data;
            }
            catch (Exception e)
            {
                throw new HttpRequestException($"智能质检平台错误，Error: {e.Message}");
            }
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <returns></returns>
        private static string MD5Encrypt(string? input)
        {
            using var md5 = MD5.Create();
            var t = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
            var sb = new StringBuilder(32);
            for (var i = 0; i < t.Length; i++)
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            return sb.ToString();
        }

        private static string Base64En(string? model)
        {
            var bytes = Encoding.UTF8.GetBytes(model);
            return Convert.ToBase64String(bytes);
        }
    }
}
