jiangping
2025-06-06 c845254d8e0d83bb9458d0236a1da201bfbeae42
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package com.doumee.service.business.impl;
 
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.core.constants.ResponseStatus;
import com.doumee.core.exception.BusinessException;
import com.doumee.core.model.LoginUserInfo;
import com.doumee.core.model.PageData;
import com.doumee.core.model.PageWrap;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.DateUtil;
import com.doumee.core.utils.Utils;
import com.doumee.dao.business.YwPatrolPointMapper;
import com.doumee.dao.business.model.Category;
import com.doumee.dao.business.model.YwDevice;
import com.doumee.dao.business.model.YwPatrolPoint;
import com.doumee.dao.system.MultifileMapper;
import com.doumee.dao.system.model.Multifile;
import com.doumee.dao.system.model.SystemUser;
import com.doumee.service.business.YwPatrolPointService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.google.zxing.qrcode.encoder.ByteMatrix;
import com.google.zxing.qrcode.encoder.Encoder;
import com.google.zxing.qrcode.encoder.QRCode;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
 
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.*;
 
/**
 * 运维巡检点信息表Service实现
 * @author 江蹄蹄
 * @date 2024/11/19 16:07
 */
@Service
public class YwPatrolPointServiceImpl implements YwPatrolPointService {
 
    @Autowired
    private YwPatrolPointMapper ywPatrolPointMapper;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
    @Autowired
    private MultifileMapper multifileMapper;
 
