using DocumentFormat.OpenXml.Math;
using Infrastructure;
using Infrastructure.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis.Text;
using Newtonsoft.Json;
using OpenAuth.App.ServiceApp.Request;
using OpenAuth.Repository.Domain;
using OpenAuth.WebApi.Model.RabbitMQService;
using RabbitMQ.Client;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
    /// <summary>
    /// 大华ai接口
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DaHuaAiController : ControllerBase
    {
        private readonly string ak = "e3d019924e7f40089bcffba4";
        private readonly string sk = "cf83a12caa155b994eb34fa9";
        private readonly string baseUrl = "https://123.132.248.154:6405";
        private readonly RabbitMqListenerService _listener;
        public DaHuaAiController(RabbitMqListenerService listener)
        {
            _listener = listener;
        }
        private async Task<Response<string>> PostJsonAsync(string path, object body)
        {
            var handler = new HttpClientHandler
            {
                // 忽略服务器证书
                ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
            };

            var headers = DHHeaderUtil.BuildHeader(ak, sk, "POST", path);
            var url = $"{baseUrl}{path}";

            using var httpClient = new HttpClient(handler);

            foreach (var kv in headers)
            {
                httpClient.DefaultRequestHeaders.Add(kv.Key, kv.Value);
            }

            var jsonBody = JsonConvert.SerializeObject(body ?? new { });
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            try
            {
                var response = await httpClient.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                return new Response<string> { Result = responseContent };
            }
            catch (Exception ex)
            {
                return new Response<string> { Result = ex.Message };
            }
        }
        /// <summary>
        /// 分页查询车辆分析
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<Response<string>> GetTasksList(int page, int limit)
        {
            return PostJsonAsync($"/processing/analysis/vehicle/tasks?start={page}&limit={limit}", new
            {
                channelIds = new[] { "sdhc" }
            });
        }

        [HttpPost]
        [AllowAnonymous]
        [Obsolete]
        public async Task<Response<string>> GetTasksList1(int page, int limit)
        {
            var handler = new HttpClientHandler();
            // 忽略服务器证书
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            // 假设 DHHeaderUtil 返回 Dictionary<string, string>
            string ak = "e3d019924e7f40089bcffba4";
            string sk = "cf83a12caa155b994eb34fa9";
            var headers = DHHeaderUtil.BuildHeader(ak, sk, "POST", $"/processing/analysis/vehicle/tasks?start={page}&limit={limit}");
            // 要请求的 URL
            var url = $"https://123.132.248.154:6405/processing/analysis/vehicle/tasks?start={page}&limit={limit}";
            // 请求体（JSON）
            var data = new
            {
                channelIds = new[]
                {
                    "sdhc"
                }
            };
            var jsonBody = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            using var httpClient = new HttpClient(handler);
            // 添加请求头
            // 只把非 Content-Type 的头加到 request
            foreach (var kv in headers)
            {
                if (kv.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))
                    continue;
                httpClient.DefaultRequestHeaders.Add(kv.Key, kv.Value);
            }
            // 创建 HttpContent
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");
            try
            {
                var response = await httpClient.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();
                return new Response<string>()
                {
                    Result = responseContent
                };
            }
            catch (Exception ex)
            {
                return new Response<string>()
                {
                    Result = ex.Message
                };
            }
        }
        /// <summary>
        /// 获取算法列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<Response<string>> GetsupportList(int page, int limit)
        {
            return PostJsonAsync($"/processing/engine/algorithms/support?currentPage={page}&pageSize={limit}", new { });
        }
        /// <summary>
        /// 查询算法参数描述文件接口
        /// </summary>
        /// <param name="version"></param>
        /// <param name="functionType"></param>
        /// <param name="algorithmCode"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<Response<string>> Getconfig(string version, int functionType, string algorithmCode)
        {
            return PostJsonAsync("/processing/engine/algorithms/isd/config/get", new
            {
                version,
                functionType,
                algorithmCode
            });
        }
        /// <summary>
        /// 创建行为场景分析任务
        /// </summary>
        /// <param name="data">参数详见文档7.1.3.3. 创建行为场景分析任务</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> CreateTasks(DaHuaTaskInfo data)
        {
            await _listener.AddQueueBindingAsync("processing_event", "topic", $"event.behaviorAlarm.1.{data.channelId}");
            return await PostJsonAsync("/processing/behavior/realtime/tasks", data);
        }
        /// <summary>
        /// 模拟添加队列
        /// </summary>
        /// <param name="channelId"></param>
        [HttpPost]
        [AllowAnonymous]
        public async void AddQueueBinding(string channelId)
        {
            await _listener.AddQueueBindingAsync("processing_event", "topic", $"event.trafficJunction.1.{channelId}");
        }
        /// <summary>
        /// 删除行为场景分析任务
        /// </summary>
        /// <param name="taskId">行为场景分析任务id</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<Response<string>> DeleteTasks(string taskId)
        {
            return PostJsonAsync($"/processing/behavior/realtime/tasks/{taskId}", new { });
        }
        /// <summary>
        /// 查看场景认知通用分析任务列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="analysisType">分析类型，仅支持0：智能分析</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<Response<string>> GetTasks(int page, int limit, int analysisType)
        {
            return PostJsonAsync($"/processing/behavior/realtime/tasks?currentPage={page}&pageSize={limit}&analysisType={analysisType}", new { });
        }
        /// <summary>
        /// 获取智能流播放地址
        /// </summary>
        /// <param name="id">taskId</param>
        /// <param name="streamType">智能流类型，当前仅支持2: 行为</param>
        /// <param name="type">行为场景智能流仅支持type=1</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public Task<Response<string>> GetChannel(string id, int streamType, int type)
        {
            return PostJsonAsync($"/processing/inner/play/channel/{id}?streamType={streamType}&type={type}", new { });
        }
    }
}
