using OpenAuth.App.BaseApp.Base;
using OpenAuth.Repository.Domain;
using OpenAuth.Repository;
using System.Text;
using OpenAuth.App.Interface;
using SqlSugar;
using Infrastructure;
using Infrastructure.Helpers;
using System.Text.Json;
using OpenAuth.App.ServiceApp.Response;
using Microsoft.Extensions.Configuration;
using OpenAuth.App.ServiceApp.DroneDocking.Request;
using DocumentFormat.OpenXml.Office.CustomUI;
using DocumentFormat.OpenXml.EMMA;
using OpenAuth.App.ServiceApp.DroneDocking.Response;
using DocumentFormat.OpenXml.Math;
using static Microsoft.Extensions.Logging.EventSource.LoggingEventSource;
using DocumentFormat.OpenXml.Drawing.Charts;
using Org.BouncyCastle.Ocsp;
using System.Net.Http.Headers;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;


namespace OpenAuth.App.ServiceApp.DroneDocking
{
    public class DroneDockApp : SqlSugarBaseApp<DroneDocktask, SugarDbContext>
    {
        private EncryptionHelper _helper;
        private IConfiguration configuration;
        public DroneDockApp(EncryptionHelper helper, IConfiguration configuration, ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<DroneDocktask> repository, IAuth auth) : base(unitWork, repository, auth)
        {
            _helper = helper;
            this.configuration = configuration;
        }

        /// <summary>
        /// 无人机机场接口注册更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Response<string>> RegistService(AirPortRegistReq req )
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = configuration.GetSection("DroneDocking:Url").Value + "/droneAirport/RegistService";
                    string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = _helper.GetToken(centercode);

                    // 序列化为 JSON 字符串
                    string json = JsonSerializer.Serialize(req);

                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);