    @Override
    public Integer create(YwPatrolPoint ywPatrolPoint) {
        if(Objects.isNull(ywPatrolPoint)
//                || Objects.isNull(ywPatrolPoint.getCode())
                || Objects.isNull(ywPatrolPoint.getName())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
 
        String pre =  systemDictDataBiz.queryByCode(Constants.XUNJIAN,Constants.XJ_POINT_PREFIX).getCode();
        int length = 8;
        try {
            length =  Integer.parseInt(systemDictDataBiz.queryByCode(Constants.XUNJIAN,Constants.XJ_POINT_CODE_LENGTH).getCode());
        }catch (Exception e){
        }
        long num = ywPatrolPointMapper.selectCount(new QueryWrapper<YwPatrolPoint>());
 
        ywPatrolPoint.setCode(pre+Constants.formartNumString (length,(num+1)));
        LoginUserInfo loginUserInfo = ywPatrolPoint.getLoginUserInfo();
        ywPatrolPoint.setCreateDate(new Date());
        ywPatrolPoint.setCreator(loginUserInfo.getId());
        ywPatrolPoint.setIsdeleted(Constants.ZERO);
        ywPatrolPoint.setStatus(Constants.ZERO);
        ywPatrolPointMapper.insert(ywPatrolPoint);
 
 
        if(Objects.nonNull(ywPatrolPoint.getFileUrl())){
            Multifile multifile = new Multifile();
            multifile.setCreator(loginUserInfo.getId());
            multifile.setCreateDate(new Date());
            multifile.setIsdeleted(Constants.ZERO);
            multifile.setObjType(Constants.MultiFile.FN_PATROL_POINT_FILE.getKey());
            multifile.setObjId(ywPatrolPoint.getId());
            multifile.setFileurl(ywPatrolPoint.getFileUrl());
            multifileMapper.insert(multifile);
        }
 
        return ywPatrolPoint.getId();
    }
 
    @Override
    public void deleteById(Integer id, LoginUserInfo user) {
        ywPatrolPointMapper.update(new UpdateWrapper<YwPatrolPoint>().lambda()
                .set(YwPatrolPoint::getIsdeleted,Constants.ONE)
                .set(YwPatrolPoint::getEditDate, DateUtil.getCurrDateTime())
                .set(YwPatrolPoint::getEditor,user.getId())
                .eq(YwPatrolPoint::getId,id)
        );
    }
 
    @Override
    public void delete(YwPatrolPoint ywPatrolPoint) {
        UpdateWrapper<YwPatrolPoint> deleteWrapper = new UpdateWrapper<>(ywPatrolPoint);
        ywPatrolPointMapper.delete(deleteWrapper);
    }
    @Override
    public void exportQrcodes(Integer id, HttpServletResponse response){
        try {
            List<File>  fileList = new ArrayList<>();
            List<YwPatrolPoint> bikesList = ywPatrolPointMapper.selectList(new QueryWrapper<YwPatrolPoint>().lambda()
                    .eq(YwPatrolPoint::getIsdeleted,Constants.ZERO)
                    .eq(id!=null,YwPatrolPoint::getId,id)
            );
            if(bikesList== null || bikesList.size() == 0){
                throw  new BusinessException(ResponseStatus.DATA_EMPTY);
            }
            // 创建临时文件的前缀和后缀
            String path =  systemDictDataBiz.queryByCode(Constants.WX_PLATFORM,Constants.WX_AUTH_URL).getCode();
            String uri =  systemDictDataBiz.queryByCode(Constants.XUNJIAN,Constants.XJ_RERIRECT_URI).getCode();
            String appId = systemDictDataBiz.queryByCode(Constants.WX_PLATFORM,Constants.WX_PLATFORM_APPID).getCode() ;
            // 创建临时文件
            for(YwPatrolPoint l : bikesList){
                if(StringUtils.isNotBlank(l.getCode())){
                    String redirectUri = uri.replace("${ywid}",l.getCode());
                    String url = path.replace("${url}",URLEncoder.encode(redirectUri)).replace("${appid}",appId);
                    File file =  generateQRCodeImage(url,100,100,l.getCode()+".png");
                    if(file!=null && file.isFile()){
                        fileList.add(file);
                    }
                }
            }
            if(fileList == null || fileList.size() == 0){
                throw  new BusinessException(ResponseStatus.DATA_EMPTY.getCode(),"对不起,下载内容为空,操作失败!");
            }
            String fileName =  "巡检点二维码导出_"+System.currentTimeMillis()+".zip" ;
            String encodeFileName =URLEncoder.encode(fileName, Charset.forName("UTF-8").toString())+".zip";
            response.setHeader("Content-Disposition","attachment;filename=" + encodeFileName);
            response.setContentType("application/octet-stream");
            response.setHeader("eva-opera-type", "download");
            response.setHeader("eva-download-filename", encodeFileName);
            packFilesToZip(fileList,response.getOutputStream());
        } catch (IOException e) {
            throw new BusinessException(ResponseStatus.EXPORT_EXCEL_ERROR, e);
        }
    }
    public static File generateQRCodeImage(String text, int width, int height, String fileName)  {
        try {
            // 创建二维码数据矩阵
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码为UTF-8
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 设置纠错等级为H
            hints.put(EncodeHintType.MARGIN, 0); // 设置白边为0
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE , width, height, hints);
            // 保存二维码图片到文件系统
            File f = new File("temp/");
            if(!f.exists()){
                f.mkdirs();
            }
//            bitMatrix =  renderResult(bitMatrix,width,height);
            Path path = FileSystems.getDefault().getPath("temp/"+fileName);
            MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); // 保存为PNG格式的图片
            return path.toFile();
        }catch (Exception e){
            e.printStackTrace();
        }
 
