rain
2024-08-17 608dea1f05bb2e33df4df050380fa49602b6c3ff
src/main/java/com/dji/sample/droneairport/service/impl/RegistServiceImpl.java
@@ -1,22 +1,43 @@
package com.dji.sample.droneairport.service.impl;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
//import com.alibaba.fastjson.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dji.sample.common.model.ResponseResult;
import com.dji.sample.component.redis.RedisOpsUtils;
import com.dji.sample.droneairport.dao.DeviceExpanSionDao;
import com.dji.sample.droneairport.dao.DbUploadMapper;
import com.dji.sample.droneairport.dao.DeviceExpanSionMapper;
import com.dji.sample.droneairport.model.Entity.DbUploadEntity;
import com.dji.sample.droneairport.model.Entity.DeviceExpanSionEntity;
import com.dji.sample.droneairport.model.dto.AddDeviceDto;
import com.dji.sample.droneairport.model.dto.DroneStateDto;
import com.dji.sample.droneairport.model.dto.RegistDto;
import com.dji.sample.droneairport.model.dto.*;
import com.dji.sample.droneairport.model.param.ReturnTaskParam;
import com.dji.sample.droneairport.service.RegistService;
import com.dji.sample.droneairport.utils.AuthUtil;
import com.dji.sample.droneairport.utils.SM2.Utils;
import com.dji.sample.droneairport.utils.SM4Util;
import com.dji.sample.manage.dao.IDeviceMapper;
import com.dji.sample.manage.model.entity.DeviceEntity;
import com.dji.sample.manage.model.enums.DeviceModeCodeEnum;
import com.dji.sample.manage.model.enums.DockModeCodeEnum;
import com.dji.sample.manage.model.receiver.OsdDockReceiver;
import com.dji.sample.manage.model.receiver.OsdSubDeviceReceiver;
import com.dji.sample.manage.service.IDeviceRedisService;
import com.dji.sample.patches.dao.GetPatchesMapper;
import com.dji.sample.patches.dao.TaskInfoMapper;
import com.dji.sample.patches.model.entity.LotInfo;
import com.dji.sample.patches.model.entity.TaskInfo;
import com.dji.sample.patches.utils.TimerUtil;
import com.dji.sample.wayline.dao.IWaylineFileMapper;
import com.dji.sample.wayline.dao.IWaylineJobMapper;
import com.dji.sample.wayline.model.entity.WaylineFileEntity;
import com.dji.sample.wayline.model.entity.WaylineJobEntity;
import com.dji.sample.wayline.model.enums.WaylineJobStatusEnum;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.bouncycastle.crypto.InvalidCipherTextException;
@@ -24,12 +45,18 @@
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.*;
import java.util.*;
import java.util.stream.Collectors;
import static com.dji.sample.droneairport.utils.TaskAllocator.assignTasks;
import static com.dji.sample.patches.utils.TimerUtil.getCurrentTimestampPlus8Hours;
import static com.dji.sample.patches.utils.TimerUtil.getNextDayEightAMTimestamp;
@Service
public class RegistServiceImpl implements RegistService {
@@ -38,14 +65,26 @@
    @Autowired
    private IDeviceRedisService redisService;
    @Autowired
    private DeviceExpanSionDao expanSionDao;
    private DeviceExpanSionMapper expanSionMapper;
    @Autowired
    private TaskInfoMapper taskInfoMapper;
    @Autowired
    private GetPatchesMapper patchesMapper;
    @Autowired
    private TimerUtil timerUtil;
    @Autowired
    private IDeviceMapper deviceMapper;
    @Autowired
    private IWaylineJobMapper waylineJobMapper;
    @Autowired
    private IWaylineFileMapper fileMapper;
    @Autowired
    private DbUploadMapper dbUploadMapper;
    public String registPort(DeviceExpanSionEntity airport) {
        try {
            RegistDto registDto = airportEntityToDto(airport);
            // 构建请求体
            String jsonBody = buildRequestBody(registDto);
            // 设置请求头
            String base64 = SM4Util.encrypt("jsimjrby3wqb7dbq", jsonBody);
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
@@ -53,13 +92,13 @@
            headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
            headers.set("Accept-Language", "zh-CN,zh;q=0.9");
            headers.setConnection("keep-alive");
            headers.set("x-lc-token", AuthUtil.getToken());
            headers.set("x-lc-secret", Utils.hexToBase64(Utils.encrypt("jsimjrby3wqb7dbq", "044D6061FC08A19D3F32CEAA8CF6679B40500008FD741FC26DE7E50AEBF3A9115D47274437730EADEDAEF0CCC4853C5F0B35B30C6AEA83A5F6FBCA4ABEAC9E3B98")));
            headers.set("x-auth-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3b3Jrc3BhY2VfaWQiOiJlM2RlYTBmNS0zN2YyLTRkNzktYWU1OC00OTBhZjMyMjgwNjkiLCJzdWIiOiJDbG91ZEFwaVNhbXBsZSIsInVzZXJfdHlwZSI6IjEiLCJuYmYiOjE3MjA2NTg3NDMsImxvZyI6IkxvZ2dlcltjb20uZGppLnNhbXBsZS5jb21tb24ubW9kZWwuQ3VzdG9tQ2xhaW1dIiwiaXNzIjoiREpJIiwiaWQiOiI5Y2MwMGY3Zi0yODMwLTRmM2UtYjdmNC1lN2E1ZjIzYjNjNGYiLCJleHAiOjE4MDcwNTg3NDMsImlhdCI6MTcyMDY1ODc0MywidXNlcm5hbWUiOiJhZG1pbkRQIn0.CrRFYUTK357HleqrrfL7nLdwFJw5Bcv3ms33n_Or8eM");
            headers.set("x-lc-token", "");
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    "https://xcx.geoway.com.cn:8033/v1/droneAirport/RegistService",
                    "http://localhost:6789/droneAirport/test",
                    HttpMethod.POST,
                    requestEntity,
                    String.class);
@@ -67,86 +106,397 @@
        } catch (Exception e) {
            // 异常处理
            throw new IllegalArgumentException("Request failed: " + e.getMessage(), e);
            throw new IllegalArgumentException("无人机机场注册失败: " + e.getMessage());
        }
    }
    private String buildRequestBody(RegistDto dto) {
//    private String buildRequestBody(RegistDto dto) {
//        try {
//            return objectMapper.writeValueAsString(dto);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("数据有误", e);
//        }
//    }
    public <T> String buildRequestBody(T obj) {
        try {
            return objectMapper.writeValueAsString(dto);
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("数据有误", e);
            throw new RuntimeException("对象转换为JSON字符串时发生错误", e);
        }
    }
    @Override
    public String addDrone(String workspaceId) {
        try {
            DeviceExpanSionEntity airport = expanSionDao.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
            DeviceExpanSionEntity airport = expanSionMapper.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                    .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                    .eq(DeviceExpanSionEntity::getType, 0));
            DeviceExpanSionEntity drone = expanSionDao.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
            DeviceExpanSionEntity drone = expanSionMapper.selectOne(new LambdaQueryWrapper<DeviceExpanSionEntity>()
                    .eq(DeviceExpanSionEntity::getWorkspaceId, workspaceId)
                    .eq(DeviceExpanSionEntity::getType, 1));
            AddDeviceDto dto = deviceEntityToDto(drone);
            // 构建请求体
            String jsonBody = buildRequestBody(dto);
            String base64 = SM4Util.encrypt("jsimjrby3wqb7dbq", jsonBody);
            String secret = enSM2("jsimjrby3wqb7dbq", "044D6061FC08A19D3F32CEAA8CF6679B40500008FD741FC26DE7E50AEBF3A9115D47274437730EADEDAEF0CCC4853C5F0B35B30C6AEA83A5F6FBCA4ABEAC9E3B98");
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
            headers.set("Accept-Language", "zh-CN,zh;q=0.9");
            headers.setConnection("keep-alive");
            headers.set("x-lc-token", AuthUtil.getToken());
            headers.set("x-lc-secret", secret);
            headers.set("x-auth-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3b3Jrc3BhY2VfaWQiOiJlM2RlYTBmNS0zN2YyLTRkNzktYWU1OC00OTBhZjMyMjgwNjkiLCJzdWIiOiJDbG91ZEFwaVNhbXBsZSIsInVzZXJfdHlwZSI6IjEiLCJuYmYiOjE3MjA2NTg3NDMsImxvZyI6IkxvZ2dlcltjb20uZGppLnNhbXBsZS5jb21tb24ubW9kZWwuQ3VzdG9tQ2xhaW1dIiwiaXNzIjoiREpJIiwiaWQiOiI5Y2MwMGY3Zi0yODMwLTRmM2UtYjdmNC1lN2E1ZjIzYjNjNGYiLCJleHAiOjE4MDcwNTg3NDMsImlhdCI6MTcyMDY1ODc0MywidXNlcm5hbWUiOiJhZG1pbkRQIn0.CrRFYUTK357HleqrrfL7nLdwFJw5Bcv3ms33n_Or8eM");
            headers.set("x-lc-token", "");
            // 构建请求实体
            HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
            // 发送请求
            RestTemplate restTemplate = new RestTemplate();
            String response = restTemplate.postForObject("https://xcx.geoway.com.cn:8033/v1/droneAirport/addDevice", requestEntity, String.class);
            ResponseEntity<String> response = restTemplate.exchange(
                    "http://localhost:6789/droneAirport/test",
                    HttpMethod.POST,
                    requestEntity,
                    String.class);
            registPort(airport);
            return response;
            return response.getBody();
        } catch (Exception e) {
            // 异常处理
            throw new IllegalArgumentException("Request failed: " + e.getMessage(), e);
            throw new IllegalArgumentException("无人机机场设备注册失败: " + e.getMessage());
        }
    }
    @Override
    public ResponseResult getDroneState(String deviceId) throws Exception {
    public String getDroneState(String deviceId) throws Exception {
        DroneStateDto data = getAirportFromCache(deviceId);
        String json = JSON.toJSONString(data);
        String SM4Screct = SM4Util.encrypt("jsimjrby3wqb7dbq", json);
        String SM2Screct = enSM2(SM4Screct, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
        return ResponseResult.success(SM2Screct);
        return SM4Screct;
    }
    //    @Override
//    public ResponseResult authorization(String base64, String Secret) throws Exception {
//        String sm4Secrect = deSM2(Secret, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
//        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
//        JSONObject jsonObject = new JSONObject(decryptedJson);
//        String deviceId = jsonObject.getStr("deviceid");
//        boolean online = redisService.checkDeviceOnline(deviceId);
//        if (online) {
//            return ResponseResult.success(200, "无人机机场授权成功!", "", "");
//        }
//        return ResponseResult.error(500, "无人机机场授权失败!");
//    }
    @Override
    public void noAuthorization(String sn) {
        AuthorDto dto = new AuthorDto();
        dto.setSn(sn);
        dto.setStatus(0);
        String jsonBody = buildRequestBody(dto);
        String base64 = SM4Util.encrypt("jsimjrby3wqb7dbq", jsonBody);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
        headers.set("Accept-Language", "zh-CN,zh;q=0.9");
        headers.setConnection("keep-alive");
        headers.set("x-auth-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3b3Jrc3BhY2VfaWQiOiJlM2RlYTBmNS0zN2YyLTRkNzktYWU1OC00OTBhZjMyMjgwNjkiLCJzdWIiOiJDbG91ZEFwaVNhbXBsZSIsInVzZXJfdHlwZSI6IjEiLCJuYmYiOjE3MjA2NTg3NDMsImxvZyI6IkxvZ2dlcltjb20uZGppLnNhbXBsZS5jb21tb24ubW9kZWwuQ3VzdG9tQ2xhaW1dIiwiaXNzIjoiREpJIiwiaWQiOiI5Y2MwMGY3Zi0yODMwLTRmM2UtYjdmNC1lN2E1ZjIzYjNjNGYiLCJleHAiOjE4MDcwNTg3NDMsImlhdCI6MTcyMDY1ODc0MywidXNlcm5hbWUiOiJhZG1pbkRQIn0.CrRFYUTK357HleqrrfL7nLdwFJw5Bcv3ms33n_Or8eM");
        headers.set("x-lc-token", "");
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                "http://localhost:6789/droneAirport/test",
                HttpMethod.POST,
                requestEntity,
                String.class);
    }
    @Override
    public ResponseResult authorization(String base64, String enSm4) throws Exception {
        String sm4Secrect = deSM2(enSm4, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
    public void Authorization(String sn) {
        AuthorDto dto = new AuthorDto();
        dto.setSn(sn);
        dto.setStatus(1);
        String jsonBody = buildRequestBody(dto);
        String base64 = SM4Util.encrypt("jsimjrby3wqb7dbq", jsonBody);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(List.of(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL));
        headers.set("Accept-Language", "zh-CN,zh;q=0.9");
        headers.setConnection("keep-alive");
        headers.set("x-auth-token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ3b3Jrc3BhY2VfaWQiOiJlM2RlYTBmNS0zN2YyLTRkNzktYWU1OC00OTBhZjMyMjgwNjkiLCJzdWIiOiJDbG91ZEFwaVNhbXBsZSIsInVzZXJfdHlwZSI6IjEiLCJuYmYiOjE3MjA2NTg3NDMsImxvZyI6IkxvZ2dlcltjb20uZGppLnNhbXBsZS5jb21tb24ubW9kZWwuQ3VzdG9tQ2xhaW1dIiwiaXNzIjoiREpJIiwiaWQiOiI5Y2MwMGY3Zi0yODMwLTRmM2UtYjdmNC1lN2E1ZjIzYjNjNGYiLCJleHAiOjE4MDcwNTg3NDMsImlhdCI6MTcyMDY1ODc0MywidXNlcm5hbWUiOiJhZG1pbkRQIn0.CrRFYUTK357HleqrrfL7nLdwFJw5Bcv3ms33n_Or8eM");
        headers.set("x-lc-token", "");
        // 构建请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(base64, headers);
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                "http://localhost:6789/droneAirport/test",
                HttpMethod.POST,
                requestEntity,
                String.class);
    }
    @Override
    public ReturnTaskParam AddTask(String base64, String Secret, String username) throws Exception {
        ReturnTaskParam param = new ReturnTaskParam();
        String taskId = UUID.randomUUID().toString();
        String traceid = UUID.randomUUID().toString();
        String sm4Secrect = deSM2(Secret, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
        JSONObject jsonObject = new JSONObject(decryptedJson);
        String deviceId = jsonObject.getStr("deviceid");
        boolean online = redisService.checkDeviceOnline(deviceId);
        if (online) {
            return ResponseResult.success(200, "无人机机场授权成功!", "");
        AddTaskDto addTaskDto = jsonToDto(jsonObject);
        TaskInfo taskInfo = new TaskInfo();
        List<String> listx = convertStringToList(addTaskDto.getDeviceid());
        taskInfo.setId(traceid);
        taskInfo.setTaskId(taskId);
        taskInfo.setName(addTaskDto.getBizidname());
        taskInfo.setDeviceIds(addTaskDto.getDeviceid());
        taskInfo.setCreateUser(username);
        param.setTraceId(traceid);
        taskInfoMapper.insert(taskInfo);
        // 转换 TaskListDto 为 LotInfo
        List<LotInfo> lotInfos = new ArrayList<>();
        List<TaskListDto> tasklist = addTaskDto.getTasklist();
        for (TaskListDto taskListDto : tasklist) {
            LotInfo lotInfo = convertToLotInfo(taskListDto);
            lotInfo.setTaskId(taskId);
            lotInfo.setType(1);
            lotInfo.setTaskName(addTaskDto.getBizidname());
            lotInfo.setUserName(username);
            lotInfos.add(lotInfo);
            patchesMapper.insert(lotInfo);
        }
        return ResponseResult.error(500, "无人机机场授权失败!");
        // 获取机场信息
        List<Airport> airports = getAirportsBySn(listx);
        List<AirportTasks> airportTasks = assignTasks(airports, lotInfos);
        // 处理并插入图斑到数据库
        processAndInsertTasks(airportTasks);
        // 根据机场位置生成航线任务
        for (AirportTasks airportTask : airportTasks) {
            Airport airport = airportTask.getAirport();
            List<LotInfo> lotInfosForAirport = airportTask.getTasks();
            if (!lotInfosForAirport.isEmpty()) {
                String waylineName = TimerUtil.getTimeName();
                MultipartFile multipartFile = timerUtil.getFile(waylineName, lotInfosForAirport, airport.getLat(), airport.getLon());
                WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, airport.getWorkspaceId(), username);
                Long time = getNextDayEightAMTimestamp(getDistinctTaskIdCount(airport.getWorkspaceId()));
                List<List<Long>> listOfLists = new ArrayList<>();
                List<Long> sublist = new ArrayList<>();
                sublist.add(time);
                listOfLists.add(sublist);
                List<Long> lists1 = new ArrayList<>();
                lists1.add(time);
                String times = TimerUtil.convertTimestampToFormattedString(time);
                param.setJobId(SM4Util.encrypt("jsimjrby3wqb7dbq", taskId));
                timerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, taskId + "~" + airport.getWorkspaceId(), airport.getDockSn());
                timerUtil.updatePatchesStatu(lotInfosForAirport);
            }
        }
        return param;
    }
    private String buildRequestBody(AddDeviceDto dto) {
        try {
            return objectMapper.writeValueAsString(dto);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("数据有误", e);
    @Override
    public ReturnTaskParam updateTask(String base64, String Secret, String username) throws Exception {
        ReturnTaskParam param = new ReturnTaskParam();
        String traceid = UUID.randomUUID().toString();
        String sm4Secrect = deSM2(Secret, "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D");
        String decryptedJson = SM4Util.decrypt(sm4Secrect, base64);
        JSONObject jsonObject = new JSONObject(decryptedJson);
        UpdataTaskDto addTaskDto = UpjsonToDto(jsonObject);
        String taskId = addTaskDto.getTaskid();
        String Bizidname = getBizidnameByTask(taskId);
        delPatchesByTaskId(taskId);
        delTaskInfo(taskId);
        delWaylineJob(taskId);
        TaskInfo taskInfo = new TaskInfo();
        List<String> listx = convertStringToList(addTaskDto.getDeviceid());
        taskInfo.setId(traceid);
        taskInfo.setTaskId(taskId);
        taskInfo.setName(Bizidname);
        taskInfo.setDeviceIds(addTaskDto.getDeviceid());
        taskInfo.setCreateUser(username);
        param.setTraceId(traceid);
        taskInfoMapper.insert(taskInfo);
        // 转换 TaskListDto 为 LotInfo
        List<LotInfo> lotInfos = new ArrayList<>();
        List<TaskListDto> tasklist = addTaskDto.getTasklist();
        for (TaskListDto taskListDto : tasklist) {
            LotInfo lotInfo = convertToLotInfo(taskListDto);
            lotInfo.setTaskId(taskId);
            lotInfo.setType(1);
            lotInfo.setTaskName(Bizidname);
            lotInfo.setUserName(username);
            lotInfos.add(lotInfo);
            patchesMapper.insert(lotInfo);
        }
        // 获取机场信息
        List<Airport> airports = getAirportsBySn(listx);
        List<AirportTasks> airportTasks = assignTasks(airports, lotInfos);
        // 处理并插入图斑到数据库
        processAndInsertTasks(airportTasks);
        // 根据机场位置生成航线任务
        for (AirportTasks airportTask : airportTasks) {
            Airport airport = airportTask.getAirport();
            List<LotInfo> lotInfosForAirport = airportTask.getTasks();
            if (!lotInfosForAirport.isEmpty()) {
                String waylineName = TimerUtil.getTimeName();
                MultipartFile multipartFile = timerUtil.getFile(waylineName, lotInfosForAirport, airport.getLat(), airport.getLon());
                WaylineFileEntity waylineFile = timerUtil.backWayline(multipartFile, waylineName, airport.getWorkspaceId(), username);
                // 将为规划的图斑状态更新为已规划
                Long time = getNextDayEightAMTimestamp(getDistinctTaskIdCount(airport.getWorkspaceId()));
                List<List<Long>> listOfLists = new ArrayList<>();
                List<Long> sublist = new ArrayList<>();
                sublist.add(time);
                listOfLists.add(sublist);
                List<Long> lists1 = new ArrayList<>();
                lists1.add(time);
                String times = TimerUtil.convertTimestampToFormattedString(time);
                param.setJobId(taskId);
                timerUtil.sendPostWithParameters(waylineName, waylineFile.getWaylineId(), times, lists1, listOfLists, airport.getWorkspaceId() + "~" + taskId, airport.getDockSn());
                timerUtil.updatePatchesStatu(lotInfosForAirport);
            }
        }
        return param;
    }
    @Override
    public ResponseResult cancelTask(String taskId) {
        LambdaUpdateWrapper<WaylineJobEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.like(WaylineJobEntity::getJobId, taskId)
                .set(WaylineJobEntity::getStatus, 4);
        waylineJobMapper.update(null, updateWrapper);
        return null;
    }
    public void processAndInsertTasks(List<AirportTasks> airportTasks) {
        for (AirportTasks airportTasksEntry : airportTasks) {
            Airport airport = airportTasksEntry.getAirport();
            List<LotInfo> tasks = airportTasksEntry.getTasks();
            // 处理每个任务
            for (LotInfo lotInfo : tasks) {
                lotInfo.setWorkspaceId(airport.getWorkspaceId()); // 设置 workspaceId
                patchesMapper.updateById(lotInfo);
            }
        }
    }
    @Override
    public ResponseResult queryTaskStatus(String taskid) {
        List<WaylineJobEntity> jobEntity = waylineJobMapper.selectList(new LambdaQueryWrapper<WaylineJobEntity>().like(WaylineJobEntity::getJobId, taskid));
        if (jobEntity == null || jobEntity.isEmpty()) {
            return ResponseResult.error(201, "查询无人机机场任务状态失败!");
        }
        // 检查是否所有 status 都等于 4
        boolean allStatusAreFour = jobEntity.stream()
                .allMatch(job -> job.getStatus() == 4);
        // 检查是否所有 status 都等于 3
        boolean allStatusAreThree = jobEntity.stream()
                .allMatch(job -> job.getStatus() == 3);
        if (allStatusAreFour) {
            return ResponseResult.error(204, "查询无人机机场任务状态成功!");
        } else if (allStatusAreThree) {
            return ResponseResult.error(200, "查询无人机机场任务状态成功!");
        } else {
            return ResponseResult.error(202, "查询无人机机场任务状态成功!");
        }
    }
    /**
     * 根据任务 ID 查找对应的 DB 文件路径
     *
     * @param taskId 任务 ID
     * @return 匹配的 DB 文件路径列表
     */
    public String findDbFilesByTaskId(String taskId) {
        DbUploadEntity entity = dbUploadMapper.selectOne(new LambdaQueryWrapper<DbUploadEntity>()
                .eq(DbUploadEntity::getTaskId, taskId));
        if (entity != null) {
            DbUploadDto dto = DbEntityToDto(entity);
            return SM4Util.encrypt("jsimjrby3wqb7dbq", buildRequestBody(dto));
        }
        return null;
//        File baseDir = new File(BASE_DIR);
//
//        // 检查基础目录是否存在并且是目录
//        if (!baseDir.exists() || !baseDir.isDirectory()) {
//            throw new IllegalStateException("Base directory does not exist or is not a directory.");
//        }
//
//        // 构建文件路径
//        File targetDir = new File(baseDir, taskId);
//        File dbFile = new File(targetDir, ".db");
//
//        // 如果文件存在,则返回文件路径
//        if (dbFile.exists()) {
//            return dbFile.getAbsolutePath();
//        }
//
//        return null; // 或者抛出异常,视需求而定
    }
    public void delPatchesByTaskId(String taskId) {
        patchesMapper.delete(new LambdaUpdateWrapper<LotInfo>().eq(LotInfo::getTaskId, taskId));
    }
    public DbUploadDto DbEntityToDto(DbUploadEntity entity) {
        DbUploadDto dto = new DbUploadDto();
        dto.setAttachmentCount(entity.getAttachmentCount());
        dto.setCount(entity.getCount());
        dto.setSign(entity.getDataSign());
        dto.setExtension(entity.getExtension());
        dto.setHash(entity.getHash());
        dto.setRegioncode(entity.getRegioncode());
        dto.setTaskId(entity.getTaskId());
        dto.setKey(entity.getDecrypt());
        dto.setTimestamp(entity.getTimestamp());
        dto.setSize(entity.getSize());
        dto.setUrl(entity.getUrl());
        return dto;
    }
    public void delTaskInfo(String taskId) {
        taskInfoMapper.delete(new LambdaUpdateWrapper<TaskInfo>().eq(TaskInfo::getTaskId, taskId));
    }
//    private String buildRequestBody(AddDeviceDto dto) {
//        try {
//            return objectMapper.writeValueAsString(dto);
//        } catch (JsonProcessingException e) {
//            throw new RuntimeException("数据有误", e);
//        }
//    }
    public String getWorkspaceId(String devicesn) {
        DeviceEntity entity = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>()
                .eq(DeviceEntity::getDeviceSn, devicesn));
        return entity.getWorkspaceId();
    }
    public String getBizidnameByTask(String taskId) {
        List<LotInfo> lotInfos = patchesMapper.selectList(new LambdaQueryWrapper<LotInfo>().eq(LotInfo::getTaskId, taskId));
        String taskName = lotInfos.get(0).getTaskName();
        return taskName;
    }
    public static String enSM2(String data, String pubKey) throws InvalidCipherTextException, IOException {
        String encrypt = Utils.encrypt(data, pubKey);
@@ -159,11 +509,6 @@
        return Utils.decrypt(hex, priKey);
    }
    public static void main(String[] args) throws Exception {
        System.out.println(enSM2("jsimjrby3wqb7dbq", "044D6061FC08A19D3F32CEAA8CF6679B40500008FD741FC26DE7E50AEBF3A9115D47274437730EADEDAEF0CCC4853C5F0B35B30C6AEA83A5F6FBCA4ABEAC9E3B98"));
        System.out.println(deSM2("BK010WH/Ax++jp57tWA4eHwbB26eqiG7bwmDfzaEGAtA6XN6/lQDt34mL0x4l4fEIOmQSzVfMqt4SV901gjzwf19mAeuPfM8AuCqCZsWZ9QU1bEx5ZqMIUDlFn9ngEbSbZ8qb1ERDvYtaMN5YE+9uI8=", "23E57DA1E4AB865CCBC325B668762207DEF74345B782237808AE0BABDF26734D"));
        System.out.println(createKey());
    }
    public static Map<String, String> createKey() throws NoSuchAlgorithmException {
        Map<String, String> keyPair = Utils.createKeyPair();
@@ -182,7 +527,7 @@
                    .latitude(entity.getLatitude())
                    .radius(entity.getRadius())
                    .regioncode(entity.getRegioncode())
                    .deviceid(entity.getDeviceId())
                    .deviceid(entity.getDeviceSn())
                    .model(entity.getModel())
                    .build();
        }
@@ -206,20 +551,235 @@
        return (OsdSubDeviceReceiver) RedisOpsUtils.get(key);
    }
    public void delWaylineJob(String taskId) {
        waylineJobMapper.delete(new LambdaQueryWrapper<WaylineJobEntity>().like(WaylineJobEntity::getJobId, taskId));
    }
    public DroneStateDto getAirportFromCache(String deviceId) {
        OsdSubDeviceReceiver receiver = getDroneFromCache(deviceId);
        Optional<OsdSubDeviceReceiver> deviceOsdOpt = redisService.getDeviceOsd(deviceId, OsdSubDeviceReceiver.class);
        boolean result = deviceOsdOpt.isPresent();
        if (!result) {
            String sn = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>().eq(DeviceEntity::getChildSn, deviceId)).getDeviceSn();
            Optional<OsdDockReceiver> dockOsdOpt = redisService.getDeviceOsd(sn, OsdDockReceiver.class);
            boolean results = dockOsdOpt.isPresent();
            if (!results) {
                DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
                builder.gimbalYaw(0.0)
                        .gimbalPitch(0.0)
                        .batteryCapacityPercent(0)
                        .height(0)
                        .latitude(0)
                        .longitude(0)
                        .modeCode(1)
                        .elevation(0.0)
                        .gpsState(0)
                        .build();
                return builder.build();
            }
            OsdDockReceiver osdDockReceiver = objectMapper.convertValue(dockOsdOpt.get(), OsdDockReceiver.class);
            int mode;
            int sne = osdDockReceiver.getModeCode().getVal();
            if (sne == 0) {
                mode = 0;
            } else {
                mode = 2;
            }
            DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
            builder.gimbalYaw(0.0)
                    .gimbalPitch(0.0)
                    .batteryCapacityPercent(osdDockReceiver.getDroneChargeState().getCapacityPercent())
                    .height(osdDockReceiver.getHeight())
                    .latitude(osdDockReceiver.getLatitude())
                    .longitude(osdDockReceiver.getLongitude())
                    .modeCode(mode)
                    .elevation(0.0)
                    .gpsState(2)
                    .build();
            return builder.build();
        }
        OsdSubDeviceReceiver receiver = objectMapper.convertValue(deviceOsdOpt.get(), OsdSubDeviceReceiver.class);
        DroneStateDto.DroneStateDtoBuilder builder = DroneStateDto.builder();
        builder.gimbalYal(receiver.getAttitudeHead())
                .gimbalPitch(receiver.getAttitudePitch())
        builder.gimbalYaw(receiver.getPayloads().get(0).getGimbalYaw())
                .gimbalPitch(receiver.getPayloads().get(0).getGimbalPitch())
                .batteryCapacityPercent(receiver.getBattery().getCapacityPercent())
                .height(receiver.getHeight())
                .latitude(receiver.getLatitude())
                .longitude(receiver.getLongitude())
                .modeCode(0)
                .modeCode(2)
                .elevation(receiver.getElevation())
                .gpsState(2)
                .build();
        return builder.build();
    }
}
    public static AddTaskDto jsonToDto(JSONObject jsonObject) {
        AddTaskDto dto = new AddTaskDto();
        String deviceid = jsonObject.getStr("deviceid");
        dto.setDeviceid(deviceid);
        dto.setBizidname(jsonObject.getStr("bizidname"));
        JSONArray taskListArray = jsonObject.getJSONArray("tasklist");
        if (taskListArray != null) {
            List<TaskListDto> taskList = new ArrayList<>();
            for (int i = 0; i < taskListArray.size(); i++) {
                JSONObject taskObject = taskListArray.getJSONObject(i);
                if (taskObject != null) {
                    TaskListDto task = new TaskListDto();
                    task.bsm = taskObject.getStr("bsm");
                    task.xzqdm = taskObject.getStr("xzqdm");
                    task.dkbh = taskObject.getStr("dkbh");
                    task.dklx = taskObject.getStr("dklx");
                    task.zdkbh = taskObject.getStr("zdkbh");
                    task.dkmc = taskObject.getStr("dkmc");
                    task.dkmj = taskObject.getDouble("dkmj");
                    task.dkfw = taskObject.getStr("dkfw");
                    task.bz = taskObject.getStr("bz");
                    taskList.add(task);
                }
            }
            dto.tasklist = taskList;
        }
        return dto;
    }
    public static UpdataTaskDto UpjsonToDto(JSONObject jsonObject) {
        UpdataTaskDto dto = new UpdataTaskDto();
        String deviceid = jsonObject.getStr("deviceid");
        String taskid = jsonObject.getStr("taskid");
        dto.setDeviceid(deviceid);
        dto.setTaskid(taskid);
        JSONArray taskListArray = jsonObject.getJSONArray("tasklist");
        if (taskListArray != null) {
            List<TaskListDto> taskList = new ArrayList<>();
            for (int i = 0; i < taskListArray.size(); i++) {
                JSONObject taskObject = taskListArray.getJSONObject(i);
                if (taskObject != null) {
                    TaskListDto task = new TaskListDto();
                    task.bsm = taskObject.getStr("bsm");
                    task.xzqdm = taskObject.getStr("xzqdm");
                    task.dkbh = taskObject.getStr("dkbh");
                    task.dklx = taskObject.getStr("dklx");
                    task.zdkbh = taskObject.getStr("zdkbh");
                    task.dkmc = taskObject.getStr("dkmc");
                    task.dkmj = taskObject.getDouble("dkmj");
                    task.dkfw = taskObject.getStr("dkfw");
                    task.bz = taskObject.getStr("bz");
                    taskList.add(task);
                }
            }
            dto.tasklist = taskList;
        }
        return dto;
    }
    public static LotInfo convertToLotInfo(TaskListDto taskListDto) {
        if (taskListDto == null) {
            return null;
        }
        return LotInfo.builder()
                .bsm(taskListDto.bsm)
                .dklx(taskListDto.dklx)
                .xzqdm(taskListDto.xzqdm)
                .dkbh(taskListDto.dkbh)
                .dkmc(taskListDto.dkmc)
                .dkmj(taskListDto.dkmj)
                .dkfw(taskListDto.dkfw)
                .bz(taskListDto.bz)
                .build();
    }
    public List<Airport> getAirportsBySn(List<String> snList) {
        List<Airport> airports = new ArrayList<>();
        // 查询所有设备
        List<DeviceExpanSionEntity> entities = expanSionMapper.selectList(
                new LambdaQueryWrapper<DeviceExpanSionEntity>().in(DeviceExpanSionEntity::getDeviceSn, snList)
        );
        // 使用一个Map来存储SN和经纬度的对应关系
        Map<String, DeviceExpanSionEntity> entityMap = new HashMap<>();
        for (DeviceExpanSionEntity entity : entities) {
            entityMap.put(entity.getDeviceSn(), entity);
        }
        // 遍历SN列表,创建Airport对象
        for (String sn : snList) {
            DeviceExpanSionEntity entity = entityMap.get(sn);
            if (entity != null) {
                DeviceEntity deviceEntity = deviceMapper.selectOne(new LambdaQueryWrapper<DeviceEntity>().eq(DeviceEntity::getChildSn, sn));
                Airport airport = new Airport(entity.getWorkspaceId(), deviceEntity.getDeviceSn(), entity.getLatitude(), entity.getLongitude());
                airports.add(airport);
            }
        }
        return airports;
    }
    public static List<String> convertStringToList(String input) {
        // 使用 Hutool 解析字符串
        JSONArray jsonArray = JSONUtil.parseArray(input);
        // 将 JSONArray 转换为 List<String>
        return jsonArray.stream()
                .map(Object::toString)
                .collect(Collectors.toList());
    }
    public void updateTaskInfo(String traceid, String taskId, String deviceIds, String username) {
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setId(traceid);
        taskInfo.setTaskId(taskId);
        taskInfo.setDeviceIds(deviceIds);
        taskInfo.setCreateUser(username);
        LambdaUpdateWrapper<TaskInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TaskInfo::getId, traceid);
        updateWrapper.eq(TaskInfo::getTaskId, taskId);
        // 执行更新操作
        taskInfoMapper.update(taskInfo, updateWrapper);
    }
    public void updateJob(String jobid, String waylineId) {
        LambdaUpdateWrapper<WaylineJobEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WaylineJobEntity::getJobId, jobid)
                .set(WaylineJobEntity::getFileId, waylineId);
        // 调用 update 方法进行更新操作
        waylineJobMapper.update(null, updateWrapper);
    }
    /**
     * 统计给定工作空间下,创建时间为当天的不同 taskId 的数量。
     *
     * @param workspaceId 工作空间 ID
     * @return 不同 taskId 的数量
     */
    public Integer getDistinctTaskIdCount(String workspaceId) {
        // 获取当前日期的开始和结束时间
        LocalDate today = LocalDate.now();
        LocalDateTime startTime = today.atStartOfDay();
        LocalDateTime endTime = today.plusDays(1).atStartOfDay();
        // 转换为毫秒时间戳
        long startTimestamp = startTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        long endTimestamp = endTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        // 使用 LambdaQueryWrapper 进行查询
        LambdaQueryWrapper<LotInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(LotInfo::getWorkspaceId, workspaceId)
                .ge(LotInfo::getCreateTime, startTimestamp)
                .lt(LotInfo::getCreateTime, endTimestamp);
        // 获取符合条件的所有 taskId
        Set<String> taskIdSet = patchesMapper.selectList(queryWrapper).stream()
                .map(LotInfo::getTaskId)
                .collect(Collectors.toSet());
        // 返回不同 taskId 的数量
        return taskIdSet.size();
    }
}