zss
2024-11-26 a5b1bad21ba279ade3954852a5e281e9086042f0
inspect-server/src/main/java/com/yuanchu/mom/service/impl/InsOrderServiceImpl.java
@@ -1,5 +1,6 @@
package com.yuanchu.mom.service.impl;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
@@ -7,6 +8,7 @@
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
@@ -19,19 +21,28 @@
import com.yuanchu.mom.exception.ErrorException;
import com.yuanchu.mom.mapper.*;
import com.yuanchu.mom.pojo.*;
import com.yuanchu.mom.service.InformationNotificationService;
import com.yuanchu.mom.service.InsOrderPlanService;
import com.yuanchu.mom.service.InsOrderService;
import com.yuanchu.mom.service.InsProductService;
import com.yuanchu.mom.utils.GiveCode;
import com.yuanchu.mom.utils.QYWXApi;
import com.yuanchu.mom.utils.QueryWrappers;
import com.yuanchu.mom.vo.SampleDefectsFatherVo;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -46,38 +57,45 @@
 * @createDate 2024-03-12 16:17:55
 */
@Service
@AllArgsConstructor
public class InsOrderServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder>
        implements InsOrderService {
@Transactional(rollbackFor = Exception.class)
public class InsOrderServiceImpl extends ServiceImpl<InsOrderMapper, InsOrder> implements InsOrderService {
    @Resource
    private GetLook getLook;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private InsOrderMapper insOrderMapper;
    @Value("${file.path}")
    private String imgUrl;
    @Value("${wordUrl}")
    private String wordUrl;
    @Resource
    private InsOrderFileMapper insOrderFileMapper;
    @Resource
    private InsSampleMapper insSampleMapper;
    @Resource
    InsProductResult2Mapper insProductResult2Mapper;
    @Resource
    InsProductResultMapper insProductResultMapper;
    @Resource
    private InsProductMapper insProductMapper;
    private InsProductService insProductService;
    @Resource
    private InsProductUserMapper insProductUserMapper;
    @Resource
    private GiveCode giveCode;
    private InsSampleUserMapper insSampleUserMapper;
    private InsOrderStateMapper insOrderStateMapper;
    @Resource
    UserMapper userMapper;
    @Resource
    InformationNotificationService informationNotificationService;
    @Resource
    PowerMapper powerMapper;
    private InsBushingMapper insBushingMapper;
    private InsFibersMapper insFibersMapper;
    private InsFiberMapper insFiberMapper;
    @Resource
    CustomMapper customMapper;
    @Resource
    QYWXApi qywxApi;
    //获取检验下单数据
@@ -89,17 +107,7 @@
        Map<String, Integer> map1 = getLook.selectPowerByMethodAndUserId("selectInsOrderParameter");
        User user = userMapper.selectById(map1.get("userId"));//当前登录的人
        Integer roleId = user.getRoleId();
        //获取当前人所属实验室id
        String departLimsId = user.getDepartLimsId();
        String laboratory = null;
        if (ObjectUtils.isNotEmpty(departLimsId) && !departLimsId.equals("")) {
            String[] split = departLimsId.split(",");
            //查询对应架构名称(通信实验室,电力实验室,检测办)
            String departLims = baseMapper.seldepLimsId(Integer.parseInt(split[split.length - 1]));
            if (departLims.contains("实验室")) {
                laboratory = departLims;
            }
        }
        //判断是否是全部权限
        Power power = powerMapper.selectOne(Wrappers.<Power>lambdaQuery().eq(Power::getRoleId, roleId).eq(Power::getMenuMethod, "selectAllInsOrderParameter"));
        if (ObjectUtils.isEmpty(power)) {
@@ -128,73 +136,30 @@
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int upInsOrder(Integer orderId, Integer sampleId, String appointed, Integer userId, String sonLaboratory) {
        InsOrder insOrder = new InsOrder();
        insOrder.setId(orderId);
        insOrder.setAppointed(LocalDate.parse(appointed));
        insOrder.setSendTime(LocalDateTime.now());
        insOrderMapper.updateById(insOrder);
        List<InsSample> insSamples = insSampleMapper.selectList(Wrappers.<InsSample>lambdaQuery().eq(InsSample::getInsOrderId, orderId).select(InsSample::getId));
        List<Integer> ids = insSamples.stream().map(a -> a.getId()).collect(Collectors.toList());
        List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                .in(InsProduct::getInsSampleId, ids)
                .eq(InsProduct::getState, 1)
//                .isNull(InsProduct::getInsFibersId)
//                .isNull(InsProduct::getInsFiberId)
                .select(InsProduct::getSonLaboratory).groupBy(InsProduct::getSonLaboratory));
        for (InsProduct insProduct : insProducts) {
            InsOrderState insOrderState = new InsOrderState();
            insOrderState.setInsOrderId(orderId);
            try {
                insOrderState.setLaboratory(insProduct.getSonLaboratory());
            } catch (NullPointerException e) {
                throw new ErrorException("该检验单有未维护实验室的检验项目");
            }
            insOrderState.setInsState(0);
            insOrderStateMapper.insert(insOrderState);
        }
        if (userId != null) {
            InsSampleUser insSampleUser = new InsSampleUser();
            insSampleUser.setState(0);
            insSampleUser.setUserId(userId);
            insSampleUser.setInsSampleId(orderId);
            insSampleUser.setSonLaboratory(sonLaboratory);
            insSampleUserMapper.insert(insSampleUser);
        }
        return 1;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addInsOrder(List<SampleProductDto> list, InsOrder insOrder, List<List<Integer>> pairing) {
    public int addInsOrder(List<SampleProductDto> list, InsOrder insOrder, List<List<Integer>> pairing, List<MultipartFile> files) {
        insOrder.setState(0);
        //判断选择的委托单位与制单人的委托单位是否一致
        Integer userId = getLook.selectPowerByMethodAndUserId(null).get("userId");
        String company = userMapper.selectById(userId).getCompany();
        if (!company.equals(insOrder.getCompanyId()+"")) {
        if (!company.equals(insOrder.getCompanyId() + "")) {
            //如果不一致那么委托人字段必填
            if (ObjectUtils.isEmpty(insOrder.getPrepareUser())){
            if (ObjectUtils.isEmpty(insOrder.getPrepareUser())) {
                throw new ErrorException("委托人不能为空");
            }
        }else {
        } else {
            //如果一致,那么制单人就是委托人
            insOrder.setPrepareUser(insOrder.getCustom());
        }
        //客户代号
        Custom custom = customMapper.selectById(insOrder.getCompanyId());
        String code = custom.getCode2();
        if (!custom.getCompany().equals(insOrder.getCompany())){
        if (!custom.getCompany().equals(insOrder.getCompany())) {
            Custom one = customMapper.selectOne(Wrappers.<Custom>lambdaQuery().eq(Custom::getCompany, insOrder.getCompany()));
            insOrder.setCompanyId(one.getId());
            code=one.getCode2();
        }
        //实验室编号
        String code2 = baseMapper.selLaboratoryCode(insOrder.getLaboratory());
        if (StringUtils.isEmpty(code2)) {
            code2 = "";
            code = one.getCode2();
        }
        //外部委托编号
        insOrder.setOutEntrustCode(giveCode.giveCode3("ZT/" + code2 + "-" + code + "-", insOrder.getCompanyId(), insOrder.getLaboratory(), "ins_order", "", "yyMM"));
        insOrder.setOutEntrustCode(giveCode.giveCode("WT-", "ins_order", "-", "yyMMdd"));
        String giveCode = this.giveCode.giveCode("JCZX-" + code + "-", "ins_sample", "", "yyMMdd");
        insOrderMapper.insert(insOrder);
        AtomicInteger count = new AtomicInteger();
@@ -202,67 +167,16 @@
            count.getAndIncrement();
            a.setId(null);
            a.setInsOrderId(insOrder.getId());
            //样品编号
            if (StrUtil.isEmpty(a.getSampleCode())) {
                a.setSampleCode(giveCode.split("-")[2] + "-" + count.get());
                a.setSampleCode("YP-" + a.getModel() + "-" + giveCode.split("-")[2] + "-" + count.get());
            }
            insSampleMapper.insert(a);
            //样品的检验项目
            if (ObjectUtil.isNotEmpty(a.getInsProduct())) {
                addInsProductMethod(a.getId(), a.getInsProduct(), null, 0, false);
                if (ObjectUtil.isNotEmpty(a.getBushing())) {
                    for (BushingDto bushingDto : a.getBushing()) {
                        bushingDto.setInsSampleId(a.getId());
                        insBushingMapper.insert(bushingDto);
                        //光纤不为空
                        if (bushingDto.getFiber().size() != 0) {
                            for (FiberDto fiberDto : bushingDto.getFiber()) {
                                fiberDto.setInsBushingId(bushingDto.getId());
                                insFiberMapper.insert(fiberDto);
                                addInsProductMethod(a.getId(), a.getInsProduct(), fiberDto.getId(), 2, true);
                                addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                            }
                        }
                        //光纤带不为空
                        else if ( bushingDto.getFibers().size()!=0){
                            for (FibersDto fibersDto : bushingDto.getFibers()) {
                                fibersDto.setInsBushingId(bushingDto.getId());
                                fibersDto.setCode(this.giveCode.giveCode("", "ins_fibers", "", "yyMMdd"));
                                insFibersMapper.insert(fibersDto);
                                for (FiberDto fiberDto : fibersDto.getFiber()) {
                                    fiberDto.setInsFibersId(fibersDto.getId());
                                    insFiberMapper.insert(fiberDto);
                                    addInsProductMethod(a.getId(), a.getInsProduct(), fiberDto.getId(), 2, true);
                                    addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                                }
                                //addInsProductMethod(a.getId(), a.getInsProduct(), fibersDto.getId(), 1);
                                addInsProductMethod(a.getId(), fibersDto.getProductList(), fibersDto.getId(), 1, false);
                            }
                        }
                        //都为空 只配置了套管 这种情况只限于项目是含有松套管的
                        else {
                            String collect = a.getInsProduct().stream().map(InsProduct::getInspectionItem).distinct().collect(Collectors.joining(","));
                            if (collect.contains("松套管")){
                                //获取检验项目中包含松套管的检验项目
                                List<InsProduct> products = a.getInsProduct().stream().filter(insProduct -> insProduct.getInspectionItem().contains("松套管")).collect(Collectors.toList());
                                for (InsProduct product : products) {
                                    product.setInsBushId(bushingDto.getId());
                                    product.setId(null);
                                    product.setCreateTime(null);
                                    product.setCreateUser(null);
                                    product.setUpdateTime(null);
                                    product.setUpdateUser(null);
                                    product.setInsSampleId(a.getId());
                                    if (product.getInspectionItemSubclass() == null) {
                                        product.setInspectionItemSubclass("");
                                    }
                                    insProductMapper.insert(product);
                                }
                            }else {
                                throw new ErrorException("样品的光纤配置信息里面没有配置光纤带信息也没有光纤信息,请重新配置保存再提交下单!!!");
                            }
                        }
                    }
                }
                addInsProductMethod(a.getId(), a.getInsProduct());
            }
            //样品的检验标准
            if (ObjectUtil.isNotEmpty(a.getInsulating())) {
                List<InsProduct> ip2 = new ArrayList<>();
                for (Integer i = 0; i < a.getInsulating().getNum(); i++) {
@@ -271,14 +185,16 @@
                for (InsProduct product : ip2) {
                    product.setStandardMethodListId(a.getInsulating().getStandardMethodListId());
                }
                addInsProductMethod(a.getId(), ip2, null, 0, false);
                addInsProductMethod(a.getId(), ip2);
            }
            //样品的检验标准
            if (ObjectUtil.isNotEmpty(a.getSheath())) {
                for (InsProduct product : a.getSheath().getInsProduct()) {
                    product.setStandardMethodListId(a.getSheath().getStandardMethodListId());
                }
                addInsProductMethod(a.getId(), a.getSheath().getInsProduct(), null, 0, false);
                addInsProductMethod(a.getId(), a.getSheath().getInsProduct());
            }
            //子样品配置
            if (ObjectUtil.isNotEmpty(a.getChildSampleList())) {
                for (SampleProductDto b : a.getChildSampleList()) {
                    for (int i = 0; i < b.getNum(); i++) {
@@ -290,260 +206,165 @@
                        }
                        insSampleMapper.insert(b);
                        if (ObjectUtil.isNotEmpty(b.getInsProduct())) {
                            addInsProductMethod(b.getId(), b.getInsProduct(), null, 0, false);
                            addInsProductMethod(b.getId(), b.getInsProduct());
                        }
                    }
                }
            }
            if (ObjectUtil.isEmpty(a.getInsProduct()) && ObjectUtil.isNotEmpty(a.getBushing())) {
                for (BushingDto bushingDto : a.getBushing()) {
                    bushingDto.setInsSampleId(a.getId());
                    insBushingMapper.insert(bushingDto);
                    if (bushingDto.getFiber().size() != 0) {
                        for (FiberDto fiberDto : bushingDto.getFiber()) {
                            fiberDto.setInsBushingId(bushingDto.getId());
                            insFiberMapper.insert(fiberDto);
                            addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                        }
                    } else {
                        for (FibersDto fibersDto : bushingDto.getFibers()) {
                            fibersDto.setInsBushingId(bushingDto.getId());
                            fibersDto.setCode(this.giveCode.giveCode("", "ins_fibers", "", "yyMMdd"));
                            insFibersMapper.insert(fibersDto);
                            for (FiberDto fiberDto : fibersDto.getFiber()) {
                                fiberDto.setInsFibersId(fibersDto.getId());
                                insFiberMapper.insert(fiberDto);
                                addInsProductMethod(a.getId(), fiberDto.getProductList(), fiberDto.getId(), 2, false);
                            }
                            addInsProductMethod(a.getId(), fibersDto.getProductList(), fibersDto.getId(), 1, false);
                        }
                    }
                }
            }
        });
        for (List<Integer> i : pairing) {
            SampleProductDto sample = JSON.parseObject(JSON.toJSONString(list.get(i.get(0) - 1)), SampleProductDto.class);
            sample.setSampleCode(list.get(i.get(0) - 1).getSampleCode() + "/" + list.get(i.get(1) - 1).getSampleCode());
            sample.setId(null);
            insSampleMapper.insert(sample);
            try {
                List<InsProduct> insProducts = sample.getInsProduct().stream().filter(a -> Objects.equals(a.getInspectionItem(), "光纤接头损耗")).collect(Collectors.toList());
                for (InsProduct insProduct : insProducts) {
                    insProduct.setId(null);
                    insProduct.setInsSampleId(sample.getId());
                    insProductMapper.insert(insProduct);
                }
            } catch (Exception e) {
        List<User> users1 = userMapper.getUserByRole("检测中心主任");
        List<User> users2 = userMapper.getUserByRole("研发部经理");
        List<User> users3 = userMapper.getUserByRole("技术负责人");
        //通信:如果是C类订单无需审核直接通过
        if (insOrder.getOrderType().equals("C")) {
            insOrder.setState(1);
            upInsOrderOfState(insOrder);
        } else if (insOrder.getOrderType().equals("A")) {
            //常规外部单需消息提醒检验中心主任和研发部经理
            //todo 企业微信推送
            users1.addAll(users2);
            String account = users1.stream().map(User::getAccount).collect(Collectors.joining("|"));
            HashMap<String, Object> map = new HashMap<>();
            map.put("touser", account);//接收消息成员的账号'ZT-031292'这种类型(如果有多个用'|'分隔)
            map.put("msgtype", "text");//消息类型 text:文本
            map.put("agentid", 1000517);//应用id
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("content", "您有一条检验订单需要审核,请前往LIMS系统查看。外部订单号是:" + insOrder.getOutEntrustCode() + ",请前往LIMS系统查看。<a href=\"https://ztwxlims.ztt.cn:7443/enter\">中天通信LIMS系统 </a>");
            map.put("text", hashMap);//消息内容
            map.put("safe", 0);//是否保密消息.0否
            map.put("enable_id_trans", 0);//是否开启id转译.0否
            map.put("enable_duplicate_check", 0);//是否开启重复消息检查.0否
            qywxApi.send(map);
            //lims消息提醒
            ArrayList<InformationNotification> notificationArrayList = new ArrayList<>();
            for (User user : users1) {
                InformationNotification info = new InformationNotification();
                info.setCreateUser(userMapper.selectById(userId).getName());
                info.setMessageType("2");
                info.setTheme("审核通知");
                info.setContent("您有一条检验订单待审核消息,订单的外部编号是:" + insOrder.getOutEntrustCode());
                info.setSenderId(userId);
                info.setViewStatus(false);
                info.setJumpPath("b1-inspection-order");
                info.setConsigneeId(user.getId());
                notificationArrayList.add(info);
            }
            informationNotificationService.saveBatch(notificationArrayList);
        } else if (insOrder.getOrderType().equals("B")) {
            //非常规外部单需消息提醒检验中心主任,研发部经理和技术负责人
            //todo 企业微信推送
            users1.addAll(users2);
            users1.addAll(users3);
            String account = users1.stream().map(User::getAccount).collect(Collectors.joining("|"));
            HashMap<String, Object> map = new HashMap<>();
            map.put("touser", account);//接收消息成员的账号'ZT-031292'这种类型(如果有多个用'|'分隔)
            map.put("msgtype", "text");//消息类型 text:文本
            map.put("agentid", 1000517);//应用id
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("content", "您有一条检验订单需要审核,请前往LIMS系统查看。外部订单号是:" + insOrder.getOutEntrustCode() + ",请前往LIMS系统查看。<a href=\"https://ztwxlims.ztt.cn:7443/enter\">中天通信LIMS系统 </a>");
            map.put("text", hashMap);//消息内容
            map.put("safe", 0);//是否保密消息.0否
            map.put("enable_id_trans", 0);//是否开启id转译.0否
            map.put("enable_duplicate_check", 0);//是否开启重复消息检查.0否
            qywxApi.send(map);
            //lims消息提醒
            ArrayList<InformationNotification> notificationArrayList = new ArrayList<>();
            for (User user : users1) {
                InformationNotification info = new InformationNotification();
                info.setCreateUser(userMapper.selectById(userId).getName());
                info.setMessageType("2");
                info.setTheme("审核通知");
                info.setContent("您有一条检验订单待审核消息,订单的外部编号是:" + insOrder.getOutEntrustCode());
                info.setSenderId(userId);
                info.setViewStatus(false);
                info.setJumpPath("b1-inspection-order");
                info.setConsigneeId(user.getId());
                notificationArrayList.add(info);
            }
            informationNotificationService.saveBatch(notificationArrayList);
        }
        //如果有上传的附件
        if (CollectionUtils.isNotEmpty(files)) {
            for (MultipartFile file : files) {
                String urlString;
                String pathName;
                String path;
                String filename = file.getOriginalFilename();
                String contentType = file.getContentType();
                InsOrderFile insOrderFile = new InsOrderFile();
                insOrderFile.setInsOrderId(insOrder.getId());
                insOrderFile.setFileName(filename);
                if (contentType != null && contentType.startsWith("image/")) {
                    // 是图片
                    path = imgUrl;
                    insOrderFile.setType(1);
                } else {
                    // 是文件
                    path = wordUrl;
                    insOrderFile.setType(2);
                }
                try {
                    File realpath = new File(path);
                    if (!realpath.exists()) {
                        realpath.mkdirs();
                    }
                    pathName = UUID.randomUUID() + "_" + file.getOriginalFilename().replace("#", "&");
                    urlString = realpath + "/" + pathName;
                    file.transferTo(new File(urlString));
                    insOrderFile.setFileUrl(pathName);
                    insOrderFileMapper.insert(insOrderFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.err.println("附件上传错误");
                }
            }
        }
        //todo 根据订单类型判断是否需要推送企业微信 @zss
        if (!insOrder.getFormType().equals("其他成品")) {
            String account = userMapper.selectById(insOrder.getIssueUser()).getAccount();
            HashMap<String, Object> map = new HashMap<>();
            map.put("touser", account);//接收消息成员的账号'ZT-031292'这种类型(如果有多个用'|'分隔)
            map.put("msgtype", "text");//消息类型 text:文本
            map.put("agentid", 1000517);//应用id
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("content", "您有一条订单需要完成,请前往LIMS系统查看。外部订单号是:" + insOrder.getOutEntrustCode() + ",请前往LIMS系统查看。<a href=\"https://ztwxlims.ztt.cn:7443/enter\">中天通信LIMS系统 </a>");
            map.put("text", hashMap);//消息内容
            map.put("safe", 0);//是否保密消息.0否
            map.put("enable_id_trans", 0);//是否开启id转译.0否
            map.put("enable_duplicate_check", 0);//是否开启重复消息检查.0否
            qywxApi.send(map);
            //LIMS系统消息推送
            InformationNotification info = new InformationNotification();
            info.setCreateUser(insProductMapper.selectUserById(userId).get("name"));
            info.setMessageType("1");
            info.setTheme("样机员通知");
            info.setContent("您有一条检验订单的样机待完成消息,外部订单号是:" + insOrder.getOutEntrustCode() + ",请前往LIMS系统查看。");
            info.setSenderId(userId);
            info.setConsigneeId(insOrder.getIssueUser());
            info.setViewStatus(false);
            info.setJumpPath("b1-inspection-order");
            informationNotificationService.addInformationNotification(info);
        }
        return insOrder.getId();
    }
    private void addInsProductMethod(Integer sampleId, List<InsProduct> productList, Integer id, Integer type, Boolean is) {
        InsOrder insOrder = insOrderMapper.selectById(insSampleMapper.selectById(sampleId).getInsOrderId());
        String name = insSampleMapper.selMethodById(sampleId);
    private void addInsProductMethod(Integer sampleId, List<InsProduct> productList) {
        for (InsProduct product : productList) {
            if (product.getInspectionItem().contains("松套管")){
                continue;
            }
            if (product.getState() == 1 && !product.getInspectionItem().equals("光纤接头损耗")) {
                //判断光缆的温度循环项目添加
                if (insOrder.getSampleType().equals("光缆") && product.getInspectionItem().equals("温度循环") && type != 0) {
                    //判断选择的标准方法是委托要求还是其他标准方法
                    if (!name.equals("委托要求")) {
                        //判断标准方法的温度循环的要求描述是否有填写
                        if (ObjectUtils.isEmpty(product.getTell()) || product.getTell().equals("")) {
                            throw new ErrorException("光缆的温度循环的要求描述为空,需要在标准库配置要求描述!!!");
                        } else {
                            //解析(温度范围:20℃,-40℃,65℃;保温时间:12h; 循环次数:2次; 光纤(1310nm,1550nm)附加衰减不大于0.03dB/km)
                            String tell = product.getTell().replace(")", ")")
                                    .replace("(", "(")
                                    .replace(")", ")")
                                    .replace(",", ",")
                                    .replace(":", ":")
                                    .replace(";", ";")
                                    .replace("不大于", "≤")
                                    .replace("不小于", "≥")
                                    .replace("大于", ">")
                                    .replace("小于", "<")
                                    .replace("等于", "=");
                            String[] message=null;
                            String[] nm=null;
                            String ask=null;
                            String count=null;
                            try {
                                String[] strings = tell.split(";");
                                //温度
                                String temperature = strings[0];
                                String[] split = temperature.split(":");
                                 message = split[1].split(",");
                                //循环次数
                                 count = strings[2].split(":")[1].split("次")[0];
                                //光纤项目和要求值
                                String string = strings[3];
                                 nm = string.split("(")[1].split(")")[0].split(",");
                                 ask = string.split("衰减")[1].split("dB")[0];
                            }catch (Exception e){
                                throw new ErrorException("温度循环的要求描述格式异常,请参照温度范围:20℃,-40℃,65℃;保温时间:12h; 循环次数:2次; 光纤(1310nm,1550nm)附加衰减不大于0.03dB/km");
                            }
                            //拼接
                            String s="";
                            for (int i = 0; i < nm.length; i++) {
                                 s+= "20℃(常温)," + nm[i] + ",null;";
                                for (int j = 0; j < message.length; j++) {
                                    s+= message[j] + "," + nm[i] + "," + ask + ";" ;
                                }
                            }
                            s+=count;
                            product.setAsk(s);
                            insProductMapper.updateById(product);
                            dealWithTemperatureLoop(type,id,sampleId,product);
                        }
                    }
                    else {
                        //20℃(常温),1310nm,null;-40℃,1310nm,≤0.2;75℃,1310nm,<0.3;20℃,1310nm,≤0.1;20℃(常温),1550nm,null;-40℃,1550nm,≤0.2;75℃,1550nm,<0.3;20℃,1550nm,≤0.1;3
                        dealWithTemperatureLoop(type,id,sampleId,product);
                    }
            if (product.getState() == 1) {
                product.setId(null);
                product.setCreateTime(null);
                product.setCreateUser(null);
                product.setUpdateTime(null);
                product.setUpdateUser(null);
                product.setInsSampleId(sampleId);
                if (product.getInspectionItemSubclass() == null) {
                    product.setInspectionItemSubclass("");
                }
                //判断热循环项目的添加和温升试验项目的添加
                else if (product.getInspectionItem().equals("热循环") || product.getInspectionItem().equals("温升试验")) {
                    List<InsProduct> insProductess = new ArrayList<>();
                    product.setId(null);
                    product.setInsSampleId(sampleId);
                    insProductess.add(product);
                    List<InsProduct> insProductes = new ArrayList<>();
                    List<InsProduct> insProducts = new ArrayList<>();
                    String[] strings = product.getAsk().split(";");
                    //循环次数
                    int count = Integer.parseInt(strings[strings.length - 1]);
                    for (int i = 0; i < strings.length - 1; i++) {
                        String[] split = strings[i].split(",");
                        InsProduct insProduct = new InsProduct();
                        insProduct.setInspectionItem("1");//检验父项--循环次数
                        insProduct.setInspectionItemSubclass(split[0]);//检验子项--环境温度/导线温度/耐张温度/接续温度
                        insProduct.setInspectionItemSubclassEn(split[1]);//检验子项英文--环境温度/导线温度/耐张温度/接续温度
                        insProduct.setAsk(null);//检验要求
                        insProduct.setTell(null);//检验描述
                        insProduct.setInsSampleId(sampleId);
                        insProduct.setState(1);
                        insProduct.setFactory(product.getFactory());
                        insProduct.setLaboratory(product.getLaboratory());
                        insProduct.setSampleType(product.getSampleType());
                        insProduct.setSample(product.getSample());
                        insProduct.setModel(product.getModel());
                        insProduct.setSonLaboratory(product.getSonLaboratory());
                        insProduct.setUnit("℃");//单位
                        insProduct.setManHourGroup(product.getManHourGroup());
                        insProduct.setInspectionItemType("0");
                        insProduct.setInspectionValueType("1");
                        if (product.getInspectionItem().equals("热循环")) {
                            insProduct.setInspectionItemClass("直流电阻");//检验子子项--直流电阻
                            insProduct.setInspectionItemClassEn("DC resistance");//检验子子项英文--直流电阻
                            insProduct.setUnit("Ω/km");//单位
                        }
                        insProducts.add(insProduct);
                        insProductes.add(insProduct);
                        insProductess.add(insProduct);
                    }
                    //热循环才有多次循环次数
                    if (count > 1) {
                        //循环超过1次
                        for (int j = 2; j <= count; j++) {
                            for (InsProduct insProduct : insProductes) {
                                InsProduct insProduct1 = new InsProduct();
                                BeanUtils.copyProperties(insProduct, insProduct1);
                                insProduct1.setInspectionItem(j + "");//循环次数
                                insProductess.add(insProduct1);
                            }
                        }
                    }
                    insProductService.saveBatch(insProductess);
                }
                else {
                    if (!is) {
                        switch (type) {
                            case 1:
                                product.setInsFibersId(id);
                                break;
                            case 2:
                                product.setInsFiberId(id);
                                break;
                        }
                        product.setId(null);
                        product.setCreateTime(null);
                        product.setCreateUser(null);
                        product.setUpdateTime(null);
                        product.setUpdateUser(null);
                        product.setInsSampleId(sampleId);
                        if (product.getInspectionItemSubclass() == null) {
                            product.setInspectionItemSubclass("");
                        }
                        insProductMapper.insert(product);
                    }
                }
                insProductMapper.insert(product);
            }
        }
    }
    //温度循环的处理
    private void dealWithTemperatureLoop(Integer type, Integer id,Integer sampleId,InsProduct product) {
        List<InsProduct> insProductes = new ArrayList<>();
        List<InsProduct> insProducts = new ArrayList<>();
        String[] strings = product.getAsk().split(";");
        for (int i = 0; i < strings.length; i++) {
            int count = Integer.parseInt(strings[strings.length - 1]);
            if (i != strings.length - 1) {
                InsProduct insProduct = new InsProduct();
                switch (type) {
                    case 1:
                        insProduct.setInsFibersId(id);
                        break;
                    case 2:
                        insProduct.setInsFiberId(id);
                        break;
                }
                String[] split = strings[i].split(",");
                if (split[0].equals("20℃")) {
                    insProduct.setInspectionItem(count + "");//检验项--循环次数
                } else {
                    insProduct.setInspectionItem("1");//检验项--循环次数
                }
                insProduct.setInspectionItemSubclass(split[0]);//检验项--温度
                insProduct.setInspectionItemClass(split[1]);//检验项--光纤项目
                insProduct.setAsk(split[2]);//检验要求
                insProduct.setTell(strings[i]);//检验描述
                insProduct.setInsSampleId(sampleId);
                insProduct.setState(1);
                insProduct.setFactory(product.getFactory());
                insProduct.setLaboratory(product.getLaboratory());
                insProduct.setSampleType(product.getSampleType());
                insProduct.setSample(product.getSample());
                insProduct.setModel(product.getModel());
                insProduct.setSonLaboratory(product.getSonLaboratory());
                insProduct.setUnit(product.getUnit());
                insProduct.setManHourGroup(product.getManHourGroup());
                insProduct.setInspectionItemType("0");
                insProduct.setInspectionValueType("1");
                insProducts.add(insProduct);
                insProductes.add(insProduct);
            } else {
                //最后一个数据是说明会循环多少次
                if (count > 1) {
                    //循环超过1次
                    for (int j = 2; j <= count; j++) {
                        for (InsProduct insProduct : insProducts) {
                            if (!insProduct.getInspectionItemSubclass().equals("20℃") && !insProduct.getInspectionItemSubclass().equals("20℃(常温)")) {
                                InsProduct insProduct1 = new InsProduct();
                                BeanUtils.copyProperties(insProduct, insProduct1);
                                insProduct1.setInspectionItem(j + "");
                                insProductes.add(insProduct1);
                            }
                        }
                    }
                }
            }
        }
        insProductService.saveBatch(insProductes);
    }
    @Override
@@ -551,6 +372,9 @@
        Map<String, Object> map = new HashMap<>();
        InsOrder insOrder = insOrderMapper.selectById(id);
        List<SampleProductDto> list = insSampleMapper.selectSampleProductListByOrderId2(id);
        if (list.size() == 0) {
            list = insSampleMapper.selectSampleProductListByOrder2Id2(id);
        }
        map.put("insOrder", insOrder);
        map.put("sampleProduct", list);
        return map;
@@ -563,43 +387,97 @@
        insOrder.setExamineTime(LocalDateTime.now());
        if (insOrder.getState() == 1) {
            //审核通过才会生成委托编号
            String code = baseMapper.selLaboratoryCode(insOrder.getLaboratory());
            if (StringUtils.isEmpty(code)) {
                code = "";
            }
            Custom custom = customMapper.selectById(order.getCompanyId());
            System.out.println("============="+custom.getCompany());
            System.out.println("-------------"+order.getCompany());
            String code2 = custom.getCode2();
            if (!custom.getCompany().equals(order.getCompany())){
                Custom one = customMapper.selectOne(Wrappers.<Custom>lambdaQuery().eq(Custom::getCompany, order.getCompany()));
                insOrder.setCompanyId(one.getId());
                code2=one.getCode2();
            }
            insOrder.setEntrustCode(giveCode.giveCode2("JCZX/" + code + "-" + code2 + "-", insOrder.getCompanyId(), insOrder.getLaboratory(), "ins_order", "", "yyMM"));
            insOrder.setEntrustCode(giveCode.giveCode2("WT-", "ins_order", "-", "yyMMdd"));
            insOrder.setSendTime(LocalDateTime.now());
        }
        return insOrderMapper.updateById(insOrder);
    }
    @Override
    public Map<String, Object> getInsOrderAndSample(Integer id, String laboratory) {
        Map<String, Object> map = new HashMap<>();
        InsOrder insOrder = insOrderMapper.selectById(id);
        List<SampleProductDto> list = insSampleMapper.getInsOrderAndSample(id, laboratory);
        for (SampleProductDto sampleProductDto : list) {
            List<Integer> ids = sampleProductDto.getInsProduct().stream().map(InsProduct::getId).collect(Collectors.toList());
            List<InsProductUser> insProductUsers = insProductUserMapper.selectList(Wrappers.<InsProductUser>lambdaQuery()
                    .in(InsProductUser::getInsProductId, ids));
            if (CollectionUtils.isNotEmpty(insProductUsers)) {
                List<Integer> userIds = insProductUsers.stream().map(InsProductUser::getCreateUser).distinct().collect(Collectors.toList());
                String collect = userMapper.selectBatchIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
                sampleProductDto.setCheckName(collect);
    public int upInsOrderOfState2(InsOrder insOrder) {
        InsOrder order = insOrderMapper.selectById(insOrder.getId());
        //获取当前人
        Integer userId = getLook.selectPowerByMethodAndUserId(null).get("userId");
        //获取当前人的角色
        String roleName = roleMapper.selectById(userMapper.selectById(userId).getRoleId()).getName();
        //判断是检测中心主任/研发部经理/技术负责人
        switch (roleName) {
            case "检测中心主任":
                order.setCheckState1(insOrder.getState());
                order.setCheckState1User(userId);
                break;
            case "研发部经理":
                order.setCheckState2(insOrder.getState());
                order.setCheckState2User(userId);
                break;
            case "技术负责人":
                order.setCheckState3(insOrder.getState());
                order.setCheckState3User(userId);
                break;
            default:
                throw new ErrorException("当前登录用户的角色不是检测中心主任/研发部经理/技术负责人,无法进行审核");
        }
        insOrderMapper.updateById(order);
        //查询该订单是A类还是B类
        if (order.getOrderType().equals("B")) {
            //如果是B类,1和2和3都审核通过这个单子就审核通过
            if (order.getCheckState1() == 1 && order.getCheckState2() == 1 && order.getCheckState3() == 1) {
                order.setState(1);
                upInsOrderOfState(order);
            } else if (order.getCheckState1() == 2 || order.getCheckState2() == 2 || order.getCheckState3() == 2) {
                order.setState(2);
                upInsOrderOfState(order);
            }
        } else if (order.getOrderType().equals("A")) {
            //如果是A类,1和2审核通过后这个单子就审核通过
            if (order.getCheckState1() == 1 && order.getCheckState2() == 1) {
                order.setState(1);
                upInsOrderOfState(order);
            } else if (order.getCheckState1() == 2 || order.getCheckState2() == 2) {
                order.setState(2);
                upInsOrderOfState(order);
            }
        }
        return 1;
    }
    @Override
    public Map<String, Object> getInsOrderAndSample(Integer sampleId, String laboratory) {
        InsSample insSample = insSampleMapper.selectById(sampleId);
        Map<String, Object> map = new HashMap<>();
        InsOrder insOrder = insOrderMapper.selectById2(insSample.getInsOrderId());
        SampleProductDto sampleProductDto = insSampleMapper.getInsOrderAndSample(sampleId, laboratory);
        //再次试验会出现为空的情况
        if (ObjectUtils.isEmpty(sampleProductDto)) {
            List<InsProduct> insProducts = insProductMapper.selectList(Wrappers.<InsProduct>lambdaQuery()
                    .eq(InsProduct::getInsSampleId, insSample.getId())
                    .eq(InsProduct::getState, 1)
                    .eq(InsProduct::getSonLaboratory, laboratory));
            for (InsProduct insProduct : insProducts) {
                List<InsProductResult2> insProductResult2List = insProductResult2Mapper.selectList(Wrappers.<InsProductResult2>lambdaQuery()
                        .eq(InsProductResult2::getInsProductId, insProduct.getId()).isNull(InsProductResult2::getNum));
                insProduct.setInsProductResult2(insProductResult2List);
                InsProductResult insProductResult = insProductResultMapper.selectOne(Wrappers.<InsProductResult>lambdaQuery()
                        .eq(InsProductResult::getInsProductId, insProduct.getId()).isNull(InsProductResult::getNum));
                insProduct.setInsProductResult(insProductResult);
            }
            SampleProductDto dto = new SampleProductDto();
            dto.setInsProduct(insProducts);
            BeanUtils.copyProperties(insSample,dto);
            sampleProductDto=dto;
        }
        List<Integer> ids = sampleProductDto.getInsProduct().stream().map(InsProduct::getId).collect(Collectors.toList());
        List<InsProductUser> insProductUsers = insProductUserMapper.selectList(Wrappers.<InsProductUser>lambdaQuery()
                .in(InsProductUser::getInsProductId, ids));
        if (CollectionUtils.isNotEmpty(insProductUsers)) {
            List<Integer> userIds = insProductUsers.stream().map(InsProductUser::getCreateUser).distinct().collect(Collectors.toList());
            String collect = userMapper.selectBatchIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
            sampleProductDto.setCheckName(collect);
        }
        map.put("insOrder", insOrder);
        map.put("sampleProduct", list);
        map.put("sampleProduct", sampleProductDto);
        //查询所有记录模版去重
        List<Map<Integer, Object>> list2 = insOrderMapper.selectReportModelByOrderId(id, laboratory);
        List<Map<Integer, Object>> list2 = insOrderMapper.selectReportModelByOrderId(insSample.getInsOrderId(), laboratory);
        map.put("reportModel", list2);
        return map;
    }
@@ -608,19 +486,19 @@
    public Map<String, Object> selectSampleAndProductByOrderId(IPage<SampleProductDto2> page, SampleProductDto2 sampleProductDto) {
        Map<String, Object> map = new HashMap<>();
        map.put("head", PrintChina.printChina(SampleProductDto2.class));
        IPage<SampleProductDto2> productDto2IPage = insOrderMapper.selectSampleAndProductByOrderId(page, QueryWrappers.queryWrappers(sampleProductDto).orderByAsc("inspection_item"),sampleProductDto.getId());
        IPage<SampleProductDto2> productDto2IPage = insOrderMapper.selectSampleAndProductByOrderId(page, QueryWrappers.queryWrappers(sampleProductDto).orderByAsc("inspection_item"), sampleProductDto.getId());
        for (SampleProductDto2 record : productDto2IPage.getRecords()) {
            InsProductUser insProductUser = insProductUserMapper.selectOne(Wrappers.<InsProductUser>lambdaQuery()
                    .eq(InsProductUser::getInsProductId, record.getInsProductId())
                    .orderByDesc(InsProductUser::getCreateTime)
                    .last("limit 1"));
            if (ObjectUtils.isNotEmpty(insProductUser)){
            if (ObjectUtils.isNotEmpty(insProductUser)) {
                record.setCheckName(userMapper.selectById(insProductUser.getCreateUser()).getName());
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                record.setCheckTime(insProductUser.getCreateTime().format(formatter));
            }
        }
        map.put("body",productDto2IPage);
        map.put("body", productDto2IPage);
        return map;
    }
@@ -662,7 +540,9 @@
                .filter(dto -> dto.getPrice() != null) // 过滤掉价格为 null 的对象
                .mapToDouble(value -> value.getPrice().doubleValue() * value.getNum())
                .sum();
        map.put("total", totalPrice);
        BigDecimal bd = new BigDecimal(totalPrice).setScale(2, RoundingMode.HALF_UP);
        double roundedTotalPrice = bd.doubleValue();
        map.put("total", roundedTotalPrice);
        return map;
    }
@@ -686,20 +566,27 @@
    public List<SampleProductDto3> labelPrinting(String ids) {
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<SampleProductDto3> sampleProductDtos = insSampleMapper.selectSampleProductListByOrderId3(list);
        Set<String> processedCodes = new HashSet<>();
        //如果是光纤或者是光纤带默认只打印第一个
        List<SampleProductDto3> sampleProductDto3s = sampleProductDtos.stream().filter(sampleProductDto3 -> {
            if (!"光纤".equals(sampleProductDto3.getIoSampleType()) && !"光纤带".equals(sampleProductDto3.getIoSampleType())) {
                return true;
        return sampleProductDtos;
    }
    //校验电机编号
    @Override
    public Map<String, List<InsSample>> checkNumber(String ids) {
        List<InsSample> samples = new ArrayList<>();
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<InsSample> sampleDtos = insSampleMapper.selectInsSample(list);
        //判断样品型号是否是BZ
        for (InsSample sampleDto : sampleDtos) {
            if (sampleDto.getModel().contains("BZ")) {
                if (ObjectUtils.isEmpty(sampleDto.getMotorNumber())) {
                    samples.add(sampleDto);
                }
            }
            if (processedCodes.contains(sampleProductDto3.getCode())) {
                return false;
            } else {
                processedCodes.add(sampleProductDto3.getCode());
                return true;
            }
        }).collect(Collectors.toList());
        return sampleProductDto3s;
        }
        if (CollectionUtils.isNotEmpty(samples)) {
            Map<String, List<InsSample>> collect = samples.stream().collect(Collectors.groupingBy(InsSample::getEntrustCode));
            return collect;
        } else return null;
    }
    @Override
@@ -752,6 +639,14 @@
            throw new RuntimeException("导出失败");
        }
    }
    @Override
    public int addNumber(List<InsSample> insSamples) {
        for (InsSample insSample : insSamples) {
            insSampleMapper.updateById(insSample);
        }
        return 0;
    }
}