        return  null;
    }
 
    public static void main(String[] args) {
        File f =generateQRCodeImage("dj少时诵诗书少时诵诗书是撒是撒是撒",100,100,UUID.randomUUID().toString()+".png");
        System.out.println(f.getAbsolutePath());
    }
 
    private static BitMatrix renderResult(BitMatrix input, int width, int height) {
        if (input == null) {
           return null;
        }
        int inputWidth = input.getWidth();
        int inputHeight = input.getHeight();
        // 依据用户的输入宽高,计算最后的输出宽高
        int outputWidth = Math.max(width, inputWidth);
        int outputHeight = Math.max(height, inputHeight);
 
        //计算缩放比例
        int multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight);
 
        BitMatrix output = new BitMatrix(outputWidth, outputHeight);
        int inputY = 0;
        // 嵌套循环,将ByteMatrix的内容计算padding后转换成BitMatrix
        for (int outputY = 0; inputY < inputHeight; outputY += multiple) {
            int inputX = 0;
            for (int outputX = 0; inputX < inputWidth; outputX += multiple) {
                if (input.get(inputX, inputY)) {
                    output.setRegion(outputX, outputY, multiple, multiple);
                }
                inputX++;
            }
            inputY++;
        }
 
        return output;
    }
    public static void packFilesToZip(List<File> files,    ServletOutputStream os) throws IOException {
        try (ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(os)) {
            for (File file : files) {
                ZipArchiveEntry entry = new ZipArchiveEntry(file.getName());
                zipOutputStream.putArchiveEntry(entry);
                try (FileInputStream fileInputStream = new FileInputStream(file)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fileInputStream.read(buffer)) > 0) {
                        zipOutputStream.write(buffer, 0, length);
                    }
                }
                zipOutputStream.closeArchiveEntry();
            }
        }
    }
    @Override
    public void deleteByIdInBatch(List<Integer> ids, LoginUserInfo user) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        ywPatrolPointMapper.deleteBatchIds(ids);
    }
 
    @Override
    public void updateById(YwPatrolPoint ywPatrolPoint) {
        if(Objects.isNull(ywPatrolPoint)
                || Objects.isNull(ywPatrolPoint.getId())
                || Objects.isNull(ywPatrolPoint.getCode())
                || Objects.isNull(ywPatrolPoint.getName())
        ){
            throw new BusinessException(ResponseStatus.BAD_REQUEST);
        }
        if(ywPatrolPointMapper.selectCount(new QueryWrapper<YwPatrolPoint>().lambda().eq(YwPatrolPoint::getIsdeleted,Constants.ZERO)
                .eq(YwPatrolPoint::getCode,ywPatrolPoint.getCode()).ne(YwPatrolPoint::getId,ywPatrolPoint.getId()))>Constants.ZERO){
            throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"巡检点编码重复!");
        }
        LoginUserInfo loginUserInfo = ywPatrolPoint.getLoginUserInfo();
        ywPatrolPoint.setEditDate(new Date());
        ywPatrolPoint.setEditor(loginUserInfo.getId());
        ywPatrolPointMapper.updateById(ywPatrolPoint);
 
        multifileMapper.delete(new QueryWrapper<Multifile>().lambda()
                .eq(Multifile::getObjId,ywPatrolPoint.getId())
                .eq(Multifile::getObjType,Constants.MultiFile.FN_PATROL_POINT_FILE.getKey())
        );
 
        if(Objects.nonNull(ywPatrolPoint.getFileUrl())){
            Multifile multifile = new Multifile();
            multifile.setCreator(loginUserInfo.getId());
            multifile.setCreateDate(new Date());
            multifile.setIsdeleted(Constants.ZERO);
            multifile.setObjType(Constants.MultiFile.FN_PATROL_POINT_FILE.getKey());
            multifile.setObjId(ywPatrolPoint.getId());
            multifile.setFileurl(ywPatrolPoint.getFileUrl());
            multifileMapper.insert(multifile);
        }
 
    }
 
    @Override
    public void updateByIdInBatch(List<YwPatrolPoint> ywPatrolPoints) {
        if (CollectionUtils.isEmpty(ywPatrolPoints)) {
            return;
        }
        for (YwPatrolPoint ywPatrolPoint: ywPatrolPoints) {
            this.updateById(ywPatrolPoint);
        }
    }
 
    @Override
    public YwPatrolPoint findById(Integer id) {
        return ywPatrolPointMapper.selectById(id);
    }
 
    @Override
    public YwPatrolPoint getDetail(Integer id) {
        YwPatrolPoint ywPatrolPoint = ywPatrolPointMapper.selectById(id);
        if(Objects.isNull(ywPatrolPoint)){
            throw new BusinessException(ResponseStatus.DATA_EMPTY);
        }
        Multifile multifile = multifileMapper.selectOne(new QueryWrapper<Multifile>().lambda().eq(Multifile::getObjId,id)
                .eq(Multifile::getObjType,Constants.MultiFile.FN_PATROL_POINT_FILE.getKey()).orderByDesc(Multifile::getId).last(" limit 1"));
        if(Objects.nonNull(multifile) && StringUtils.isNotBlank(multifile.getFileurl())){
            String path = systemDictDataBiz.queryByCode(Constants.FTP,Constants.FTP_RESOURCE_PATH).getCode()
                    +systemDictDataBiz.queryByCode(Constants.FTP,Constants.YW_PATROL).getCode();
            ywPatrolPoint.setFileFullUrl(path + multifile.getFileurl());
            ywPatrolPoint.setFileUrl(multifile.getFileurl());
        }
 
        return ywPatrolPoint;
    }
 
 
 
    @Override
    public YwPatrolPoint findOne(YwPatrolPoint ywPatrolPoint) {
        QueryWrapper<YwPatrolPoint> wrapper = new QueryWrapper<>(ywPatrolPoint);
        return ywPatrolPointMapper.selectOne(wrapper);
    }
 
    @Override
    public List<YwPatrolPoint> findList(YwPatrolPoint ywPatrolPoint) {
        QueryWrapper<YwPatrolPoint> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(YwPatrolPoint::getIsdeleted,Constants.ZERO);
        if(com.github.xiaoymin.knife4j.core.util.CollectionUtils.isNotEmpty(ywPatrolPoint.getIdLists())){
            wrapper.lambda().notIn(YwPatrolPoint::getId,ywPatrolPoint.getIdLists());
        }
        return ywPatrolPointMapper.selectList(wrapper);
    }
  
    @Override
    public PageData<YwPatrolPoint> findPage(PageWrap<YwPatrolPoint> pageWrap) {
        IPage<YwPatrolPoint> page = new Page<>(pageWrap.getPage(), pageWrap.getCapacity());
        MPJLambdaWrapper<YwPatrolPoint> queryWrapper = new MPJLambdaWrapper<YwPatrolPoint>();
        Utils.MP.blankToNull(pageWrap.getModel());
        YwPatrolPoint model = pageWrap.getModel();
        queryWrapper.selectAll(YwPatrolPoint.class)
                .selectAs(Category::getName,YwPatrolPoint::getAreaName)
                .selectAs(YwDevice::getName,YwPatrolPoint::getDeviceName)
                .leftJoin(Category.class,Category::getId,YwPatrolPoint::getAreaId)
                .leftJoin(YwDevice.class,YwDevice::getId,YwPatrolPoint::getDeviceId)
                .and(Objects.nonNull(model)&&StringUtils.isNotBlank(model.getName()),
                        i->i.like(YwPatrolPoint::getName,model.getName()).or().like(YwPatrolPoint::getCode,model.getName()))
                .eq(Objects.nonNull(model.getAreaId()),YwPatrolPoint::getAreaId,model.getAreaId())
                .eq(YwPatrolPoint::getIsdeleted,Constants.ZERO)
                .orderByDesc(YwPatrolPoint::getCreateDate)
        ;
        IPage iPage = ywPatrolPointMapper.selectJoinPage(page,YwPatrolPoint.class,queryWrapper);
        return PageData.from(iPage);
    }
 
    @Override
    public long count(YwPatrolPoint ywPatrolPoint) {
        QueryWrapper<YwPatrolPoint> wrapper = new QueryWrapper<>(ywPatrolPoint);
        return ywPatrolPointMapper.selectCount(wrapper);
    }
}