李林
2023-10-07 658d4927d468c47208fd012d9128b09249c07eff
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
package com.chinaztt.mes.quality.service.impl;
 
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaztt.mes.basic.util.DictUtils;
import com.chinaztt.mes.common.wrapper.QueryWrapperUtil;
import com.chinaztt.mes.quality.dto.Quality19GrossPrintDTO;
import com.chinaztt.mes.quality.entity.*;
import com.chinaztt.mes.quality.excel.QualityHw19CodeBingData;
import com.chinaztt.mes.quality.excel.QualityHw19CodeBingImportData;
import com.chinaztt.mes.quality.excel.QualityHw19GrossData;
import com.chinaztt.mes.quality.excel.QualityHw19GrossImportData;
import com.chinaztt.mes.quality.mapper.HwWeightLabelConfigMapper;
import com.chinaztt.mes.quality.mapper.QualityHw19CodeBingMapper;
import com.chinaztt.mes.quality.mapper.QualityHw19CodeMapper;
import com.chinaztt.mes.quality.mapper.QualityHw19GrossMapper;
import com.chinaztt.mes.quality.service.QualityHw19GrossService;
import com.chinaztt.mes.quality.utils.HwWeightLabelConfigUtils;
import com.chinaztt.ztt.admin.api.feign.RemoteParamService;
import com.chinaztt.ztt.common.core.constant.SecurityConstants;
import com.chinaztt.ztt.common.core.util.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
 
 
/**
 * 19条码毛重
 *
 * @author pigx code generator
 * @date 2022-12-02 14:16:26
 */
@Service
public class QualityHw19GrossServiceImpl extends ServiceImpl<QualityHw19GrossMapper, QualityHw19Gross> implements QualityHw19GrossService {
 
    @Autowired
    private QualityHw19CodeMapper codeMapper;
 
    @Autowired
    private QualityHw19CodeBingMapper bingMapper;
 
    @Autowired
    private DictUtils dictUtils;
 
    @Autowired
    private StockBean stockBean;
 
    @Autowired
    private HwWeightLabelConfigMapper hwWeightLabelConfigMapper;
 
    @Autowired
    private static final ScriptEngineManager manager = new ScriptEngineManager();
 
    @Autowired
    private RemoteParamService remoteParamService;
 
    @Autowired
    private HwWeightLabelConfigUtils hwWeightLabelConfigUtils;
 
    @Override
    public Quality19GrossPrintDTO getPrintInfo(Long id) throws Exception {
        //校验数据
        R r = hwWeightLabelConfigUtils.printCheck(id);
 
        QualityHw19Gross entity = this.baseMapper.selectById(id);
        Quality19GrossPrintDTO printDTO = new Quality19GrossPrintDTO();
        BeanUtils.copyProperties(entity,printDTO);
 
        String res = remoteParamService.getByKey(HwWeightLabelConfig.CHECK_WEIGHT_SWITCH, SecurityConstants.FROM_IN).getData();
        if (null != res && res.equals("true")) {
            //校验开关打开
            if (r.getCode() == 1) {
                printDTO.setNeedPwd(true);
                printDTO.setHintMsg(r.getMsg());
            }
        }
 
        //校验满足条件,则更新打印次数,否则在通过密码强制验证通过时更新打印次数
        if (!printDTO.getNeedPwd()) {
            this.baseMapper.updatePrintCount(id);
        }
 
        return printDTO;
    }
 
    @Override
    public BigDecimal getWeight(String weighingApiAddress) {
        String resp = getGrossWei(weighingApiAddress);
        return new BigDecimal(resp);
//
//        int i = RandomUtil.randomInt(100, 600);
//        return new BigDecimal(i);
    }
 
