rain
2024-05-09 74d0031c16c468fa82208dbcdde4fa3766a58eeb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package com.dji.sample.patches.utils;
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dji.sample.common.model.CustomClaim;
import com.dji.sample.media.dao.IFileMapper;
import com.dji.sample.media.model.MediaFileEntity;
import com.dji.sample.patches.config.pojo.PatchesConfigPojo;
import com.dji.sample.patches.dao.ShpToDataSourceMapper;
import com.dji.sample.patches.model.entity.LotInfo;
import com.dji.sample.patches.service.GetPatchesService;
import com.dji.sample.patches.xml.mode.XMLTemplateModel;
import com.dji.sample.patches.xml.utils.CreateWaylineFileUtils;
import com.dji.sample.territory.pojo.TerritoryConfigPojo;
import com.dji.sample.territory.service.ITbFJService;
import com.dji.sample.wayline.model.entity.WaylineFileEntity;
import com.dji.sample.wayline.model.param.CreateJobParam;
import com.dji.sample.wayline.service.IWaylineFileService;
import com.dji.sample.wayline.service.IWaylineJobService;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import java.time.LocalDateTime;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
import static com.dji.sample.patches.utils.MultipartFileTOFileUtil.convert;
import static com.dji.sample.patches.utils.ZipUtil.zipFolder;
import static com.dji.sample.wayline.model.enums.WaylineTaskTypeEnum.TIMED;
import static com.dji.sample.wayline.model.enums.WaylineTemplateTypeEnum.WAYPOINT;
 
@Component
public class TimerUtil {
    @Autowired
    private ShpToDataSourceMapper shpToDataSourceMapper;
    @Autowired
    private PatchesConfigPojo patchesConfigPojo;
    @Autowired
    public IWaylineFileService waylineFileService;
    @Autowired
    private IFileMapper fileMapper;
    @Autowired
    private ITbFJService tbFJService;
    @Autowired
    private GetPatchesService getPatchesService;
    @Autowired
    private IWaylineJobService waylineJobService;
    @Autowired
    private TerritoryConfigPojo territoryConfigPojo;
 
    /**
     * 定时
     *
     * @throws IOException
     * @throws SQLException
     */
    @Scheduled(cron = "45 1 16 * * ?")
    public void myTask() throws Exception {
        String workspaceId = "4a574db8-4ad3-48f7-9f16-3edbcd8056e1";
        //获取未规划的图斑集合
//        List<List<LotInfo>> lists = getNoPlan();
//        List<List<LotInfo>> convertedLists = convertToLists(lists);
//        for (List<LotInfo> list : convertedLists) {
//            long timestamp = System.currentTimeMillis();
//            String waylineName = "云飞行调查" + timestamp;
//            //根据获取的图斑集合获得kmz航线文件
//            MultipartFile multipartFile = getFile(waylineName, list);
//            //上传航线文件
//            String waylineId = backWayline(multipartFile, waylineName, workspaceId, backclaim().getUsername());
//            //将为规划的图斑状态更新为已规划
//            updatePatchesStatu(list);
//            //调用publshFlightTask方法创建定时任务
//            waylineJobService.publishFlightTask(JobParam(waylineId), backclaim());
//        }
        List<List<MediaFileEntity>> list = getNoadd();
        List<List<MediaFileEntity>> media = convertToLists(list);
        for (int i = 0; i < media.size(); i++) {
            tbFJService.deleteData();
            String dkbh = getDkbh(media.get(i).get(i).getFileName());
            String taskId = getTaskId(media.get(i).get(i).getFileName());
            LotInfo lotInfo = getPatchesService.getLotinfo(dkbh, workspaceId);
            tbFJService.insertData(media.get(i), lotInfo);
            updateMediaStatu(media.get(i));
            sendPostWithFileAndParameter(territoryConfigPojo.getResult(), taskId);
        }
    }
 
    public MultipartFile getFile(String waylineName, List<LotInfo> list) throws IOException {
        List<PointPO> coordinates = GeoToolsUtil.getRoutePointOrder(list, 28.62703, 115.867719);
        XMLTemplateModel xmlModel = XMLTemplateModel.init(coordinates, list);
        CreateWaylineFileUtils.createWaylineFile(xmlModel, patchesConfigPojo.getTemplate(), patchesConfigPojo.getTargetTemplate(), patchesConfigPojo.getWaylines(), patchesConfigPojo.getTargetWaylines());
        // 压缩文件夹中的内容
        String destKMZFile = patchesConfigPojo.getDestKMZFile() + waylineName + ".kmz"; // 输出的KMZ文件路径
        zipFolder(patchesConfigPojo.getSourceDir(), destKMZFile);
        return convert(new File(destKMZFile));
    }
 
