using System.Text;
using Castle.Core.Internal;
using Infrastructure;
using Infrastructure.CloudSdk.wayline;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenAuth.App.ServiceApp;
using OpenAuth.App.ServiceApp.AirLine.Request;
using OpenAuth.App.ServiceApp.FlyTask.Response;
using OpenAuth.App.ServiceApp.Request;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.Repository.Domain;

namespace OpenAuth.WebApi.Controllers.ServiceControllers
{
    /// <summary>
    /// 后台管理模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ManageController : ControllerBase
    {
        private readonly ManageApp _app;
        private readonly MqttClientManager _mqttClientManager;

        public ManageController(ManageApp app, MqttClientManager mqttClientManager)
        {
            _app = app;
            _mqttClientManager = mqttClientManager;
        }

        #region 机场管理

        /// <summary>
        /// 获取机场列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="sn">sn</param>
        /// <param name="type">类型</param>
        /// <param name="workspaceid">项目</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<LasaDronePort>>>> GetDataList(int page, int limit, string sn,
            string type, string workspaceid)
        {
            var result = new Response<PageInfo<List<LasaDronePort>>>();
            try
            {
                result = await _app.GetPageList(page, limit, sn, type, workspaceid);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 编辑机场
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> EditDronePort(LasaDronePort info)
        {
            return await _app.EditDronePort(info);
        }

        /// <summary>
        /// 修改机场固件信息
        /// </summary>
        /// <param name="id">机场id</param>
        /// <param name="firmwareVersion">机场版本</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> EditDronePortFirmware(string id, string firmwareVersion)
        {
            return await _app.EditDronePortFirmware(id, firmwareVersion);
        }

        /// <summary>
        /// 删除机场
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteDronePort(string id)
        {
            return await _app.DeleteDronePort(id);
        }

        #endregion

        #region 无人机管理

        /// <summary>
        /// 获取无人机列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="sn">sn</param>
        /// <param name="type">类型</param>
        /// <param name="workspaceid">项目</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<dynamic>>>> GetUavPageList(int page, int limit, string sn, string type,
            string workspaceid)
        {
            var result = new Response<PageInfo<List<dynamic>>>();
            try
            {
                result = await _app.GetUavPageList(page, limit, sn, type, workspaceid);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 编辑无人机
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> EditUav(LasaUav info)
        {
            return await _app.EditUav(info);
        }

        /// <summary>
        /// 修改无人机固件信息
        /// </summary>
        /// <param name="id">无人机id</param>
        /// <param name="firmwareVersion">机场版本</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> EditUavFirmware(string id, string firmwareVersion)
        {
            return await _app.EditUavFirmware(id, firmwareVersion);
        }

        /// <summary>
        /// 删除无人机
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteUav(string id)
        {
            return await _app.DeleteUav(id);
        }

        /// <summary>
        /// 无人机查询
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<PageInfo<List<dynamic>>>> GetUavPageByDockSnNew(int page, int limit, string sn)
        {
            var result = new Response<PageInfo<List<dynamic>>>();
            try
            {
                result = await _app.GetUavPageByDockSnNew(page, limit, sn);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 根据机场sn获取无人机列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sn"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<dynamic>>>> GetUavPageByDocksn(int page, int limit, string sn)
        {
            var result = new Response<PageInfo<List<dynamic>>>();
            try
            {
                result = await _app.GetUavPageByDocksn(page, limit, sn);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 导出无人机信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportDevice()
        {
            var content = await _app.GetUavSn();
            byte[] fileBytes = Encoding.UTF8.GetBytes(content);
            string fileName = "DeviceSNList_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            return File(fileBytes, "text/plain", fileName);
        }

        #endregion

        #region 任务管理

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<LasaTask>>>> GetTaskPageList(int page, int limit, string key,
            int? status)
        {
            var result = new Response<PageInfo<List<LasaTask>>>();
            try
            {
                result = await _app.GetTaskPageList(page, limit, key, status);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddTask(LasaTask info)
        {
            return await _app.AddTask(info);
        }

        /// <summary>
        /// 编辑任务,不再允许编辑任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Obsolete]
        public async Task<Response<bool>> EditTask(LasaTask info)
        {
            return await _app.EditTask(info);
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteTask(string id)
        {
            return await _app.DeleteTask(id);
        }

        /// <summary>
        /// 根据flightId查询指令拍摄图片
        /// </summary>
        /// <param name="flightId"></param>
        /// <param name="timestamp"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<CommandPictureResponse>> GetTaskPicList(string flightId, long timestamp)
        {
            return await _app.GetTaskPicList(flightId, timestamp);
        }


        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<CommandVideoResponse>> GetTaskVideoList(string flightId, long timestamp)
        {
            return await _app.GetTaskVideoList(flightId, timestamp);
        }

        #endregion

        #region 航线管理

        [HttpPost]
        public async Task<Response<bool>> CreateAirLineFolder(FolderCreateReq req)
        {
            return await _app.CreateAirLineFolder(req.FolderName, req.ParentId);
        }

        /// <summary>
        /// 删除文件夹及文件夹航线
        /// </summary>
        /// <param name="folderId"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteAirLineFolder(string folderId)
        {
            return await _app.DeleteAirLineFolder(folderId);
        }

        [HttpGet]
        public async Task<Response<List<LasaLineFolder>>> ListAirLineFolder()
        {
            return await _app.ListAirLineFolder();
        }

        /// <summary>
        /// 获取航线列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<PageInfo<List<LasaAirLine>>>> GetAirLineList([FromQuery] AirLineListRequestPage req)
        {
            var result = new Response<PageInfo<List<LasaAirLine>>>();
            try
            {
                result = await _app.GetAirLinePageList(req);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 航线详情
        /// </summary>
        /// <param name="airLineId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<LasaAirLine>> GetAirLine(string airLineId)
        {
            return await _app.GetAirLine(airLineId);
        }

        /// <summary>
        /// 添加航线
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddAirLine(LasaAirLine info)
        {
            return await _app.AddAirLine(info);
        }

        /// <summary>
        /// 编辑航线
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> EditAirLine(LasaAirLine info)
        {
            return await _app.EditAirLine(info);
        }

        /// <summary>
        /// 删除航线
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteAirLine(string id)
        {
            return await _app.DeleteAirLine(id);
        }

        /// <summary>
        /// 上传航线文件
        /// </summary>
        /// <param name="xmlFile">kmz文件</param>
        /// <param name="folder">文件夹</param>
        /// <returns></returns>
        [HttpPost("upload")]
        [AllowAnonymous]
        public async Task<IActionResult> UploadXmlFile(IFormFile xmlFile, string folder)
        {
            if (xmlFile == null || xmlFile.Length == 0)
                return BadRequest("文件为空");
            if (string.IsNullOrEmpty(folder))
            {
                folder = "";
            }

            var path = await _app.UploadFile(xmlFile, folder);
            return Ok(new { message = "上传成功", path });
        }
        /*/// <summary>
        /// 更新航线文件
        /// </summary>
        /// <param name="xmlFile"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("uploadwpmlfile")]
        [AllowAnonymous]
        public async Task<IActionResult> UploadWpmlFile(IFormFile xmlFile, string id)
        {
            if (xmlFile == null || xmlFile.Length == 0)
                return BadRequest("文件为空");
            string baseFolder = "Waylines/" + (string.IsNullOrEmpty(id) ? Guid.NewGuid().ToString() : id);
            var uploadsFolder = Path.Combine(Directory.GetCurrentDirectory(), baseFolder);
            if (!Directory.Exists(uploadsFolder))
                Directory.CreateDirectory(uploadsFolder);

            // todo 这里只有一个文件，是否得改
            var filePath = Path.Combine(uploadsFolder, "waylines.wpml");

            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await xmlFile.CopyToAsync(stream);
            }

            return Ok(new { message = "上传成功", path = filePath });
        }*/

        #endregion

        #region 项目管理

        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <param name="isjoin">是否是已加入的项目（0全部，1加入，2未加入）</param>
        /// <param name="key">项目名称筛选</param>
        /// <param name="state">状态（0全部，1进行中，2已归档）</param>
        /// <param name="order">排序</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<dynamic>>> GetWorkspaceList(int isjoin, string key, int state,
            string order = "\"CreateTime\" desc")
        {
            var result = new Response<List<dynamic>>();
            try
            {
                result = await _app.GetWorkspaceList(isjoin, key, state, order);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 添加项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> AddWorkspace(WorkSpace info)
        {
            return await _app.AddWorkspace(info);
        }

        /// <summary>
        /// 编辑项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> EditWorkspace(WorkSpace info)
        {
            return await _app.EditWorkspace(info);
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteWorkspace(string id)
        {
            return await _app.DeleteWorkspace(id);
        }

        /// <summary>
        /// 归档项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> CompleteWorkspace(string id)
        {
            return await _app.CompleteWorkspace(id);
        }

        /// <summary>
        /// 获取机场列表，添加项目使用
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<LasaDronePort>>> GetUavList()
        {
            var result = new Response<List<LasaDronePort>>();
            try
            {
                result = await _app.GetUavList();
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 根据项目id获取项目信息，编辑项目使用
        /// </summary>
        /// <param name="id">项目id</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<WorkSpaceRes>> GetWorkSpaceById(string id)
        {
            var result = new Response<WorkSpaceRes>();
            try
            {
                result = await _app.GetWorkSpaceById(id);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        #endregion

        // 航线任务在云端的 共享查看、下发执行、取消以及进度上报等功能。
        /// <summary>
        /// 解除挂起（执行任务） todo 需不需要加时间限制判断？ 
        /// </summary>
        /// <param name="taskId"></param>
        [HttpPost]
        [AllowAnonymous]
        // todo 根据项目设置的起飞条件设置是否起飞
        public async Task ExecuteFlyTask(string taskId)
        {
            await _app.ExecuteFlyTask(taskId);
        }

        /// <summary>
        /// 挂起任务
        /// </summary>
        /// <param name="taskId"></param>
        [HttpPost]
        public async Task PendingFlyTask(string taskId)
        {
            // todo  先只针对立即任务实现
            await _app.PendingFlyTask(taskId);
        }

        /// <summary>
        /// 任务图片列表查询
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<LasaMediaFile>>> GetTaskImageList(string taskId)
        {
            return await _app.GetTaskImageList(taskId);
        }

        /// <summary>
        /// 开启机场直播（测试使用）
        /// </summary>
        /// <param name="streamUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<bool>> StartDronePortLive(string streamUrl)
        {
            return await _app.StartDronePortLive(streamUrl);
        }

        /// <summary>
        /// 测试使用
        /// </summary>
        /// <param name="streamUrl"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Response<bool>> StopDronePortLive(string streamUrl)
        {
            return await _app.StopDronePortLive(streamUrl);
        }

        /// <summary>
        /// 阻飞模拟测试
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<string> TestPreventFlyTask(string taskId)
        {
            return await _app.TestPreventFlyTask(taskId);
        }


        [HttpGet]
        [AllowAnonymous]
        public string TestGetDevJson()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile(
                    $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json",
                    optional: true)
                .AddEnvironmentVariables();
            // 构建配置
            var configuration = builder.Build();
            // 读取连接字符串
            var dir = configuration["WpmlDir"];
            return dir;
        }

        #region 添加地图作业区域

        /// <summary>
        /// 添加地图作业区域
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<string>> AddWorkArea([FromBody] LasaShpData model)
        {
            var res = new Response<string>();
            try
            {
                return await _app.AddWorkArea(model);
            }
            catch (Exception ex)
            {
                res.Code = 500;
                res.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return res;
        }

        /// <summary>
        /// 更新地图作业区域
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<string>> UpdateWorkArea([FromBody] LasaShpData model)
        {
            var res = new Response<string>();
            try
            {
                return await _app.UpdateWorkArea(model);
            }
            catch (Exception ex)
            {
                res.Code = 500;
                res.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return res;
        }

        /// <summary>
        /// 删除地图作业区域
        /// </summary>
        /// <param name="id">地图作业区域id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteWorkArea(string id)
        {
            return await _app.DeleteWorkArea(id);
        }

        /// <summary>
        /// 获取地图作业区域列表
        /// </summary>
        /// <param name="workspaceid">项目id</param>
        /// <param name="state">项目状态（0已启用，1已禁用，null全部）</param>
        /// <param name="type">区域类型（作业区，限飞区等）</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<LasaShpData>>> GetWorkAreaList(string workspaceid, int? state, string type)
        {
            var result = new Response<List<LasaShpData>>();
            try
            {
                result = await _app.GetWorkAreaList(workspaceid, state, type);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        #endregion

        #region 添加地图标注

        /// <summary>
        /// 添加地图标注
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<string>> AddAnnotation([FromBody] LasaAnnotation model)
        {
            var res = new Response<string>();
            try
            {
                return await _app.AddAnnotation(model);
            }
            catch (Exception ex)
            {
                res.Code = 500;
                res.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return res;
        }

        /// <summary>
        /// 更新地图标注
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<string>> UpdateAnnotation([FromBody] LasaAnnotation model)
        {
            var res = new Response<string>();
            try
            {
                return await _app.UpdateAnnotation(model);
            }
            catch (Exception ex)
            {
                res.Code = 500;
                res.Message = ex.InnerException?.Message ?? ex.Message;
            }

            return res;
        }

        /// <summary>
        /// 删除地图标注
        /// </summary>
        /// <param name="id">地图标注id</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> DeleteAnnotation(string id)
        {
            return await _app.DeleteAnnotation(id);
        }

        /// <summary>
        /// 获取地图标注列表
        /// </summary>
        /// <param name="workspaceid">项目id</param>
        /// <param name="state">项目状态（0已启用，1已禁用，null全部）</param>
        /// <param name="type">区域类型（0点，1线，2多边行，3圈）</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<Response<List<LasaAnnotation>>> GetAnnotationList(string workspaceid, int? state, int? type)
        {
            var result = new Response<List<LasaAnnotation>>();
            try
            {
                result = await _app.GetAnnotationList(workspaceid, state, type);
            }
            catch (Exception ex)
            {
                result.Code = 500;
                result.Message = ex.Message;
            }

            return result;
        }

        #endregion

        #region 基本信息

        /// <summary>
        /// 获取基本信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Response<JObject>> GetBasicInfo()
        {
            return await _app.GetBasicInfo();
        }

        #endregion

        #region 媒体库

        /// <summary>
        /// 媒体文件夹树结构
        /// </summary>
        /// <param name="workspaceId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<List<LasaMediaFile>> ListMediaFolder(string workspaceId)
        {
            return await _app.ListMediaFolder(workspaceId);
        }
        /// <summary>
        /// 媒体库新建文件夹记录
        /// </summary>
        /// <returns></returns>
        /// todo  应该传什么参数？
        [HttpPost]
        public async Task<Response<bool>> CreateMediaFolder(string name ,string parentKey)
        {
            return await _app.CreateMediaFolder(name,parentKey);
        }
        #endregion
        
        /// <summary>
        ///  媒体保存测试
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Response<bool>> Test1111(string msg)
        {
            return await _app.Test1111(msg);
        }
    }
}