    @Override
    public void insert(QualityHw19Gross qualityHw19Gross) throws Exception {
 
        //校验
        String codeCer = qualityHw19Gross.getCodeCer();
        if (StringUtils.isBlank(codeCer)) {
            throw new RuntimeException("合格证不能为空!");
        }
        String[] cerSplit = codeCer.split("&");
        if (cerSplit.length != 2) {
            throw new RuntimeException("合格证格式不对!");
        }
        String serialNum = cerSplit[0];
        BigDecimal length = new BigDecimal(cerSplit[1]);
        //1.流水号唯一性
        Integer countSerial = this.baseMapper.selectCount(Wrappers.<QualityHw19Gross>lambdaQuery().eq(QualityHw19Gross::getSerialNum, serialNum));
        if (countSerial > 0) {
            throw new RuntimeException("毛重表中已存在流水号");
        }
 
        //2.流水号、19码、箱码是否绑定
        Integer countBox = bingMapper.selectCount(Wrappers.<QualityHw19CodeBing>lambdaQuery().eq(QualityHw19CodeBing::getSerialNum, serialNum)
                .eq(QualityHw19CodeBing::getBarCode, qualityHw19Gross.getBarCode()).eq(QualityHw19CodeBing::getCodeBox, qualityHw19Gross.getCodeBox()));
        if (countBox == 0) {
            throw new RuntimeException("流水号、19码、箱码未绑定");
        }
 
        //3.19码长度与合格证长度校验
        QualityHw19Code qualityHw19Code = codeMapper.selectOne(Wrappers.<QualityHw19Code>lambdaQuery().eq(QualityHw19Code::getBarCode, qualityHw19Gross.getBarCode()));
        if (length.compareTo(qualityHw19Code.getLength()) != 0) {
            throw new RuntimeException("合格证长度与19码长度不一致");
        }
 
 
        //生成尺寸
        //改成从配置表中获取
        String size = null;
//        if (length.compareTo(new BigDecimal(100)) == 0) {
//            size = "480*240*480";
//        } else if (length.compareTo(new BigDecimal(100))>0 && length.compareTo(new BigDecimal(300))<=0) {
//            size = "400*400*320";
//        } else if (length.compareTo(new BigDecimal(300)) > 0 && length.compareTo(new BigDecimal(600)) <= 0) {
//            size = "550*550*460";
//        } else {
//            throw new RuntimeException(length + "长度不在[100,600]范围内,无对应尺寸");
//        }
 
        //根据19条码获取客户物料编码
        List<QualityHw19Code> qualityHw19CodeList = codeMapper.selectList(Wrappers.<QualityHw19Code>lambdaQuery().eq(QualityHw19Code::getBarCode,qualityHw19Gross.getBarCode()));
        if (CollectionUtils.isEmpty(qualityHw19CodeList)){
            throw new RuntimeException("19条码 = 【" + qualityHw19Gross.getBarCode() + "】 -> 查无生码记录");
        }
 
        if (qualityHw19CodeList.size() != 1) {
            throw new RuntimeException("19条码 = 【" + qualityHw19Gross.getBarCode() + "】 -> 存在多条生码记录");
        }
 
        //根据客户物料编码获取称重配置数据
        List<HwWeightLabelConfig> hwWeightLabelConfigList = hwWeightLabelConfigUtils.getConfigs(qualityHw19CodeList.get(0).getMaterialCode());
 
        //根据客户物料编码及长度获取对应的配置记录行
        HwWeightLabelConfig hwWeightLabelConfig = hwWeightLabelConfigUtils.getConfigLine(hwWeightLabelConfigList, qualityHw19CodeList.get(0).getLength());
 
        qualityHw19Gross.setSize(hwWeightLabelConfig.getPackSize());
        size = hwWeightLabelConfig.getPackSize();
 
        //生成尺寸码
        String[] sizeSplit = size.split("\\*");
        String sizeCode = "230"+sizeSplit[0]+"/0"+sizeSplit[1]+"/0"+sizeSplit[2]+"9";
        qualityHw19Gross.setCodeSize(sizeCode);
 
        //生成毛重码
        BigDecimal grossWei = qualityHw19Gross.getGrossWei();
        if (grossWei == null) {
            throw new RuntimeException("毛重不能为空!");
        }
        if (grossWei.compareTo(new BigDecimal(100))>0) {
            throw new RuntimeException("毛重超出(0,100]范围,请核对!");
        }
        DecimalFormat decimalFormat = new DecimalFormat("00.00");//客户要求保留两位小数
        String grossStr = decimalFormat.format(grossWei);
        String[] grossSplit = grossStr.split("[.]");
        String grossCode = "24000020"+grossSplit[0]+grossSplit[1]+"9";
        qualityHw19Gross.setCodeGross(grossCode);
 
        //生成毛重尺寸码
        qualityHw19Gross.setCodeSizeGross(sizeCode+"*"+grossCode);
 
        //生成净重
        //包装重量改成从配置表中获取
//        Map<String, String> grossTypeMap = dictUtils.getDicKey("hw_gross_type");
//        String sub = grossTypeMap.get(size);//根据尺寸获取盘重
//        qualityHw19Gross.setNetWei(grossWei.subtract(new BigDecimal(sub)));
        switch (hwWeightLabelConfig.getPackMaterial()) {
            case "纸箱" :
                //实际净重 = 毛重 - 纸箱重量
                qualityHw19Gross.setNetWei(qualityHw19Gross.getGrossWei().subtract(hwWeightLabelConfig.getCartonWeight()));
                break;
            case "盘具" :
                //实际净重 = 毛重 - 空盘具重量 + 纸板重量
                qualityHw19Gross.setNetWei(qualityHw19Gross.getGrossWei().subtract(hwWeightLabelConfig.getEmptyTrayWeight()).add(hwWeightLabelConfig.getPaperboardWeight()));
                break;
            default:
                //没有包材,不需要打印称重标签,也无法知道确切的净重
                break;
 
        }
 
        qualityHw19Gross.setSerialNum(serialNum);
        qualityHw19Gross.setIsMatch(1);
 
        //根据长度校验实际净重是否在标准范围内
        BigDecimal a;
        BigDecimal b;
        BigDecimal standardWeight;
        BigDecimal errorPer;
        DecimalFormat decimalFormatTip = new DecimalFormat("00.00");//报错提示精度
        //临时取消,后期需求整改
//        if (length.compareTo(new BigDecimal(600)) == 0) {
//            standardWeight = new BigDecimal(67.5);
//            errorPer = new BigDecimal(0.03);
//            a = standardWeight.subtract(standardWeight.multiply(errorPer));
//            b = standardWeight.add(standardWeight.multiply(errorPer));
//            if (qualityHw19Gross.getNetWei().compareTo(a) == -1 || qualityHw19Gross.getNetWei().compareTo(b) == 1) {
//                throw new RuntimeException("实际净重 = " + qualityHw19Gross.getNetWei() + " -> 超出标准范围 -> [" + decimalFormatTip.format(a) + "," + decimalFormatTip.format(b) + "]");
//            }
//        } else if (length.compareTo(new BigDecimal(100)) == 0) {
//            standardWeight = new BigDecimal(16);
//            errorPer = new BigDecimal(0.04);
//            a = standardWeight.subtract(standardWeight.multiply(errorPer));
//            b = standardWeight.add(standardWeight.multiply(errorPer));
//            if (qualityHw19Gross.getNetWei().compareTo(a) == -1 || qualityHw19Gross.getNetWei().compareTo(b) == 1) {
//                throw new RuntimeException("实际净重 = " + qualityHw19Gross.getNetWei() + " -> 超出标准范围 -> [" + decimalFormatTip.format(a) + "," + decimalFormatTip.format(b) + "]");
//            }
//        }
        this.baseMapper.insert(qualityHw19Gross);
    }
 