    public String backWayline(MultipartFile multipartFile, String waylineName, String workspaceId, String username) {
        waylineFileService.importKmzFile(multipartFile, workspaceId, username);
        WaylineFileEntity entity = waylineFileService.selectByName(waylineName);
        try {
            waylineFileService.getObjectUrl(workspaceId, entity.getWaylineId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return entity.getWaylineId();
    }
 
    /**
     * 获取未规划的图斑集合
     *
     * @return
     */
    public List<List<LotInfo>> getNoPlan() {
        List<LotInfo> list = shpToDataSourceMapper.selectList(new LambdaQueryWrapper<LotInfo>().eq(LotInfo::getIsPlan, 0));
        List<List<LotInfo>> combinedTasks = list.stream()
                .collect(Collectors.groupingBy(LotInfo::getTaskId))
                .values().stream()
                .map(ArrayList::new)
                .collect(Collectors.toList());
        return combinedTasks;
    }
 
    /**
     * 更新图斑执行状态
     *
     * @param list
     */
    public void updatePatchesStatu(List<LotInfo> list) {
        for (LotInfo lotInfo : list) {
            lotInfo.setIsPlan(1);
            shpToDataSourceMapper.updateById(lotInfo);
        }
    }
 
    public void updateMediaStatu(List<MediaFileEntity> list) {
        for (MediaFileEntity mediaFile : list) {
            mediaFile.setIsadd(1);
            fileMapper.updateById(mediaFile);
        }
    }
 
    public List<List<MediaFileEntity>> getNoadd() {
        List<MediaFileEntity> list = fileMapper.selectList(new LambdaQueryWrapper<MediaFileEntity>()
                .eq(MediaFileEntity::getIsadd, 0).like(MediaFileEntity::getFileName, "~"));
        List<List<MediaFileEntity>> groupedFilenames = groupTasks(list);
        return groupedFilenames;
    }
 
    public CreateJobParam JobParam(String waylineId) {
        List<List<Long>> listOfLists = new ArrayList<>();
        List<Long> sublist = new ArrayList<>();
        sublist.add(177271980L); // 添加整数值
        listOfLists.add(sublist);
        List<Long> list = new ArrayList<>();
        list.add(177271980L);
        CreateJobParam param = new CreateJobParam();
        param.setName("云飞行调查");
        param.setTaskType(TIMED);
        param.setOutOfControlAction(0);
        param.setRepFreType(3);
        param.setRepFreVal(1);
        param.setRepRuleType(1);
        param.setRthAltitude(80);
        param.setWaylineType(WAYPOINT);
        param.setTaskPeriods(listOfLists);
        param.setTaskDays(list);
        param.setFileId(waylineId);
        param.setDockSn("4TADKCMB010016");
        return param;
    }
 
    public CustomClaim backclaim() {
        CustomClaim claim = new CustomClaim();
        claim.setId("1");
        claim.setUsername("adminPC");
        claim.setWorkspaceId("4a574db8-4ad3-48f7-9f16-3edbcd8056e1");
        claim.setUserType(1);
        return claim;
    }
 
    public static <T> List<List<T>> convertToLists(List<List<T>> listOfLists) {
        List<List<T>> convertedLists = new ArrayList<>();
        for (List<T> list : listOfLists) {
            convertedLists.add(new ArrayList<>(list));
        }
        return convertedLists;
    }
 
 
    // 对任务ID进行分组
    public static List<List<MediaFileEntity>> groupTasks(List<MediaFileEntity> mediaFiles) {
        Map<String, List<MediaFileEntity>> groupedTasks = new HashMap<>();
        for (MediaFileEntity mediaFile : mediaFiles) {
            String taskId = getTaskId(mediaFile.getFileName());
            if (!groupedTasks.containsKey(taskId)) {
                groupedTasks.put(taskId, new ArrayList<>());
            }
            groupedTasks.get(taskId).add(mediaFile);
        }
        return new ArrayList<>(groupedTasks.values());
    }
 
    // 从filename字段中提取任务ID(假设任务ID在文件名中以"~"开头、"."结尾)
    public static String getTaskId(String filename) {
        // 这里只是一个示例,你需要根据实际情况编写提取task_id的逻辑
        int startIndex = filename.indexOf("~") + 1;
        int endIndex = filename.indexOf(".");
        return filename.substring(startIndex, endIndex);
    }
 
    public static String getDkbh(String filename) {
        // 这里只是一个示例,你需要根据实际情况编写提取task_id的逻辑
        int startIndex = filename.indexOf("点") + 1;
        int endIndex = filename.indexOf("~");
        return filename.substring(startIndex, endIndex);
    }
 
    public static void sendPostWithFileAndParameter(String filePath, String taskId) throws IOException {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();
 
        // 读取文件内容为字节数组
        byte[] fileContent = readFileToBytes(filePath);
 
        // 构建请求体
        MultiValueMap<String, Object> body = buildRequestBody(taskId, fileContent, filePath);
 
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
 
 
        // 构建请求实体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
 
        // 发送请求
        ResponseEntity<String> response = restTemplate.exchange(
                "http://localhost:6789/territory/tbdkjbxx/upload",
                HttpMethod.POST,
                requestEntity,
                String.class);
 
        // 输出响应结果
        System.out.println("Response: " + response.getBody());
    }
 
    private static MultiValueMap<String, Object> buildRequestBody(String taskId, byte[] fileContent, String filePath) {
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("taskId", taskId);
        body.add("file", new ByteArrayResource(fileContent) {
            @Override
            public String getFilename() {
                return Paths.get(filePath).getFileName().toString();
            }
        });
        return body;
    }
 
    private static byte[] readFileToBytes(String filePath) throws IOException {
        Path path = Paths.get(filePath);
        return Files.readAllBytes(path);
    }
 
}