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 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.lambdaQuery().eq(QualityHw19Gross::getSerialNum, serialNum)); if (countSerial > 0) { throw new RuntimeException("毛重表中已存在流水号"); } //2.流水号、19码、箱码是否绑定 Integer countBox = bingMapper.selectCount(Wrappers.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.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 qualityHw19CodeList = codeMapper.selectList(Wrappers.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 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 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 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("") + 8, resp.indexOf("")); // if (!result.equals("OK")) { // throw new RuntimeException("称重接口请求失败:"+resp); // } // return resp.substring(resp.indexOf("") + 9, resp.indexOf("")); } @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 list = this.list(QueryWrapperUtil.gen(req)); List 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 respList = new ArrayList<>(); excelWriter.write(respList, mainSheet); //关闭流 excelWriter.finish(); } catch (IOException e) { throw new RuntimeException("导出失败"); } } @Override public void importExcel(List list) { List qualityHw19GrossList = new ArrayList<>(); List 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.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.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.lambdaQuery().eq(QualityHw19Code::getBarCode, qualityHw19GrossImportData.getBarCode())); if (length.compareTo(qualityHw19Code.getLength()) != 0) { throw new RuntimeException("合格证长度与19码长度不一致"); } //根据19条码获取客户物料编码 List qualityHw19CodeList = codeMapper.selectList(Wrappers.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); } }