    @Override
    public R checkPwd(String pwd, Long id) {
        String res = remoteParamService.getByKey(HwWeightLabelConfig.PWD, SecurityConstants.FROM_IN).getData();
 
        if (null == pwd || pwd.length() == 0) {
            return R.failed("密码不可为空");
        }
 
        if (null == res) {
            return R.failed("密码验证失败");
        }
 
        if (!res.equals(pwd)) {
            return R.failed("密码错误");
        }
 
        //密码校验通过后,更新打印次数
        this.baseMapper.updatePrintCount(id);
        return R.ok();
    }
 
    /**
     * 获取毛重
     * @return
     */
    public String getGrossWei(String weighingApiAddress) {
        String ok = "OK";
        String key = "result";
        String weight = "message";
 
        JSONObject jsonObject;
 
        try {
            //从地磅获取称重
            Map<String, Object> paramMap = new HashMap<>(16);
            String result = HttpRequest.get(weighingApiAddress).form(paramMap).execute().body();
            //String result = "[{\"result\":\"OK\",\"message\":\"0.5\"}]";//测试用
            JSONArray jsonArray = JSONObject.parseArray(result);
            jsonObject = jsonArray.getJSONObject(0);
 
        } catch (Exception e) {
            throw new RuntimeException("调用接口失败");
        }
 
        if (jsonObject.getString(key).equals(ok)){
            return jsonObject.getString(weight);
        }else{
            throw new RuntimeException("获取称重失败 -> " + jsonObject.getString(weight));
        }
 
//        String resp = HttpRequest.get(stockBean.getGd_1()).execute().body();
//        if (StringUtils.isBlank(resp)) {
//            throw new RuntimeException("称重接口请求失败,未获取到数据");
//        }
//        String result = resp.substring(resp.indexOf("<result>") + 8, resp.indexOf("</result>"));
//        if (!result.equals("OK")) {
//            throw new RuntimeException("称重接口请求失败:"+resp);
//        }
//        return resp.substring(resp.indexOf("<message>") + 9, resp.indexOf("</message>"));
    }
 
 
    @Override
    public void exportInfo(HttpServletResponse response, QualityHw19Gross req) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("19条码毛重", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "19条码").head(QualityHw19GrossData.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<QualityHw19Gross> list = this.list(QueryWrapperUtil.gen(req));
            List<QualityHw19GrossData> respList = new ArrayList<>();
            for (QualityHw19Gross qualityHw19Gross : list) {
                QualityHw19GrossData resp = new QualityHw19GrossData();
                BeanUtils.copyProperties(qualityHw19Gross,resp);
                LocalDateTime createTime = qualityHw19Gross.getCreateTime();
                if (createTime != null) {
                    resp.setCreateTime(createTime.toString().replace("T"," "));
                }
                respList.add(resp);
            }
            excelWriter.write(respList, mainSheet);
 
            //关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
 
    }
 
