rain
2024-08-14 75e6eea8cd3fac9cc888e2ffc9cdb126fab8429d
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.territory.service.impl;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.dji.sample.media.dao.IMarkMapper;
import com.dji.sample.media.model.*;
import com.dji.sample.media.util.ImgUtil;
import com.dji.sample.patches.config.pojo.PatchesConfigPojo;
import com.dji.sample.patches.model.entity.LotInfo;
import com.dji.sample.territory.dao.ITbFjMapper;
import com.dji.sample.territory.model.entity.TbFjEntity;
import com.dji.sample.territory.pojo.TerritoryConfigPojo;
import com.dji.sample.territory.service.ITbFJService;
import com.dji.sample.territory.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
import static com.dji.sample.media.service.impl.FileServiceImpl.uploadFile;
import static com.dji.sample.territory.utils.SM3.sm3;
 
@Service
@DS("sqlite-ret")
public class TbFjServiceImpl implements ITbFJService {
    @Autowired
    private ITbFjMapper tbFjMapper;
    @Autowired
    private PatchesConfigPojo patchesConfigPojo;
    @Autowired
    private TerritoryConfigPojo territoryConfigPojo;
    @Autowired
    private MinioPojo pojo;
    @Autowired
    private IMarkMapper markMapper;
    /**
     * 按照地块编号所对应的信息和音视频文件存入sqlite数据库
     *
     * @param mediaFile
     * @param lotInfo
     * @return
     * @throws IOException
     */
    @Transactional
    public int insertData(List<MediaFileEntity> mediaFile, LotInfo lotInfo) throws Exception {
        int count = 0;
        List<TbFjEntity> list = new ArrayList<>();
        TbFjEntity tbFj;
        for (int i = 0; i < mediaFile.size(); i++) {
            MediaFileEntity file = mediaFile.get(i);
            tbFj = dbConvertToEntity(file, lotInfo);
            list.add(tbFj);
            tbFjMapper.insert(tbFj);
            count++;
        }
        return count;
    }
 
    public void insertOneData(MediaFileEntity mediaFile, LotInfo lotInfo) throws Exception {
        TbFjEntity tbFj = dbConvertToEntity(mediaFile, lotInfo);
        if (tbFj.getFjysgd() == 3000) {
            tbFjMapper.insert(tbFj);
        }
    }
 
    @Override
    public void deleteData() {
        tbFjMapper.delete(null);
    }
 
    /**
     * 将Media和Lotinfo实体类转化为TbFjEntity实体类
     *
     * @param mediaFile
     * @param lotInfo
     * @return
     * @throws IOException
     */
    private TbFjEntity dbConvertToEntity(MediaFileEntity mediaFile, LotInfo lotInfo) throws Exception {
        File file1 = null;
        byte[] FJ = null;
        String jsonString = JSONObject.toJSONString(mediaFile.getMetadata());
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        Double absoluteAltitude = jsonObject.getDouble("absoluteAltitude");
        Double relativeAltitude = jsonObject.getDouble("relativeAltitude");
        Double gimbalYawDegree = jsonObject.getDouble("gimbalYawDegree");
        Long sj = jsonObject.getLong("createdTime");
        JSONObject shootPosition = jsonObject.getJSONObject("shootPosition");
        Double lat = shootPosition.getDouble("lat");
        Double lng = shootPosition.getDouble("lng");
        PositionDTO position=new PositionDTO();
        position.setLat(lat);
        position.setLng(lng);
//        double[] coordinates = extractCoordinates(pointWGStoCGCS(lng, lat));
//        double x = Double.parseDouble(((formatCoordinate(coordinates[1]))));
//        double y = Double.parseDouble(((formatCoordinate(coordinates[0]))));
        //本地数据库没有的数据在FJ表非空用0
        double psjd = WaterMarkUtil.convertAngle(gimbalYawDegree);
        int pshgj = 0;
        String psry = "中图智绘无人机";
        String zsdm = "23C8CCC61E3042FBA6A658F319337B1A";
        String dklx = "0";
        int fjlx = 1;
        String pstz = "Y";
        String pssj = convertTimestampToDateTime(sj);
        String bsm = UUID.randomUUID().toString();
        String fjmc = mediaFile.getFileName();
        String key = mediaFile.getObjectKey();
        String head = "http://dev.jxpskj.com:9000/cloud-bucket";
        String url = head + key;
        File file = downloadFile(url);
        JSONObject jsons = (JSONObject) (ImgUtil.getInfo(file));
        String str = jsons.toJSONString();
        String newstr = str.replace("+", "");
        JSONObject json = JSON.parseObject(newstr);
        double pitch = json.getDouble("GimbalPitchDegree");
        String focal = json.getString("FocalLength");
        String numberPart = focal.replaceAll("[^\\d]", "");
        int psjj = Integer.parseInt(numberPart);
        json.getString("GimbalYawDegree");
        BufferedImage image = ImageIO.read(file);
        int width = image.getWidth();
        int height = image.getHeight();
        String fjhxz = null;
        //对应图片和视频文件进行不同处理
        boolean endsWith = key.endsWith(".mp4");
        if (!endsWith) {
            file1 = WaterMarkUtil.addWatermark(file, sj, lat, lng, gimbalYawDegree);
            byte[] bytesArray = Files.readAllBytes(file1.toPath());
            fjhxz= sm3(bytesArray);
            FJ = fileToByteArray(file1);
            saveMarkFile(lotInfo.getWorkspaceId(),mediaFile,file1);
        } else {
            file1 = VideoZipUtil.compressVideo(file, 800000, 128000, 1280, 720);
            FJ = fileToByteArray(file1);
        }
        StringBuffer buffer=SM3.addStringBuffer(fjhxz,pssj,truncateToSevenDecimalPlaces(lng),truncateToSevenDecimalPlaces(lat),(int)pitch,(int)psjd,pshgj,psry,zsdm);
        String jyms= SM3.addJym(buffer);
        TbFjEntity.TbFjEntityBuilder builder = TbFjEntity.builder();
        if (lotInfo != null) {
            builder.bsm(bsm)
                    .dkbsm(lotInfo.getBsm())
                    .xzqdm(lotInfo.getXzqdm())
                    .dklx(dklx)
                    .xdgd(truncateToTwoDecimalPlaces(relativeAltitude))
                    .jdgd(truncateToTwoDecimalPlaces(absoluteAltitude))
                    .Latitude(truncateToSevenDecimalPlaces(lat))
                    .longitude(truncateToSevenDecimalPlaces(lng))
                    .fj(FJ)
                    .psjj(psjj)
                    .fjmc(fjmc)
                    .fjlx(fjlx)
                    .psfyj(pitch)
                    .pssj(pssj)
                    .psjd((int) psjd)
                    .fjhxz(fjhxz)
                    .pshgj(pshgj)
                    .zsdm(zsdm)
                    .psry(psry)
                    .jym(jyms)
                    .url(url)
                    .pstz(pstz)
                    .fjyskd(width)
                    .fjysgd(height)
                    .build();
        }
//        else {
////            throw new IllegalArgumentException("未匹配到相关地块");
//        }
        file.delete();
        return builder.build();
    }
 
