using DocumentFormat.OpenXml.Wordprocessing;
using Infrastructure;
using Infrastructure.CloudSdk.minio;
using Infrastructure.CloudSdk.wayline;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OpenAuth.App.BaseApp.Base;
using OpenAuth.App.BasicQueryService;
using OpenAuth.App.Interface;
using OpenAuth.App.ServiceApp.Request;
using OpenAuth.App.ServiceApp.Response;
using OpenAuth.Repository;
using OpenAuth.Repository.Domain;
using OpenAuth.WebApi;
using OpenAuth.WebApi.CloudSdk;
using SqlSugar;
using System.Dynamic;
using System.Text;

namespace OpenAuth.App.ServiceApp
{
    public class ManageApp : SqlSugarBaseApp<LasaDronePort, SugarDbContext>
    {
        private readonly MqttClientManager _mqttClientManager;
        private readonly MinioService _minioService;
        CommonDataManager _commonDataManager;

        public ManageApp(ISugarUnitOfWork<SugarDbContext> unitWork, ISimpleClient<LasaDronePort> repository, IAuth auth,
            MqttClientManager mqttClientManager, CommonDataManager commonDataManager, MinioService minioService)
            : base(unitWork, repository, auth)
        {
            _mqttClientManager = mqttClientManager;
            _minioService = minioService;
            _commonDataManager = commonDataManager;
        }

        #region 机场管理

