using Infrastructure;
using Infrastructure.Cache;
using Infrastructure.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using OpenAuth.App.ServiceApp.DroneDocking;
using OpenAuth.App.ServiceApp.DroneDocking.Request;
using OpenAuth.App.ServiceApp.DroneDocking.Response;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.Repository.Domain;
using Org.BouncyCastle.Ocsp;
using System.Text;

namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
    /// <summary>
    /// 对接
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DroneDockController: ControllerBase
    {
        private readonly DroneDockApp _app;
        private EncryptionHelper _helper;
        public DroneDockController(DroneDockApp app,EncryptionHelper helper)
        {
            _app = app;
            _helper = helper;
        }

        /// <summary>
        /// 无人机机场接口注册/更新
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> RegistService([FromBody] AirPortRegistReq req)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.RegistService(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 无人机机场设备注册/更新
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> AddDevice([FromBody] AddDeviceReq req)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.AddDevice(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 无人机机场设备授权
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> Authorization([FromBody] AuthorizationReq req)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.Authorization(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }


        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> Test(AirPortTaskReq req)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.Test(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// 无人机任务添加
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("/zhcfzx/droneAirport/AddTask")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<ReciveData<string>> AddTask(string recivedata)
        {
            var result = new ReciveData<string>();
            if(Request.Headers.TryGetValue("x-lc-token", out var tokenValue))
            {
                var tokenflag = _helper.Verify(tokenValue);
                if (tokenflag)
                {
                    // 获取请求头中的x-lc-secret
                    if (Request.Headers.TryGetValue("x-lc-secret", out var secretValue))
                    {
                        string secret = secretValue.ToString();
                        try
                        {
                            // 1. 从请求体中直接读取原始字符串（即 encryptedData）
                            string req;
                            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
                            {
                                req = await reader.ReadToEndAsync();
                            }
                            var data = await _app.AddTask(req, secret);
                            result.data = data.Result;
                            result.code=data.Code;
                            result.message = data.Message;
                            //Request.Headers.TryGetValue("traceid", out var traceid);
                            //result.traceid = traceid;
                            result.traceid = Guid.NewGuid().ToString();
                            Response.Headers.Add("x-lc-secret", data.Secret);
                        }
                        catch (Exception ex)
                        {
                            result.code = 500;
                            result.message = "error";
                            //Request.Headers.TryGetValue("traceid", out var traceid);
                            //result.traceid = traceid;
                            result.traceid = Guid.NewGuid().ToString();
                        }
                        return result;
                    }
                    else
                    {
                        throw new Exception("Missing required header: x-lc-secret");
                    }
                }
                else
                {
                    throw new Exception("unauthorized");
                }
            }
            else
            {
                throw new Exception("Missing required header: x-lc-token");
            }

        }


        /// <summary>
        /// 无人机任务更新
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("/zhcfzx/droneAirport/updateTask")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<ReciveData<string>> updateTask(string recivedata)
        {
            var result = new ReciveData<string>();
            if (Request.Headers.TryGetValue("x-lc-token", out var tokenValue))
            {
                var tokenflag = _helper.Verify(tokenValue);
                if (tokenflag)
                {
                    // 获取请求头中的x-lc-secret
                    if (Request.Headers.TryGetValue("x-lc-secret", out var secretValue))
                    {
                        string secret = secretValue.ToString();
                        try
                        {
                            // 1. 从请求体中直接读取原始字符串（即 encryptedData）
                            string req;
                            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
                            {
                                req = await reader.ReadToEndAsync();
                            }
                            var data = await _app.UpdateTask(req, secret);
                            result.data = data.Result;
                            result.code = data.Code;
                            result.message = data.Message;
                            //Request.Headers.TryGetValue("traceid", out var traceid);
                            //result.traceid = traceid;
                            result.traceid = Guid.NewGuid().ToString();
                            Response.Headers.Add("x-lc-secret", data.Secret);
                        }
                        catch (Exception ex)
                        {
                            result.code = 200;
                            result.message = "error";
                            //Request.Headers.TryGetValue("traceid", out var traceid);
                            //result.traceid = traceid;
                            result.traceid = Guid.NewGuid().ToString();
                        }
                        return result;
                    }
                    else
                    {
                        throw new Exception("Missing required header: x-lc-secret");
                    }
                }
                else
                {
                    throw new Exception("unauthorized");
                }
            }
            else
            {
                throw new Exception("Missing required header: x-lc-token");
            }

        }

        /// <summary>
        /// 取消无人机任务
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("/zhcfzx/droneAirport/cancelTask")]
        [HttpGet]
        [AllowAnonymous]
        public async Task<ReciveData<string>> cancelTask(string taskid)
        {
            var result = new ReciveData<string>();
            if (Request.Headers.TryGetValue("x-lc-token", out var tokenValue))
            {
                var tokenflag = _helper.Verify(tokenValue);
                if (tokenflag)
                {
                    try
                    {
                        var data = await _app.CancelTask(taskid);
                        result.data = data.Result;
                        result.code = data.Code;
                        result.message = data.Message;
                        //Request.Headers.TryGetValue("traceid", out var traceid);
                        //result.traceid = traceid;
                        result.traceid = Guid.NewGuid().ToString();
                        Response.Headers.Add("x-lc-secret", data.Secret);
                    }
                    catch (Exception ex)
                    {
                        result.code = 200;
                        result.message = "error";
                        //Request.Headers.TryGetValue("traceid", out var traceid);
                        //result.traceid = traceid;
                        result.traceid = Guid.NewGuid().ToString();
                    }
                    return result;
                }
                else
                {
                    throw new Exception("unauthorized");
                }
            }
            else
            {
                throw new Exception("Missing required header: x-lc-token");
            }

        }


        /// <summary>
        /// 省任务获取无人机状态信息
        /// </summary>
        /// <param name="deviceid"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        [HttpGet]
        [AllowAnonymous]
        [Route("/zhcfzx/droneAirport/getDroneStatus")]
        public async  Task<ReciveData<string>> GetDroneStatus(string deviceid)
        {
    
            var result = new ReciveData<string>();
            if (Request.Headers.TryGetValue("x-lc-token", out var tokenValue))
            {
                // todo 完成后，需要恢复
                //var tokenflag = _helper.Verify(tokenValue);
                var tokenflag = true;
                if (tokenflag)
                {
                    try
                    {
                        var data = await _app.GetDroneStatus(deviceid);
                        result.data = data.Result;
                        result.code = data.Code;
                        result.message = data.Message;
                        result.traceid = Guid.NewGuid().ToString();
                        Response.Headers.Add("x-lc-secret", data.Secret);
                    }
                    catch (Exception ex)
                    {
                        result.code = 200;
                        result.message = "error";

                        result.traceid = Guid.NewGuid().ToString();
                    }
                    return result;
                }
                else
                {
                    throw new Exception("unauthorized");
                }
            }
            else
            {
                throw new Exception("Missing required header: x-lc-token");
            }

        }
        /// <summary>
        /// 无人机状态上报
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> reportDroneStatus([FromBody] List<AirPortStatusApply> req)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.reportDroneStatus(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 无人机任务进度查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [Route("/zhcfzx/droneAirport/queryTaskStatus")]
        [HttpPost]
        [AllowAnonymous]
        public async Task<ReciveData<string>> queryTaskStatus(string taskid)
        {
            var result = new ReciveData<string>();
            if (Request.Headers.TryGetValue("x-lc-token", out var tokenValue))
            {
                var tokenflag = _helper.Verify(tokenValue);
                if (tokenflag)
                {
                    // 获取请求头中的x-lc-secret
                    if (Request.Headers.TryGetValue("x-lc-secret", out var secretValue))
                    {
                        string secret = secretValue.ToString();
                        try
                        {
                            // 1. 从请求体中直接读取原始字符串（即 encryptedData）
                            string req;
                            using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
                            {
                                req = await reader.ReadToEndAsync();
                            }
                            var data = await _app.queryTaskStatus(req, secret);
                            result.data = data.Result;
                            result.code = data.Code;
                            result.message = data.Message;
                            //Request.Headers.TryGetValue("traceid", out var traceid);
                            //result.traceid = traceid;
                            result.traceid = Guid.NewGuid().ToString();
                            Response.Headers.Add("x-lc-secret", data.Secret);
                        }
                        catch (Exception ex)
                        {
                            result.code = 200;
                            result.message = "error";
                            //Request.Headers.TryGetValue("traceid", out var traceid);
                            //result.traceid = traceid;
                            result.traceid = Guid.NewGuid().ToString();
                        }
                        return result;
                    }
                    else
                    {
                        throw new Exception("Missing required header: x-lc-secret");
                    }
                }
                else
                {
                    throw new Exception("unauthorized");
                }
            }
            else
            {
                throw new Exception("Missing required header: x-lc-token");
            }

        }

        /// <summary>
        /// 校验token
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public  Response<bool> VerifyToken(string token)
        {
            Response<bool> result= new Response<bool>();
            try
            {
                var tokenflag = _helper.Verify(token);
                if (tokenflag)
                {
                    result.Message = "校验成功";
                    result.Result = true;
                }
                else
                {
                    result.Message = "校验失败";
                    result.Result = false;
                    result.Code = 500;
                }
                return result ;
            }
            catch (Exception ex) 
            {
                result.Code = 500;
                result.Message = "error";
                return result;
            }     
        }

        /// <summary>
        /// 获取省对接任务列表
        /// </summary>
        /// <param name="keyWord">名称筛选</param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<PageInfo<List<DroneDockRes>>>> GetDroneDockInfos(string keyWord, int page, int limit)
        {
            return await _app.GetDroneDockInfos(keyWord, page, limit);
        }


        /// <summary>
        /// 前端任务获取
        /// </summary>
        /// <param name="taskid">执行任务id</param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<DroneDockflightRes>> GetDroneDockflightInfos(string taskid)
        {
            return await _app.GetDroneDockflightInfos(taskid);
        }


        /// <summary>
        /// 获取临时上传地址
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<string>> getUploadFilePath([FromBody] AirPortUploadReq req)
        {
            var result = new Response<string>();
            try
            {
                result = await _app.getUploadFilePath(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }

        [HttpPost]
        [AllowAnonymous]
        public  async Task<Response<string>> UploadFile(AirPortUploadDbReq req) {
            var result = new Response<string>();
            try
            {
                result =  await _app.UploadFile(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }
            return result;
        }

        [HttpGet]
        [AllowAnonymous]
        [Route("/zhcfzx/droneAirport/getResult")]
        public async Task<ReciveData<string>> getResult(string taskid)
        {
            var result = new ReciveData<string>();
            if (Request.Headers.TryGetValue("x-lc-token", out var tokenValue))
            {
                var tokenflag = _helper.Verify(tokenValue);
                if (tokenflag)
                {
                    try
                    {
                        var data = await _app.getResult(taskid);
                        result.data = data.Result;
                        result.code = data.Code;
                        result.message = data.Message;
                        //Request.Headers.TryGetValue("traceid", out var traceid);
                        //result.traceid = traceid;
                        result.traceid = Guid.NewGuid().ToString();
                        Response.Headers.Add("x-lc-secret", data.Secret);
                    }
                    catch (Exception ex)
                    {
                        result.code = 200;
                        result.message = "error";
                        //Request.Headers.TryGetValue("traceid", out var traceid);
                        //result.traceid = traceid;
                        result.traceid = Guid.NewGuid().ToString();
                    }
                    return result;
                }
                else
                {
                    throw new Exception("unauthorized");
                }
            }
            else
            {
                throw new Exception("Missing required header: x-lc-token");
            }

        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<ReciveData<string>> dbupload (string taskid)
        {
            var result = new ReciveData<string>();

            _app.InsertDb(taskid);
            result.code = 200;
            result.message = "success";

            return result;

        }
    }
}