    @Override
    public void exportModel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("19条码毛重模板", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        try {
            //新建ExcelWriter
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            //获取sheet0对象
            WriteSheet mainSheet = EasyExcel.writerSheet(0, "19条码").head(QualityHw19GrossImportData.class).build();
            //向sheet0写入数据 传入空list这样只导出表头
            List<QualityHw19GrossImportData> respList = new ArrayList<>();
            excelWriter.write(respList, mainSheet);
            //关闭流
            excelWriter.finish();
        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }
 
    @Override
    public void importExcel(List<QualityHw19GrossImportData> list) {
        List<QualityHw19Gross> qualityHw19GrossList = new ArrayList<>();
        List<String> serialNumList = new ArrayList<>();
        for (QualityHw19GrossImportData qualityHw19GrossImportData : list) {
            //校验
            String codeCer = qualityHw19GrossImportData.getCodeCer();
            if (StringUtils.isBlank(codeCer)) {
                throw new RuntimeException("合格证不能为空!");
            }
            String[] cerSplit = codeCer.split("&");
            if (cerSplit.length != 2) {
                throw new RuntimeException("合格证格式不对!");
            }
            String serialNum = cerSplit[0];
            serialNumList.add(serialNum);
            BigDecimal length = new BigDecimal(cerSplit[1]);
            //1.流水号唯一性
            Integer countSerial = this.baseMapper.selectCount(Wrappers.<QualityHw19Gross>lambdaQuery().eq(QualityHw19Gross::getSerialNum, serialNum));
            if (countSerial > 0) {
                throw new RuntimeException("毛重表中已存在流水号");
            }
            //2.流水号、19码、箱码是否绑定
            if (StringUtils.isBlank(qualityHw19GrossImportData.getBarCode())) {
                throw new RuntimeException("19码不能为空!");
            }
            if (StringUtils.isBlank(qualityHw19GrossImportData.getCodeBox())) {
                throw new RuntimeException("箱码不能为空!");
            }
            Integer countBox = bingMapper.selectCount(Wrappers.<QualityHw19CodeBing>lambdaQuery().eq(QualityHw19CodeBing::getSerialNum, serialNum)
                    .eq(QualityHw19CodeBing::getBarCode, qualityHw19GrossImportData.getBarCode()).eq(QualityHw19CodeBing::getCodeBox, qualityHw19GrossImportData.getCodeBox()));
            if (countBox == 0) {
                throw new RuntimeException("流水号、19码、箱码未绑定");
            }
 
            //3.19码长度与合格证长度校验
            QualityHw19Code qualityHw19Code = codeMapper.selectOne(Wrappers.<QualityHw19Code>lambdaQuery().eq(QualityHw19Code::getBarCode, qualityHw19GrossImportData.getBarCode()));
            if (length.compareTo(qualityHw19Code.getLength()) != 0) {
                throw new RuntimeException("合格证长度与19码长度不一致");
            }
 
            //根据19条码获取客户物料编码
            List<QualityHw19Code> qualityHw19CodeList = codeMapper.selectList(Wrappers.<QualityHw19Code>lambdaQuery().eq(QualityHw19Code::getBarCode,qualityHw19GrossImportData.getBarCode()));
            if (CollectionUtils.isEmpty(qualityHw19CodeList)){
                throw new RuntimeException("19条码 = 【" + qualityHw19GrossImportData.getBarCode() + "】 -> 查无生码记录");
            }
 
            if (qualityHw19CodeList.size() != 1) {
                throw new RuntimeException("19条码 = 【" + qualityHw19GrossImportData.getBarCode() + "】 -> 存在多条生码记录");
            }
 
            //毛重码校验
            if (qualityHw19GrossImportData.getGrossWei() == null) {
                throw new RuntimeException("毛重不能为空!");
            }
            if (qualityHw19GrossImportData.getGrossWei().compareTo(new BigDecimal(100))>0) {
                throw new RuntimeException("毛重超出(0,100]范围,请核对!");
            }
            QualityHw19Gross qualityHw19Gross = new QualityHw19Gross();
            BeanUtils.copyProperties(qualityHw19GrossImportData,qualityHw19Gross);
            qualityHw19Gross.setSerialNum(serialNum);
            qualityHw19GrossList.add(qualityHw19Gross);
        }
        long serialNum = serialNumList.stream().distinct().count();
        if (serialNum < serialNumList.size()) {
            throw new RuntimeException("导入记录中流水号重复");
        }
        saveBatch(qualityHw19GrossList);
 
    }
}