                    var encryptedData = _helper.Encrypt(bytes);
                    // 创建请求体
                    var httpContent = new StringContent(encryptedData, Encoding.UTF8, "application/json");

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-secret", x_lc_secret);
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);

                    //发送请求
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }

        /// <summary>
        /// 无人机机场设备注册/更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Response<string>> AddDevice(AddDeviceReq req)
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = configuration.GetSection("DroneDocking:Url").Value+ "/droneAirport/addDevice";
                    string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = _helper.GetToken(centercode);

                    // 序列化为 JSON 字符串
                    string json = JsonSerializer.Serialize(req);

                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);

                    var encryptedData = _helper.Encrypt(bytes);
                    // 创建请求体
                    var httpContent = new StringContent(encryptedData, Encoding.UTF8, "application/json");

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-secret", x_lc_secret);
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);

                    //发送请求
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }

        /// <summary>
        /// 无人机机场授权
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Response<string>> Authorization(AuthorizationReq req)
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = configuration.GetSection("DroneDocking:Url").Value + "/droneAirport/authorization";
                    string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = _helper.GetToken(centercode);

                    // 序列化为 JSON 字符串
                    string json = JsonSerializer.Serialize(req);

                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);

                    var encryptedData = _helper.Encrypt(bytes);
                    // 创建请求体
                    var httpContent = new StringContent(encryptedData, Encoding.UTF8, "application/json");

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-secret", x_lc_secret);
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);

                    //发送请求
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }

        /// <summary>
        /// 无人机机场授权
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Response<string>> Test(AirPortUpdateTaskReq req)
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = "http://localhost:10042/zhcfzx/droneAirport/updateTask";
                    string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = "API32_HENJOZMPBYKEXNVLFMY3Y5W5SQ.1751622229582.fmCjIucQYyq4YZe4CnSStN/rHcwjZTxUsDuXeXJfrYn0bwoaV1/IW8mcFwtLw8JHjowvMJrmPyy/QZAhssxQCQ==";

                    // 序列化为 JSON 字符串
                    string json = JsonSerializer.Serialize(req);

                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);

                    var encryptedData = _helper.Encrypt(bytes);
                    // 创建请求体
                    var httpContent = new StringContent(encryptedData, Encoding.UTF8, "application/json");

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-secret", x_lc_secret);
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);

                    //发送请求
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }

        public async Task<Response<string>> Test1(string taskid)
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = $"http://localhost:10042/zhcfzx/droneAirport/cancelTask?taskid={taskid}";
                    //string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = "API32_HENJOZMPBYKEXNVLFMY3Y5W5SQ.1751622229582.fmCjIucQYyq4YZe4CnSStN/rHcwjZTxUsDuXeXJfrYn0bwoaV1/IW8mcFwtLw8JHjowvMJrmPyy/QZAhssxQCQ==";

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);

                    //发送请求
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }

        /// <summary>
        /// 无人机任务添加
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<ResData> AddTask(string req,string secret)
        {
            ResData Response = new ResData();

            //解密数据
            byte[] secretbyte = Convert.FromBase64String(secret);   //x-lc-secret
            byte[] reqbyte = Convert.FromBase64String(req);    //返回数据
            string data = _helper.Decrypt(secretbyte, reqbyte);

            //序列化返回数据并处理
            var task = JsonSerializer.Deserialize<AirPortTaskReq>(data);

            string ids = "";
            foreach(var item in task.deviceid)
            {

            }
            
            //task数据生成
            DroneDocktask dt= new DroneDocktask();
            dt.id=Guid.NewGuid().ToString();
            dt.deviceid= string.Join(",", task.deviceid);
            dt.bizidname=task.bizidname.ToString();
            dt.taskid = task.taskid;
            dt.taskname = task.taskname;
            dt.datacode= task.datacode;
            dt.state = 0;
            dt.createtime = DateTime.Now;

            //taskdetail数据生成
            List<DroneDocktaskdetail> dalist= new List<DroneDocktaskdetail>();
            if (task.tasklist.Count > 0 )
            {
                foreach(var item in task.tasklist)
                {
                    DroneDocktaskdetail da= new DroneDocktaskdetail();
                    da.id = Guid.NewGuid().ToString();
                    da.taskid = dt.id;
                    da.bz=item.bz;
                    da.dkbh=item.dkbh;
                    da.dkfw=item.dkfw;
                    da.dkmj=item.dkmj;
                    da.dkmc=item.dkmc;
                    da.xzqdm=item.xzqdm;
                    da.zdkbh=item.zdkbh;
                    da.bsm=item.bsm;
                    da.dklx=item.dklx;
                    dalist.Add(da);
                }
            }

            using (var uow = base.UnitWork.CreateContext())
            {
                //查询数据  检查是否有重复数据
                var info = uow.DroneDocktask.AsQueryable().Where(r => r.taskid == task.taskid).First();
                if (info != null)
                {
                    //本地数据库数据添加
                    await uow.DroneDocktask.InsertAsync(dt);
                    await uow.DroneDocktaskdetail.InsertRangeAsync(dalist);
                    var flag = uow.Commit();

                    //返回数据
                    if (flag)
                    {
                        string x_lc_secret = _helper.getxseret();
                        // 转换为字节数组
                        byte[] bytes = Encoding.UTF8.GetBytes(dt.taskid);
                        var encryptedResData = _helper.Encrypt(bytes);
                        Response.Result = encryptedResData;
                        Response.Message = "无人机机场任务添加成功";
                        Response.Code = 200;
                        Response.Secret = x_lc_secret;
                        return Response;
                    }
                    else
                    {
                        string x_lc_secret = _helper.getxseret();
                        // 转换为字节数组
                        byte[] bytes = Encoding.UTF8.GetBytes(" ");

                        var encryptedResData = _helper.Encrypt(bytes);
                        Response.Result = encryptedResData;
                        Response.Message = "无人机机场任务添加失败";
                        Response.Code = 500;
                        Response.Secret = x_lc_secret;
                        return Response;
                    }
                }
                else
                {
                    string x_lc_secret = _helper.getxseret();
                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(" ");

                    var encryptedResData = _helper.Encrypt(bytes);
                    Response.Result = encryptedResData;
                    Response.Message = "已存在相同taskid任务";
                    Response.Code = 500;
                    Response.Secret = x_lc_secret;
                    return Response;
                }  
            } 
        }


        /// <summary>
        /// 无人机任务更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<ResData> UpdateTask(string req, string secret)
        {
            ResData Response = new ResData();

            //解密数据
            byte[] secretbyte = Convert.FromBase64String(secret);   //x-lc-secret
            byte[] reqbyte = Convert.FromBase64String(req);    //返回数据
            string data = _helper.Decrypt(secretbyte, reqbyte);

            //序列化返回数据并处理
            var task = JsonSerializer.Deserialize<AirPortUpdateTaskReq>(data);

            using (var uow = base.UnitWork.CreateContext())
            {
                //查询数据
                var info=uow.DroneDocktask.AsQueryable().Where(r=>r.taskid==task.taskid).First();
                if (info != null) 
                {
                    if (info.state == 0)
                    {
                        //taskdetail数据生成
                        List<DroneDocktaskdetail> dalist = new List<DroneDocktaskdetail>();
                        if (task.tasklist.Count > 0)
                        {
                            foreach (var item in task.tasklist)
                            {
                                DroneDocktaskdetail da = new DroneDocktaskdetail();
                                da.id = Guid.NewGuid().ToString();
                                da.taskid = info.id;
                                da.bz = item.bz;
                                da.dkbh = item.dkbh;
                                da.dkfw = item.dkfw;
                                da.dkmj = item.dkmj;
                                da.dkmc = item.dkmc;
                                da.xzqdm = item.xzqdm;
                                da.zdkbh = item.zdkbh;
                                da.bsm = item.bsm;
                                da.dklx = item.dklx;
                                dalist.Add(da);
                            }
                        }
                        await uow.DroneDocktaskdetail.DeleteAsync(r => r.taskid == info.taskid);
                        await uow.DroneDocktaskdetail.InsertRangeAsync(dalist);
                        var flag = uow.Commit();

                        //返回数据
                        if (flag)
                        {
                            string x_lc_secret = _helper.getxseret();
                            // 转换为字节数组
                            byte[] bytes = Encoding.UTF8.GetBytes(info.taskid);
                            var encryptedResData = _helper.Encrypt(bytes);
                            Response.Result = encryptedResData;
                            Response.Message = "无人机机场任务更新成功";
                            Response.Code = 200;
                            Response.Secret = x_lc_secret;
                            return Response;
                        }
                        else
                        {
                            string x_lc_secret = _helper.getxseret();
                            // 转换为字节数组
                            byte[] bytes = Encoding.UTF8.GetBytes(" ");

                            var encryptedResData = _helper.Encrypt(bytes);
                            Response.Result = encryptedResData;
                            Response.Message = "无人机机场任务更新失败";
                            Response.Code = 500;
                            Response.Secret = x_lc_secret;
                            return Response;
                        }
                    }
                    else
                    {
                        string x_lc_secret = _helper.getxseret();
                        // 转换为字节数组
                        byte[] bytes = Encoding.UTF8.GetBytes(" ");

                        var encryptedResData = _helper.Encrypt(bytes);
                        Response.Result = encryptedResData;
                        Response.Message = "任务已开始执行，无法更新，请重新添加任务";
                        Response.Code = 500;
                        Response.Secret = x_lc_secret;
                        return Response;
                    }
                }
                else
                {
                    string x_lc_secret = _helper.getxseret();
                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(" ");

                    var encryptedResData = _helper.Encrypt(bytes);
                    Response.Result = encryptedResData;
                    Response.Message = "未找到任务数据";
                    Response.Code = 500;
                    Response.Secret = x_lc_secret;
                    return Response;
                }     
            }
        }

        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<ResData> CancelTask(string taskid)
        {
            ResData Response = new ResData();

            using (var uow = base.UnitWork.CreateContext())
            {
                //查询数据
                var info = uow.DroneDocktask.AsQueryable().Where(r => r.taskid == taskid).First();
                if (info != null)
                {
                    var flag = await uow.DroneDocktask.UpdateAsync(it => new DroneDocktask()
                    {
                        state=3
                    }, it => it.id == info.id);

                    //返回数据
                    if (uow.Commit())
                    {
                        string x_lc_secret = _helper.getxseret();
                        // 转换为字节数组
                        byte[] bytes = Encoding.UTF8.GetBytes(info.taskid);
                        var encryptedResData = _helper.Encrypt(bytes);
                        Response.Result = encryptedResData;
                        Response.Message = "无人机机场任务取消成功";
                        Response.Code = 200;
                        Response.Secret = x_lc_secret;
                        return Response;
                    }
                    else
                    {
                        string x_lc_secret = _helper.getxseret();
                        // 转换为字节数组
                        byte[] bytes = Encoding.UTF8.GetBytes(" ");

                        var encryptedResData = _helper.Encrypt(bytes);
                        Response.Result = encryptedResData;
                        Response.Message = "无人机机场任务取消失败";
                        Response.Code = 500;
                        Response.Secret = x_lc_secret;
                        return Response;
                    }   
                }
                else
                {
                    string x_lc_secret = _helper.getxseret();
                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(" ");

                    var encryptedResData = _helper.Encrypt(bytes);
                    Response.Result = encryptedResData;
                    Response.Message = "未找到任务数据";
                    Response.Code = 500;
                    Response.Secret = x_lc_secret;
                    return Response;
                }
            }
        }

        /// <summary>
        /// 无人机状态获取
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<ResData> getDroneStatus(string deviceid)
        {
            ResData Response = new ResData();
            string data = "{\r\n\"code\": 200,\r\n\"data\": {\r\n\"mode_code\":0,\r\n\"longitude\":122.45,\r\n\"latitude\":30.45,\r\n\"height\":80,\r\n\"elevation\":50,\r\n\"gimbal_pitch\":-45,\r\n\"gimbal_yaw\":23,\r\n\"battery_capacity_percent\":35,\r\n\"gps_state\":2,\r\n},\r\n\"message\": \"获取无人机机场状态成功！\",\r\n\"traceid\": \"xxx\"\r\n}";
            //todo deviceid
            if (true)
            {
                string x_lc_secret = _helper.getxseret();
                // 转换为字节数组
                byte[] bytes = Encoding.UTF8.GetBytes(data);
                var encryptedResData = _helper.Encrypt(bytes);
                Response.Result = encryptedResData;
                Response.Message = "获取无人机机场状态成功！";
                Response.Code = 200;
                Response.Secret = x_lc_secret;
                return Response;
            }
            else
            {
                string x_lc_secret = _helper.getxseret();
                // 转换为字节数组
                byte[] bytes = Encoding.UTF8.GetBytes(" ");

                var encryptedResData = _helper.Encrypt(bytes);
                Response.Result = encryptedResData;
                Response.Message = "获取无人机机场状态失败！";
                Response.Code = 500;
                Response.Secret = x_lc_secret;
                return Response;
            }

        }
        /// <summary>
        /// 无人机任务查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<ResData> queryTaskStatus(string req, string secret)
        {
            ResData Response = new ResData();

            //解密数据
            byte[] secretbyte = Convert.FromBase64String(secret);   //x-lc-secret
            byte[] reqbyte = Convert.FromBase64String(req);    //返回数据
            string data = _helper.Decrypt(secretbyte, reqbyte);

            //序列化返回数据并处理
            var task = JsonSerializer.Deserialize<AirPortTaskReq>(data);
            string sql = "select * from drone_docktask where taskid=" + data;


            string x_lc_secret = _helper.getxseret();
            // 转换为字节数组
            byte[] bytes = Encoding.UTF8.GetBytes(sql);
            var encryptedResData = _helper.Encrypt(bytes);
            Response.Result = encryptedResData;
            Response.Message = "查询无人机机场任务状态成功！";
            Response.Code = 200;
            Response.Secret = x_lc_secret;
            return Response;


        }
        /// <summary>
        /// 无人机机场设备注册/更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Response<string>> reportDroneStatus(List<AirPortStatusApply> req)
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = configuration.GetSection("DroneDocking:Url").Value + "/droneAirport/reportDroneStatus";
                    string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = _helper.GetToken(centercode);

                    // 序列化为 JSON 字符串
                    string json = JsonSerializer.Serialize(req);

                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);

                    var encryptedData = _helper.Encrypt(bytes);
                    // 创建请求体
                    var httpContent = new StringContent(encryptedData, Encoding.UTF8, "application/json");

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-secret", x_lc_secret);
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);

                    //发送请求
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }


        /// <summary>
        /// 获取临时上传地址
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Response<string>> getUploadFilePath(AirPortUploadReq req)
        {
            Response<string> Response = new Response<string>();

            var handler = new HttpClientHandler();
            // 如果需要忽略服务器证书错误（仅测试环境）
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            using (var client = new HttpClient())
            {
                try
                {
                    string url = configuration.GetSection("DroneDocking:Url").Value + "/DataExchange/getUploadFilePath";
                    string x_lc_secret = _helper.getxseret();
                    string centercode = "UAV32_LJY2FPMYDE6UDES3P3ZD7V3IKQ";
                    string x_token = _helper.GetToken(centercode);

                    // 序列化为 JSON 字符串
                    string json = JsonSerializer.Serialize(req);

                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);

                    var encryptedData = _helper.Encrypt(bytes);
                    // 创建请求体
                    var httpContent = new StringContent(encryptedData, Encoding.UTF8, "application/json");

                    // 添加请求头
                    client.DefaultRequestHeaders.Add("x-lc-secret", x_lc_secret);
                    client.DefaultRequestHeaders.Add("x-lc-token", x_token);
                    client.DefaultRequestHeaders.Add("x-lc-datacode", "AirportData");

                    //发送请求
                    HttpResponseMessage response = await client.PostAsync(url, httpContent);
                    response.EnsureSuccessStatusCode();

                    // 获取响应头中的 x_cl_screte 参数
                    string resx_cl_screte = GetHeaderValue(response, "x-lc-secret");

                    // 读取响应内容并反序列化
                    string responseBody = await response.Content.ReadAsStringAsync();
                    var result = JsonSerializer.Deserialize<ReciveData<string>>(responseBody);

                    //解密数据
                    byte[] resbytesx = Convert.FromBase64String(resx_cl_screte);
                    byte[] resdatabytes = Convert.FromBase64String(result?.data);
                    string data = _helper.Decrypt(resbytesx, resdatabytes);

                    Response.Result = data;
                    Response.Message = result.message;
                    Response.Code = result.code;
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                    Response.Result = "连接错误";
                }
            }

            return Response;
        }

        public Response<string> UploadFile(AirPortUploadDbReq req)
        {
            Response<string> Response = new Response<string>();
            var filePath = req.filePath;
            var uploadUrl = req.fileUrl;
            var fileName = Path.GetFileName(filePath);
            byte[] fileBuffer = null;
            HttpClient client = null;
            MultipartFormDataContent formData = null;
            try
            {
                //文件过大，建议使用 大文件上传接口，分段读取，进行上传
                fileBuffer = File.ReadAllBytes(filePath);
                client = new HttpClient();
                client.Timeout = new TimeSpan(0, 0, 0, 5);
                formData = new MultipartFormDataContent();
                var fileContent = new ByteArrayContent(fileBuffer);
                fileContent.Headers.ContentDisposition = new
                ContentDispositionHeaderValue("attachment");
                fileContent.Headers.ContentDisposition.FileName = fileName;
                //注意：务必 根据 文件扩展名，这里指定 ContentType
                fileContent.Headers.ContentType = new
                MediaTypeHeaderValue(fileName);
                formData.Add(fileContent);
                var request = new HttpRequestMessage
                {
                    //注意：这里是 PUT
                    Method = HttpMethod.Put,
                    RequestUri = new Uri(uploadUrl),
                    Content = formData
                };
                var result = client.SendAsync(request).Result.Content.ReadAsStringAsync().Result;
                if (string.IsNullOrWhiteSpace(result))
                {
                    Response.Result = result;
                        
                }
            }
            catch (Exception ex)
            {
                Response.Result = "上传失败";
            }
            finally
            {
                fileBuffer = null;
                formData?.Dispose();
                client?.Dispose();
            }
            return Response;
        }
            /// <summary>
            /// 无人机状态获取
            /// </summary>
            /// <param name="req"></param>
            /// <returns></returns>
            public async Task<ResData> getResult(string taskid)
        {
            ResData Response = new ResData();
            using (var uow = base.UnitWork.CreateContext())
            {
                //查询数据  检查是否有重复数据
                var info = uow.DbfineInfo.AsQueryable().Where(r => r.taskid == taskid).First();
       
                if (true)
                {
                    string json = JsonSerializer.Serialize(info);
                    string x_lc_secret = _helper.getxseret();
                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(json);
                    var encryptedResData = _helper.Encrypt(bytes);
                    Response.Result = encryptedResData;
                    Response.Message = "获取无人机机场状态成功！";
                    Response.Code = 200;
                    Response.Secret = x_lc_secret;
                    return Response;
                }
                else
                {
                    string x_lc_secret = _helper.getxseret();
                    // 转换为字节数组
                    byte[] bytes = Encoding.UTF8.GetBytes(" ");

                    var encryptedResData = _helper.Encrypt(bytes);
                    Response.Result = encryptedResData;
                    Response.Message = "获取无人机机场状态失败！";
                    Response.Code = 500;
                    Response.Secret = x_lc_secret;
                    return Response;
                }
            }
        }
        // 安全获取响应头值的方法
        private static string GetHeaderValue(HttpResponseMessage response, string headerName)
        {
            if (response.Headers.TryGetValues(headerName, out IEnumerable<string> values))
            {
                return string.Join(", ", values); // 如果多个值则合并
            }

            // 尝试忽略大小写再次查找
            foreach (var header in response.Headers)
            {
                if (header.Key.Equals(headerName, StringComparison.OrdinalIgnoreCase))
                {
                    return string.Join(", ", header.Value);
                }
            }

            return null; // 未找到
        }

        //获取省对接任务信息
        public async Task<Response<PageInfo<List<DroneDockRes>>>> GetDroneDockInfos(string keyWord, int page, int limit)
        {
            RefAsync<int> totalCount = 0;
            var info = await base.Repository.AsQueryable()
            .WhereIF(!string.IsNullOrEmpty(keyWord), t => t.taskname.Contains(keyWord)||t.bizidname.Contains(keyWord))
            .Select(t=>new DroneDockRes
            {
                id= t.id,
                bizidname= t.bizidname,
                taskname= t.taskname,
                createtime= t.createtime,
                state= t.state,
                datacode= t.datacode,
                deviceid= t.deviceid,
                taskid= t.taskid,
                tasklist=SqlFunc.Subqueryable<DroneDocktaskdetail>().Where(r=>r.taskid==t.id).ToList()
            })
            .ToPageListAsync(page, limit, totalCount);
            return new Response<PageInfo<List<DroneDockRes>>>
            {
                Result = new PageInfo<List<DroneDockRes>>
                {
                    Items = info,
                    Total = totalCount
                }
            };
        }

        //获取飞行数据
        public async Task<Response<DroneDockflightRes>> GetDroneDockflightInfos(string taskid)
        {
            DroneDockflightRes res=new DroneDockflightRes();
            var detailinfo=await Repository.ChangeRepository<SugarRepositiry<DroneDocktaskdetail>>()
                .AsQueryable()
                .Where(r=>r.flighttaskid==taskid)
                .ToListAsync();
            if (detailinfo.Count > 0)
            {
                var taskId= detailinfo[0].taskid;
                var taskinfo = await Repository.AsQueryable().Where(r => r.id == taskId).FirstAsync();
                var flighttaskinfo= await Repository.ChangeRepository<SugarRepositiry<LasaTask>>()
                .AsQueryable()
                .Where(r => r.FlightId == taskid)
                .FirstAsync();
                if (taskinfo != null)
                {
                    res.bizidname = taskinfo.bizidname;
                    res.taskname = taskinfo.taskname;
                }
                res.tasklist = detailinfo;
                if(flighttaskinfo != null)
                {
                    res.taskExecuteTime =Convert.ToDateTime(flighttaskinfo.ExecuteTime).ToString("yyyy-MM-dd HH:mm:ss");
                    res.waylineName=flighttaskinfo.TaskAirLineName;
                    res.flightTaskType=Convert.ToInt32(flighttaskinfo.FlightTaskType);
                    switch (flighttaskinfo.Status)
                    {
                        case 0:
                            res.flightTaskState = 1;
                            break;

                        case 1:
                            res.flightTaskState = 2;
                            break;

                        case 2:
                            res.flightTaskState = 3; 
                            break;

                        case 5:
                            res.flightTaskState = 0;
                            break;
                        case null: //交集
                            res.flightTaskState = 4;
                            break;
                    }
                }
                
                
            }
            return new Response<DroneDockflightRes>
            {
                Result = res
            };
        }

    }
}