        /// <summary>
        /// 分页获取所有数据 
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<LasaDronePort>>>> GetPageList(int page, int limit, string key)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.LasaDronePort.AsQueryable().Includes(a => a.UavList)
                    .Where(a => a.IsDelete == false)
                    .WhereIF(!string.IsNullOrEmpty(key), a => a.Name.Contains(key))
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<LasaDronePort>>>
                {
                    Result = new PageInfo<List<LasaDronePort>> { Items = list, Total = totalCount }
                };
            }
        }

        /// <summary>
        /// 编辑机场信息
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public async Task<Response<bool>> EditDronePort(LasaDronePort info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaDronePort.UpdateAsync(it => new LasaDronePort()
                {
                    Name = info.Name,
                    WorkSpaceId = info.WorkSpaceId,
                }, it => it.Id == info.Id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                else
                    return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        /// <summary>
        /// 修改机场固件信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<Response<bool>> EditDronePortFirmware(string id, string firmwareVersion)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaDronePort.UpdateAsync(it => new LasaDronePort()
                {
                    FirmwareVersion = firmwareVersion
                }, it => it.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                else
                    return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        //删除机场信息
        public async Task<Response<bool>> DeleteDronePort(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.LasaDronePort.UpdateAsync(u => new LasaDronePort
                {
                    IsDelete = true
                }, u => u.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "删除成功" };
                else
                    return new Response<bool> { Result = false, Message = "删除失败" };
            }
        }

        //添加机场信息
        public bool AddDronePort(LasaDronePort info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = db.LasaDronePort.Insert(info);
                if (db.Commit())
                    return true;
                else
                    return false;
            }
        }

        #endregion

        /// <summary>
        /// 获取无人机列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<dynamic>>>> GetUavPageList(int page, int limit, string key)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.LasaUav.AsQueryable()
                    .LeftJoin<LasaDronePort>((a, b) => a.PId == b.Id)
                    .Where((a, b) => a.IsDelete == false)
                    .WhereIF(!string.IsNullOrEmpty(key), (a, b) => a.Name.Contains(key))
                    .Select<dynamic>((a, b) => new
                    {
                        id = a.Id,
                        name = a.Name,
                        pId = a.PId,
                        typeId = a.TypeId,
                        sn = a.Sn,
                        psn = b.Sn,
                        updateTime = a.UpdateTime,
                        isDelete = a.IsDelete,
                        pName = b.Name, // 机场名称
                        workSpaceId = a.WorkSpaceId,
                        firmwareVersion = a.FirmwareVersion,
                    })
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<dynamic>>>
                {
                    Result = new PageInfo<List<dynamic>> { Items = list, Total = totalCount }
                };
            }
        }

        /// <summary>
        /// 编辑无人机
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public async Task<Response<bool>> EditUav(LasaUav info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaUav.UpdateAsync(it => new LasaUav()
                {
                    Name = info.Name,
                }, it => it.Id == info.Id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                else
                    return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        /// <summary>
        /// 修改无人机固件信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="firmwareVersion"></param>
        /// <returns></returns>
        public async Task<Response<bool>> EditUavFirmware(string id, string firmwareVersion)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaUav.UpdateAsync(it => new LasaUav()
                {
                    FirmwareVersion = firmwareVersion
                }, it => it.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                else
                    return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        //删除无人机
        public async Task<Response<bool>> DeleteUav(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.LasaUav.UpdateAsync(u => new LasaUav
                {
                    IsDelete = true
                }, u => u.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "删除成功" };
                else
                    return new Response<bool> { Result = false, Message = "删除失败" };
            }
        }

        //添加无人机
        public bool AddLasaUav(LasaUav info)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = db.LasaUav.Insert(info);
                if (db.Commit())
                    return true;
                else
                    return false;
            }
        }

        /// <summary>
        /// 获取任务列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<LasaTask>>>> GetTaskPageList(int page, int limit, string key)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.LasaTask.AsQueryable()
                    .WhereIF(!string.IsNullOrEmpty(key), a => a.TaskName.Contains(key))
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<LasaTask>>>
                {
                    Result = new PageInfo<List<LasaTask>> { Items = list, Total = totalCount }
                };
            }
        }

        //添加任务
        public async Task<Response<bool>> AddTask(LasaTask task)
        {
            using (var db = UnitWork.CreateContext())
            {
                task.Id = Guid.NewGuid().ToString();
                task.CreateId = _auth.GetCurrentUser().User.Id;
                task.CreateTime = DateTime.Now;
                var flag = await db.LasaTask.InsertAsync(task);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "添加成功" };
                else
                    return new Response<bool> { Result = false, Message = "添加失败" };
            }
        }

        //编辑任务
        public async Task<Response<bool>> EditTask(LasaTask task)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaTask.UpdateAsync(task);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                else
                    return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        //删除任务
        public async Task<Response<bool>> DeleteTask(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaTask.DeleteAsync(it => it.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "删除成功" };
                else
                    return new Response<bool> { Result = false, Message = "删除失败" };
            }
        }

        #region 航线管理

        /// <summary>
        /// 获取航线列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<PageInfo<List<LasaAirLine>>>> GetAirLinePageList(int page, int limit, string key)
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var list = await db.LasaAirLine.AsQueryable()
                    .WhereIF(!string.IsNullOrEmpty(key), a => a.AirLineName.Contains(key))
                    .ToPageListAsync(page, limit, totalCount);
                return new Response<PageInfo<List<LasaAirLine>>>
                {
                    Result = new PageInfo<List<LasaAirLine>> { Items = list, Total = totalCount }
                };
            }
        }

        //添加航线
        public async Task<Response<bool>> AddAirLine(LasaAirLine lasaAirLine)
        {
            using (var db = UnitWork.CreateContext())
            {
                lasaAirLine.Id = Guid.NewGuid().ToString();
                lasaAirLine.CreateId = _auth.GetCurrentUser().User.Id;
                lasaAirLine.CreateTime = DateTime.Now;
                var flag = await db.LasaAirLine.InsertAsync(lasaAirLine);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "添加成功" };
                else
                    return new Response<bool> { Result = false, Message = "添加失败" };
            }
        }

        //编辑航线
        public async Task<Response<bool>> EditAirLine(LasaAirLine lasaAirLine)
        {
            var oldLasaAirLine = await Repository.ChangeRepository<SugarRepositiry<LasaAirLine>>()
                .GetByIdAsync(lasaAirLine.Id);
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaAirLine.UpdateAsync(lasaAirLine);
                if (db.Commit())
                {
                    // http://175.27.168.120:6013/test/2025061617111990020017.wpml
                    var wmpl = oldLasaAirLine.WPML;
                    await _minioService.DeleteFile(wmpl);
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                }

                return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        //删除航线
        public async Task<Response<bool>> DeleteAirLine(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                var flag = await db.LasaAirLine.DeleteAsync(it => it.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "删除成功" };
                else
                    return new Response<bool> { Result = false, Message = "删除失败" };
            }
        }
        //生成航线文件

        #endregion

        #region 项目管理

        /// <summary>
        /// 获取项目列表
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public async Task<Response<List<dynamic>>> GetWorkspaceList(int isjoin, string key, int state,
            string order = "\"CreateTime\" desc")
        {
            RefAsync<int> totalCount = 0;
            using (var db = UnitWork.CreateContext())
            {
                var userid = _auth.GetCurrentUser().User.Id;
                List<string> ids = new List<string>();
                if (isjoin == 1)
                {
                    ids = db.LasaSpaceUser.AsQueryable().Where(r => r.UserId == userid)?.Select(r => r.WorkSpaceId)
                        .ToList();
                }

                var list = await db.LasaWorkspace.AsQueryable()
                    .WhereIF(!string.IsNullOrEmpty(key), a => a.WorkspaceName.Contains(key))
                    .WhereIF(state != 0, a => a.Sate == state)
                    .WhereIF(isjoin == 1, a => ids.Contains(a.Id))
                    .WhereIF(isjoin == 2, a => !ids.Contains(a.Id))
                    .LeftJoin<SysUser>((a, u) => a.CreateId == u.Id)
                    .Select<dynamic>((a, u) => new
                    {
                        a.Id,
                        a.WorkspaceName,
                        a.WorkspaceDesc,
                        a.Sate,
                        a.CreateTime,
                        a.CreateId,
                        u.Account,
                        u.Name,
                        UserNames = SqlFunc.Subqueryable<LasaSpaceUser>().Where(r => r.WorkSpaceId == a.Id)
                            .LeftJoin<SysUser>((r, s) => r.UserId == s.Id).SelectStringJoin((r, s) => s.Name, ",")
                    }).MergeTable()
                    .OrderBy(order)
                    .ToListAsync();

                return new Response<List<dynamic>>
                {
                    Result = list
                };
            }
        }

        //添加项目 
        public async Task<Response<bool>> AddWorkspace(WorkSpace info)
        {
            using (var db = UnitWork.CreateContext())
            {
                LasaWorkspace lasaWorkspace = info.LasaWorkspace;
                lasaWorkspace.Id = Guid.NewGuid().ToString();
                lasaWorkspace.CreateId = _auth.GetCurrentUser().User.Id;
                lasaWorkspace.CreateTime = DateTime.Now;

                List<LasaSpaceDevice> devices = new List<LasaSpaceDevice>();
                foreach (var item in info.DeviceIds)
                {
                    LasaSpaceDevice sd = new LasaSpaceDevice();
                    sd.WorkSpaceId = lasaWorkspace.Id;
                    sd.DeviceId = item;
                    devices.Add(sd);
                }

                List<LasaSpaceUser> users = new List<LasaSpaceUser>();
                foreach (var item in info.UserIds)
                {
                    LasaSpaceUser sd = new LasaSpaceUser();
                    sd.WorkSpaceId = lasaWorkspace.Id;
                    sd.UserId = item;
                    users.Add(sd);
                }

                foreach (var item in info.Lockfly)
                {
                    item.Id = Guid.NewGuid().ToString();
                    item.WorkSpaceId = lasaWorkspace.Id;
                    await db.LasaSpaceLockFly.InsertAsync(item);
                }

                await db.LasaWorkspace.InsertAsync(lasaWorkspace);
                await db.LasaSpaceDevice.InsertRangeAsync(devices);
                await db.LasaSpaceUser.InsertRangeAsync(users);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "添加成功" };
                else
                    return new Response<bool> { Result = false, Message = "添加失败" };
            }
        }

        //编辑项目 
        public async Task<Response<bool>> EditWorkspace(WorkSpace info)
        {
            using (var db = UnitWork.CreateContext())
            {
                LasaWorkspace lasaWorkspace = info.LasaWorkspace;
                var flag = await db.LasaWorkspace.UpdateAsync(lasaWorkspace);
                List<LasaSpaceDevice> devices = new List<LasaSpaceDevice>();
                foreach (var item in info.DeviceIds)
                {
                    LasaSpaceDevice sd = new LasaSpaceDevice();
                    sd.WorkSpaceId = lasaWorkspace.Id;
                    sd.DeviceId = item;
                    devices.Add(sd);
                }

                List<LasaSpaceUser> users = new List<LasaSpaceUser>();
                foreach (var item in info.UserIds)
                {
                    LasaSpaceUser sd = new LasaSpaceUser();
                    sd.WorkSpaceId = lasaWorkspace.Id;
                    sd.UserId = item;
                    users.Add(sd);
                }

                foreach (var item in info.Lockfly)
                {
                    if (!string.IsNullOrEmpty(item.Id))
                    {
                        await db.LasaSpaceLockFly.UpdateAsync(item);
                    }
                    else
                    {
                        item.Id = Guid.NewGuid().ToString();
                        item.WorkSpaceId = lasaWorkspace.Id;
                        await db.LasaSpaceLockFly.InsertAsync(item);
                    }
                }

                await db.LasaSpaceDevice.DeleteAsync(r => r.WorkSpaceId == lasaWorkspace.Id);
                await db.LasaSpaceDevice.InsertRangeAsync(devices);
                await db.LasaSpaceUser.DeleteAsync(r => r.WorkSpaceId == lasaWorkspace.Id);
                await db.LasaSpaceUser.InsertRangeAsync(users);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "编辑成功" };
                else
                    return new Response<bool> { Result = false, Message = "编辑失败" };
            }
        }

        //获取无人机信息
        public async Task<Response<List<LasaDronePort>>> GetUavList()
        {
            using (var db = UnitWork.CreateContext())
            {
                var list = db.LasaSpaceDevice.AsQueryable()?.Select(r => r.DeviceId).ToList();

                var uavlist = await db.LasaDronePort.AsQueryable()
                    .Where(r => !list.Contains(r.Id))
                    .ToListAsync();
                return new Response<List<LasaDronePort>>
                {
                    Result = uavlist
                };
            }
        }

        /// <summary>
        /// 根据项目id获取项目信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<WorkSpaceRes>> GetWorkSpaceById(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                WorkSpaceRes res = new WorkSpaceRes();
                var workspace = await db.LasaWorkspace.AsQueryable().Where(r => r.Id == id && r.IsDelete == false)
                    .FirstAsync();
                if (workspace != null)
                {
                    var sysuser = db.User.AsQueryable()
                        .LeftJoin<LasaSpaceUser>((r, a) => r.Id == a.UserId)
                        .Where((r, a) => a.WorkSpaceId == id)
                        .Select((r, a) => r).ToList();
                    var uav = db.LasaDronePort.AsQueryable()
                        .LeftJoin<LasaSpaceDevice>((r, a) => r.Id == a.DeviceId)
                        .Where((r, a) => a.WorkSpaceId == id)
                        .Select((r, a) => r).ToList();
                    var lockfly = db.LasaSpaceLockFly.AsQueryable().Where(r => r.WorkSpaceId == id).ToList();
                    res.users = sysuser;
                    res.LasaDronePort = uav;
                    res.lasaSpaceLockFlies = lockfly;
                    res.workspace = workspace;
                }

                return new Response<WorkSpaceRes>
                {
                    Result = res
                };
            }
        }

        //删除项目 
        public async Task<Response<bool>> DeleteWorkspace(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.LasaWorkspace.UpdateAsync(u => new LasaWorkspace
                {
                    IsDelete = true
                }, u => u.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "删除成功" };
                else
                    return new Response<bool> { Result = false, Message = "删除失败" };
            }
        }

        //归档项目 
        public async Task<Response<bool>> CompleteWorkspace(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.LasaWorkspace.UpdateAsync(u => new LasaWorkspace
                {
                    Sate = 2
                }, u => u.Id == id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "归档成功" };
                else
                    return new Response<bool> { Result = false, Message = "归档失败" };
            }
        }

        #endregion

        public async Task ExecuteFlyTask(string taskId)
        {
            // 任务信息
            var task = await Repository.ChangeRepository<SugarRepositiry<LasaTask>>().GetByIdAsync(taskId);
            // 航线文件信息
            var airLine = await Repository.ChangeRepository<SugarRepositiry<LasaAirLine>>()
                .GetByIdAsync(task.AirLineId);
            // 航线文件链接
            var wpml = airLine.WPML;
            //  查询sn
            var dronePort = await Repository.ChangeRepository<SugarRepositiry<LasaDronePort>>()
                .GetByIdAsync(task.TaskDronePort);
            if (dronePort == null)
            {
                throw new Exception("指定机场不存在");
            }

            var serialNo = dronePort.Sn;
            var topic = string.Format(GatewayManager.FlightTaskPrepare, serialNo);
            var request = new TopicServicesRequest<object>()
            {
                method = "flighttask_prepare",
                tid = Guid.NewGuid().ToString(),
                bid = Guid.NewGuid().ToString(),
                timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds()
            };

            dynamic data = new ExpandoObject();
            data.flight_id = Guid.NewGuid().ToString(); // 用任务id 作为
            data.execute_time = DateTimeOffset.Now.ToUnixTimeMilliseconds();
            //{"0":"立即任务","1":"定时任务","2":"条件任务"}
            // 立即任务和定时任务均由execute_time指定执行时间；条件任务支持ready_conditions字段指定任务就绪条件，设备可在指定时间段内满足就绪条件后即可执行；立即任务媒体上传优先级最高，定时任务和条件任务媒体上传优先级相同
            // 若task_type任务类型指定为“立即执行”时，设备端限制了30s的时间误差，若设备收到指令的时间与execute_time相差超过30s，将报错且该任务无法正常执行。
            data.task_type = task.TaskType;
            var md5 = await _minioService.GetMetaObject(wpml, "");
            // todo 临时固定代码
            // http://175.27.168.120:6013/test/2025062209390863860047.kmz
            // wpml = await _minioService.GetObjectUrl("test", "2025062209390863860047.kmz");
            data.file = new
            {
                url = wpml,
                fingerprint = md5
            };
            //任务执行条件
            data.executable_conditions = new
            {
                // 可执行任务的机场或飞行器最低存储容量，机场或飞行器存储容量不满足 storage_capacity 时，任务执行失败。
                // todo 容量单位是什么？  一个图片多少兆，预计拍多少图片？
                // 1. 需要多少容量
                // 2. 多少图片需要多少容量
                // 3. 要存多少图片
                // 4. 
                storage_capacity = 1000 // todo 50GB左右共 ，其它型号不一定啊？ 先不考虑等它报错 
            };
            // todo 1. 查询上报断点 2. 断点续飞方法支持
            if (false)
            {
                data.break_point = new
                {
                    index = 1, // 断点序号
                    state = 1, // “0":"在航段上","1":"在航点上
                    progress = 1.0, // {"max":"1.0","min":"0"} 
                    wayline_id = "" // 航线id
                };
            }

            // 返航高度 {"max":1500,"min":20,"step":"","unit_name":"米 / m"}
            data.rth_altitude = task.ReturnAltitude; // todo  取自任务
            // 返航高度模式 {"0":"智能高度","1":"设定高度"}
            // 智能返航模式下，飞行器将自动规划最佳返航高度。
            // 大疆机场当前不支持设置返航高度模式，只能选择'设定高度'模式。当环境，光线不满足视觉系统要求时（譬如傍晚阳光直射、夜间弱光无光），飞行器将使用您设定的返航高度进行直线返航
            data.rth_mode = 0;
            // {"0":"返航","1":"悬停","2":"降落"}
            // 	失控动作，当前固定传的值是 0，即返航。注意该枚举值定义跟飞控跟机场定义的不一致，机场端会进行转换。
            data.out_of_control_action = task.LossOfControlAction;
            // 航线失控动作 保持跟 KMZ 文件一致
            // {"0":"继续执行航线任务","1":"退出航线任务，执行遥控器失控动作"}
            data.exit_wayline_when_rc_lost = 1;
            // 航线精度类型 {"0":"GPS 任务","1":"高精度 RTK 任务"}
            // 高精度 RTK 任务：飞行器起飞后会在空中等待 RTK 收敛后再执行任务，等待 RTK 收敛的过程中无法暂停任务。
            // 默认场景建议使用该模式。GPS 任务：飞行器无需等待 RTK 收敛便可以直接开始执行。精度要求不高的任务或对起飞时效性要求较高的任务建议使用该模式。
            // data.wayline_precision_type = task.WaylinePrecisionType; // 值来自任务
            data.wayline_precision_type = task.WaylinePrecisionType;
            // 是否在模拟器中执行任务 todo  调试时使用
            /*data.simulate_mission = new
            {
                //118.309405,35.14035 应用科学城坐标
                //是否开启模拟器任务
                //{"0":"不开启","1":"开启"}
                is_enable = 1,
                // 纬度 {"max":"90.0","min":"-90.0"}
                latitude = 35.140331,
                // 经度 {"max":"180.0","min":"-180.0"}
                longitude = 118.309419,
                // 高度 {"max":"9999.9","min":"-9999.9"unit_name":"米 / m"}
                altitude = 120.0
            };*/
            // 飞行安全预检查
            // {"0":"关闭","1":"开启"}
            // 设置一键起飞和航线任务中的飞行安全是否预先检查。此字段为可选，默认为0，值为0表示关闭，1表示开启。飞行安全预先检查表示: 飞行器执行任务前，检查自身作业区文件是否与云端一致，如果不一致则拉取文件更新，如果一致则不处理
            data.flight_safety_advance_check = 0;

            if (data.task_type == 2)
            {
                // 任务就绪条件 可选字段。条件任务（即 task_type 为2）时必填，其他类型任务会忽略该字段。下发条件任务后，设备会定频检查 ready_conditions 是否全部满足，若全部满足则会有 flighttask_ready 事件通知。且设备端接收 flighttask_execute 指令时，也会检查任务的 ready_conditions 是否已全部满足。
                data.ready_conditions = new
                {
                    // 可执行任务的飞行器电池电量百分比阈值，任务开始执行时的飞行器电量必须大于
                    // todo 获取指定值 计算 还是
                    battery_capacity = 77, // 设备电量百分比，范围 0-100
                    // todo  设定时间
                    begin_time = DateTimeOffset.Now.ToUnixTimeMilliseconds() + 50000, // 任务开始执行时间必须大于该值 
                    // todo 设定结束时间
                    end_time = DateTimeOffset.Now.ToUnixTimeMilliseconds() + 100000, // 任务结束时间必须
                };
            }

            request.SetData(data);
            // 任务下发
            await _mqttClientManager.PublishAsync(topic, JsonConvert.SerializeObject(request));
            // 记录任务中间信息
            var taskAssign = new LasaTaskAssign
            {
                Id = Guid.NewGuid().ToString(),
                Bid = request.bid,
                Tid = request.tid,
                FlightId = data.flight_id,
                GatewaySn = dronePort.Sn,
                AirlineId = task.AirLineId,
                Status = 0,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                TaskId = taskId,
                Md5 = md5,
                Wpml = wpml
            };
            await Repository.ChangeRepository<SugarRepositiry<LasaTaskAssign>>().InsertAsync(taskAssign);
            // todo 更新任务状态？
           
        }

        public async Task PendingFlyTask(string taskId)
        {
            // todo 
            // todo 查看任务状态（待执行，任务执行，已暂停，已挂起） 1. 待执行，任务执行，需要先取消任务 2. 已暂停，直接挂起任务 3. 已挂起，返回
            throw new NotImplementedException();
        }

        public Task<string> UploadFile(IFormFile xmlFile)
        {
            return _minioService.UploadFile(xmlFile, "");
        }

        #region 添加地图作业区域

        /// <summary>
        /// 添加地图作业区域
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<string>> AddWorkArea(LasaShpData model)
        {
            var _user = _auth.GetCurrentUser().User;
            model.CreateTime = DateTime.Now;
            model.CreateUser = _user.Id.ToString();
            model.CreateUserName = _user.Name.ToString();
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //获取主键
                string id = Guid.NewGuid().ToString();
                model.Id = id;

                //格式化数据
                string _wktModel = _commonDataManager.WktDataConvert(model.Geom, "MULTIPOLYGON ZM", 4);

                model.Geom = null;

                StringBuilder geomSql = new StringBuilder();
                geomSql.AppendFormat(
                    $" update lasa_shpdata set \"Geom\" = st_geomfromtext('{_wktModel}',4326) where \"Id\" = '{id}'");

                //更新面积
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat(
                    $" update lasa_shpdata set \"Area\" = st_area(st_transform(\"Geom\",4527)) where \"Geom\" is not null and  \"Id\" = '{id}'");

                //更新周长
                StringBuilder sqlle = new StringBuilder();
                sqlle.AppendFormat(
                    $" update lasa_shpdata set \"Length\" = ST_Perimeter(st_transform(\"Geom\",4527)) where \"Geom\" is not null and  \"Id\" = '{id}'");

                //使用事务提交数据
                var transFlag = await db.UseTranAsync(async () =>
                {
                    //插入图斑数据
                    var flag = await db.Insertable(model).ExecuteCommandAsync();

                    //修改图斑数据
                    var flagGeom = await db.Ado.ExecuteCommandAsync(geomSql.ToString());

                    //修改图斑面积
                    var flagUpdate = await db.Ado.ExecuteCommandAsync(sql.ToString());

                    //修改图斑周长
                    var lengthUpdate = await db.Ado.ExecuteCommandAsync(sqlle.ToString());
                });
                if (transFlag.IsSuccess)
                    return new Response<string>
                    {
                        Result = id,
                        Message = "新增成功"
                    };
                else
                    return new Response<string>
                    {
                        Message = "新增失败"
                    };
            }
        }

        /// <summary>
        /// 更新地图作业区域
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<Response<string>> UpdateWorkArea(LasaShpData model)
        {
            using (var db = base.UnitWork.CreateContext().Db.CopyNew())
            {
                //格式化数据
                string _wktModel = _commonDataManager.WktDataConvert(model.Geom, "MULTIPOLYGON ZM", 4);

                model.Geom = null;

                StringBuilder geomSql = new StringBuilder();
                geomSql.AppendFormat(
                    $" update lasa_shpdata set \"Geom\" = st_geomfromtext('{_wktModel}',4326) where \"Id\" = '{model.Id}'");

                //更新面积
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat(
                    $" update lasa_shpdata set \"Area\" = st_area(st_transform(\"Geom\",4527)) where \"Geom\" is not null and  \"Id\" = '{model.Id}'");

                //更新周长
                StringBuilder sqlle = new StringBuilder();
                sqlle.AppendFormat(
                    $" update lasa_shpdata set \"Length\" = ST_Perimeter(st_transform(\"Geom\",4527)) where \"Geom\" is not null and  \"Id\" = '{model.Id}'");

                //使用事务提交数据
                var transFlag = await db.UseTranAsync(async () =>
                {
                    //插入图斑数据
                    var flag = await db.Updateable(model).ExecuteCommandAsync();

                    //修改图斑数据
                    var flagGeom = await db.Ado.ExecuteCommandAsync(geomSql.ToString());

                    //修改图斑面积
                    var flagUpdate = await db.Ado.ExecuteCommandAsync(sql.ToString());

                    //修改图斑周长
                    var lengthUpdate = await db.Ado.ExecuteCommandAsync(sqlle.ToString());
                });
                if (transFlag.IsSuccess)
                    return new Response<string>
                    {
                        Result = model.Id,
                        Message = "更新成功"
                    };
                else
                    return new Response<string>
                    {
                        Message = "更新失败"
                    };
            }
        }

        //删除地图作业区域
        public async Task<Response<bool>> DeleteWorkArea(string id)
        {
            using (var db = UnitWork.CreateContext())
            {
                await db.LasaShpData.DeleteByIdAsync(id);
                if (db.Commit())
                    return new Response<bool> { Result = true, Message = "删除成功" };
                else
                    return new Response<bool> { Result = false, Message = "删除失败" };
            }
        }

        /// <summary>
        /// 获取地图作业区域列表
        /// </summary>
        /// <param name="workspaceid">项目id</param>
        /// <returns></returns>
        public async Task<Response<List<LasaShpData>>> GetWorkAreaList(string workspaceid, int? state, string type)
        {
            using (var db = UnitWork.CreateContext())
            {
                StringBuilder sql = new StringBuilder();
                sql.AppendFormat($" Select * from   lasa_shpdata where  \"WorkSpaceId\" = '{workspaceid}'");
                var list = db.Db.SqlQueryable<LasaShpData>(sql.ToString()).ToList();
                if (!string.IsNullOrEmpty(type) && list.Count > 0)
                {
                    list = list.Where(r => r.Type == type).ToList();
                }

                if (state != null)
                {
                    list = list.Where(r => r.State == state).ToList();
                }

                return new Response<List<LasaShpData>>
                {
                    Result = list
                };
            }
        }

        #endregion

        public async Task<string> TestExecuteFlyTask(string flightid)
        {
            // flighttask_prepare method 
            /// thing/product/{gateway_sn}/services 主题
            // todo 执行下发任务
            var request = new TopicServicesRequest<object>();
            dynamic data = new ExpandoObject();
            data.flight_id = flightid;
            request.SetMethod("flighttask_execute")
                .SetTid(flightid)
                .SetBid(Guid.NewGuid().ToString())
                .SetData(data);
            return JsonConvert.SerializeObject(request);
        }

        public LasaDronePort GetDroneDockBySn(string gatewaySn)
        {
            var droneDock = Repository.GetSingle(r => r.Sn == gatewaySn);
            return droneDock;
        }

        public LasaTaskAssign GetTaskAssignByBidAndTid(string bid, string tid)
        {
            return Repository
                .ChangeRepository<SugarRepositiry<LasaTaskAssign>>()
                .GetSingle(r => r.Bid == bid && r.Tid == tid && r.Status == 0);
        }


        public LasaTaskAssign GetTaskAssignByFlightId(string flightId)
        {
            return Repository
                .ChangeRepository<SugarRepositiry<LasaTaskAssign>>()
                .GetSingle(r => r.FlightId == flightId);
        }
    }
}