    /**
     * 将音视频文件转换成字节流
     *
     * @param fileUrl
     * @return
     */
    public static File downloadFile(String fileUrl) {
        File downloadedFile = null;
 
        try {
            URL url = new URL(fileUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
 
            // 创建临时文件
            File tempFile = File.createTempFile("temp", ".jpeg");
            downloadedFile = tempFile;
 
            // 使用 try-with-resources 确保流被关闭
            try (InputStream inputStream = connection.getInputStream();
                 OutputStream outputStream = new FileOutputStream(downloadedFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
 
        return downloadedFile;
    }
 
    /**
     * 将文件转换为字节数组。
     *
     * @param file 需要转换的文件对象。
     * @return 文件内容的字节数组。
     * @throws IOException 如果读取文件发生错误。
     */
    public static byte[] fileToByteArray(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        fis.read(data);
        fis.close();
        return data;
    }
    public void saveMarkFile(String workspaceId, MediaFileEntity file,File file1) {
        try {
            MediaFileMarkEntity mediaFileMarkEntity= new MediaFileMarkEntity();
            mediaFileMarkEntity.setWorkspaceId(workspaceId);
            mediaFileMarkEntity.setIsadd(0);
            mediaFileMarkEntity.setIsOriginal(false);
            mediaFileMarkEntity.setFileId(UUID.randomUUID().toString());
            mediaFileMarkEntity.setObjectKey("/mark" + file.getFilePath()+ "/" + file.getFileName());
            mediaFileMarkEntity.setFileName("mark" + file.getFileName());
            mediaFileMarkEntity.setFilePath("mark" + file.getFilePath());
            uploadFile(pojo.getEndpoint(), pojo.getAccessKey(), pojo.getSecretKey(), pojo.getBucket(), mediaFileMarkEntity.getObjectKey(), file1, "image/jpeg");
            markMapper.insert(mediaFileMarkEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static String convertTimestampToDateTime(long timestamp) {
        // 将时间戳转换为 Instant 对象
        Instant instant = Instant.ofEpochMilli(timestamp);
 
        // 将 Instant 对象转换为 LocalDateTime 对象
        LocalDateTime dateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
 
        // 格式化日期时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return dateTime.format(formatter);
    }
 
    public static Double truncateToTwoDecimalPlaces(Double value) {
        //小数点只保留两位
        if (value == null) {
            return null;  // 处理null值情况
        }
        BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.DOWN);
        return bd.doubleValue();
    }
 
    public static Double truncateToSevenDecimalPlaces(Double value) {
        //小数点只保留七位
        if (value == null) {
            return null;  // 处理null值情况
        }
        BigDecimal bd = new BigDecimal(value).setScale(7, RoundingMode.DOWN);
        return bd.doubleValue();
 
    }
}