fuliqi
2024-11-14 e9af9f5cfeddbe5c0b33a3060b8ea6364c51e744
ycl-server/src/main/java/com/ycl/platform/service/impl/YwThresholdServiceImpl.java
@@ -1,17 +1,34 @@
package com.ycl.platform.service.impl;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson2.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ycl.dataListener.CurrencyDataListener;
import com.ycl.platform.domain.entity.WorkOrder;
import com.ycl.platform.domain.entity.WorkOrderWhite;
import com.ycl.platform.domain.entity.YwPoint;
import com.ycl.platform.domain.entity.YwThreshold;
import com.ycl.platform.domain.excel.ErrorExport;
import com.ycl.platform.domain.excel.PointExport;
import com.ycl.platform.domain.excel.WorkOrderWhiteExport;
import com.ycl.platform.domain.query.WorkOrderWhiteQuery;
import com.ycl.platform.domain.result.HK.FaceDeviceInspectionResult;
import com.ycl.platform.domain.result.HK.VehicleDeviceInspectionResult;
import com.ycl.platform.domain.vo.DynamicColumnVO;
import com.ycl.platform.mapper.WorkOrderWhiteMapper;
import com.ycl.platform.mapper.YwThresholdMapper;
import com.ycl.platform.service.IYwThresholdService;
import com.ycl.platform.service.WorkOrderService;
import com.ycl.system.Result;
import com.ycl.system.page.PageUtil;
import com.ycl.utils.SecurityUtils;
import com.ycl.utils.StringUtils;
import com.ycl.utils.ip.PingUtil;
import com.ycl.utils.poi.EasyExcelImportUtils;
import com.ycl.utils.uuid.IdUtils;
@@ -21,14 +38,20 @@
import enumeration.ErrorType;
import enumeration.general.BusinessTypeEnum;
import enumeration.general.WorkOrderStatusEnum;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import utils.DateUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
@@ -47,6 +70,8 @@
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private WorkOrderWhiteMapper workOrderWhiteMapper;
    /**
     * 查询运维阈值
     *
@@ -151,21 +176,6 @@
        // 清晰度异常检测
        // 亮度异常故障检测
    }
    @Override
    public Result importData(MultipartFile file) {
        List<Map<String, String>> list = EasyExcelImportUtils.makeData(file);
        List<PointExport> dataList = new ArrayList<>();
        for (Map<String, String> map : list) {
            PointExport pointExport = new PointExport();
            pointExport.setPointName(map.get(PointHeaderConstant.Point_Name));
            pointExport.setSerialNumber(map.get(PointHeaderConstant.Serial_Number));
            dataList.add(pointExport);
        }
        workOrderService.batchImportWhite(dataList);
        return Result.ok("导入成功");
    }
    /**
@@ -305,6 +315,264 @@
    }
    /**
     * 白名单详情
     * @param id
     * @return
     */
    @Override
    public Result selectWorkOrderWhiteDetail(Integer id) {
        WorkOrderWhite workOrderWhite = workOrderWhiteMapper.getById(id);
        List<String> errorTypeList = Arrays.asList(workOrderWhite.getErrorType().split(","));
        workOrderWhite.setErrorTypeList(errorTypeList);
        return Result.ok().data(workOrderWhite);
    }
    /**
     * 工单白名单列表
     *
     * @param query 查询
     * @return {@link List }<{@link WorkOrderWhite }>
     * @author
     */
    @Override
    public Result selectWorkOrderWhiteList(WorkOrderWhiteQuery query) {
        IPage<WorkOrderWhite> page = PageUtil.getPage(query, WorkOrderWhite.class);
        workOrderWhiteMapper.page(page, query);
        List<WorkOrderWhite> records = page.getRecords();
        records.forEach(white-> {
            List<String> errorTextList = new ArrayList<>();
            List<String> errorTypeList = Arrays.asList(white.getErrorType().split(","));
            errorTypeList.forEach(error->{
                String errorText = ErrorType.getDescriptionByValue(error);
                errorTextList.add(errorText);
            });
            white.setErrorType(String.join(",", errorTextList));
        });
        return Result.ok().data(records).total(page.getTotal());
    }
    /**
     * 添加工单白名单
     *
     * @param workOrderWhite 白色工单
     * @return {@link Result }
     * @author
     */
    @Override
    public Result addWorkOrderWhite(WorkOrderWhite workOrderWhite) {
        // 检查是否已经存在该白名单
        WorkOrderWhite flag = workOrderWhiteMapper.selectBySerialNumber(workOrderWhite.getSerialNumber());
        if (flag != null) {
            return Result.error("该设备已存在白名单");
        } else {
            List<String> errorTypeList = workOrderWhite.getErrorTypeList();
            workOrderWhite.setErrorType(String.join(",",errorTypeList));
            workOrderWhite.setCreateBy(SecurityUtils.getUsername());
            workOrderWhiteMapper.insert(workOrderWhite);
            return Result.ok();
        }
    }
    /**
     * 修改工单白名单
     *
     * @param workOrderWhite 白色工单
     * @return {@link Result }
     * @author
     */
    @Override
    public Result updateWorkOrderWhite(WorkOrderWhite workOrderWhite) {
        WorkOrderWhite white = workOrderWhiteMapper.selectBySerialNumber(workOrderWhite.getSerialNumber());
        workOrderWhite.setId(white.getId());
        List<String> errorTypeList = workOrderWhite.getErrorTypeList();
        workOrderWhite.setErrorType(String.join(",",errorTypeList));
        workOrderWhiteMapper.updateById(workOrderWhite);
        return Result.ok();
    }
    /**
     * 批量删除工单白名单
     *
     * @param ids ids
     * @author
     */
    @Override
    public Result batchDeleteWorkOrderWhite(List<String> ids) {
        workOrderWhiteMapper.batchDelete(ids);
        return Result.ok();
    }
    /**
     * 白名单导出
     * @param response
     * @throws IOException
     */
    @Override
    public void whiteExport(HttpServletResponse response) throws IOException {
        //白名单数据
        List<WorkOrderWhiteExport> data = workOrderWhiteMapper.whiteExport();
        data.forEach(white-> {
            List<String> errorTextList = new ArrayList<>();
            List<String> errorTypeList = Arrays.asList(white.getErrorType().split(","));
            errorTypeList.forEach(error->{
                String errorText = ErrorType.getDescriptionByValue(error);
                errorTextList.add(errorText);
            });
            white.setErrorType(String.join(",", errorTextList));
        });
        //故障类型数据
        List<String> errorTextList = ErrorType.getDescriptionList();
        List<ErrorExport> errorExports = new ArrayList<>();
        errorTextList.forEach(error -> {
            ErrorExport errorExport = new ErrorExport();
            errorExport.setError(error);
            errorExports.add(errorExport);
        });
        ExcelWriter excelWriter = null;
        try(OutputStream outputStream = response.getOutputStream()) {
            excelWriter = EasyExcel.write(outputStream).build();
            WriteSheet whiteSheet = EasyExcel.writerSheet(0, "工单白名单清单").head(WorkOrderWhiteExport.class).build();
            WriteSheet errorSheet = EasyExcel.writerSheet(1, "故障类型").head(ErrorExport.class).build();
            excelWriter.write(data, whiteSheet);
            excelWriter.write(errorExports, errorSheet);
            excelWriter.finish();
            outputStream.flush();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                excelWriter.finish();
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 导入工单白名单
     * @param file
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result importWhite(MultipartFile file) throws IOException{
//        Consumer<List<WorkOrderWhiteExport>> consumer = (dataList) -> {
//            try {
//                this.updateWhite(dataList);
//            } catch (ExecutionException e) {
//                e.printStackTrace();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        };
//        EasyExcel.read(file.getInputStream(), WorkOrderWhiteExport.class, new CurrencyDataListener(consumer))
//                .sheet()
//                .headRowNumber(1)
//                .doRead();
        List<WorkOrderWhiteExport> dataList = new ArrayList<>();
        EasyExcel.read(file.getInputStream(), WorkOrderWhiteExport.class, new AnalysisEventListener<WorkOrderWhiteExport>() {
            @Override
            public void invoke(WorkOrderWhiteExport excel, AnalysisContext analysisContext) {
                // 将读取到的每一行存入reportDetails集合中
                dataList.add(excel);
            }
            @Override
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
        }).sheet().doRead();
        if (CollectionUtils.isEmpty(dataList)) {
            throw new RuntimeException("导入数据不能为空");
        }
        boolean duplic = checkDuplic(dataList);
        if(duplic) throw new RuntimeException("存在重复国标设备");
        //已存在的白名单
        Map<String, WorkOrderWhite> whiteMap = workOrderWhiteMapper.selectList().stream().collect(Collectors.toMap(WorkOrderWhite::getSerialNumber, Function.identity()));
        List<WorkOrderWhite> addList = new ArrayList<>();
        dataList.stream().forEach(item -> {
            WorkOrderWhite white = new WorkOrderWhite();
            //国标码
            white.setSerialNumber(item.getSerialNumber());
            //备注
            white.setRemark(item.getRemark());
            String errorType = item.getErrorType();
            if(StringUtils.isEmpty(errorType)){
                throw new RuntimeException("国标码为"+item.getSerialNumber()+"的设备故障不能为空");
            }
            try {
                List<String> errorDataList = new ArrayList<>();
                List<String> errorExcelList = Arrays.asList(item.getErrorType().split(","));
                errorExcelList.forEach(desc->{
                    //把中文转换为数据库存储格式
                    String errorText = ErrorType.getValueByDescription(desc);
                    //找不到抛出异常
                    if(errorText == null) throw new RuntimeException("国标码为"+item.getSerialNumber()+"的设备故障类型有误");
                    errorDataList.add(errorText);
                });
                white.setErrorType(String.join(",", errorDataList));
                //如果已存在补充id
                WorkOrderWhite whiteExsit = whiteMap.get(white.getSerialNumber());
                if(whiteExsit!=null) white.setId(whiteExsit.getId());
                addList.add(white);
            } catch (Exception e) {
                throw new RuntimeException("国标码为"+item.getSerialNumber()+"的设备故障类型有误");
            }
        });
        if(!CollectionUtils.isEmpty(addList)) {
            workOrderWhiteMapper.deleteAll();
            workOrderWhiteMapper.insertBatch(addList);
        }
        return Result.ok();
    }
    /**
     * 修改白名单
     *
     * @param dataList
     * @param unitId
     */
    public void updateWhite(List<WorkOrderWhiteExport> dataList) throws ExecutionException, InterruptedException {
        if (CollectionUtils.isEmpty(dataList)) {
            throw new RuntimeException("导入数据不能为空");
        }
        //已存在的白名单
        List<String> serialNumbers = workOrderWhiteMapper.selectList().stream().map(WorkOrderWhite::getSerialNumber).collect(Collectors.toList());
        List<WorkOrderWhite> addList = new ArrayList<>();
        List<WorkOrderWhite> updateList = new ArrayList<>();
        dataList.stream().forEach(item -> {
            WorkOrderWhite white = new WorkOrderWhite();
            //国标码
            white.setSerialNumber(item.getSerialNumber());
            //备注
            white.setRemark(item.getRemark());
            String errorType = item.getErrorType();
            if(StringUtils.isEmpty(errorType)){
                throw new RuntimeException("国标码为"+item.getSerialNumber()+"的设备故障不能为空");
            }
            try {
                List<String> errorDataList = new ArrayList<>();
                List<String> errorExcelList = Arrays.asList(item.getErrorType().split(","));
                errorExcelList.forEach(desc->{
                    //把中文转换为数据库存储格式
                    String errorText = ErrorType.getValueByDescription(desc);
                    //找不到抛出异常
                    if(errorText == null) throw new RuntimeException("国标码为"+item.getSerialNumber()+"的设备故障类型有误");
                    errorDataList.add(errorText);
                });
                white.setErrorType(String.join(",", errorDataList));
                if(!CollectionUtils.isEmpty(serialNumbers) && serialNumbers.contains(white.getSerialNumber())){
                    updateList.add(white);
                }else {
                    addList.add(white);
                }
            } catch (Exception e) {
                throw new RuntimeException("国标码为"+item.getSerialNumber()+"的设备故障类型有误");
            }
        });
        if(!CollectionUtils.isEmpty(addList)) workOrderWhiteMapper.insertBatch(addList);
        if(!CollectionUtils.isEmpty(updateList)) workOrderWhiteMapper.updateBatch(updateList);
    }
    /**
     * 检查阈值
     *
     * @param key 某阈值标识
@@ -324,6 +592,14 @@
                    T thresholdAutoValue = parseThreshold(ywThreshold.getValueAuto(), value.getClass());
                    //直接下发工单阈值
                    T thresholdValue = parseThreshold(ywThreshold.getValue(), value.getClass());
                    if("percent".equals(ywThreshold.getCountType())){
                        if (thresholdAutoValue instanceof Float) {
                            thresholdAutoValue = (T) Float.valueOf(((Float) thresholdAutoValue) / 100f);
                        }
                        if (thresholdValue instanceof Float) {
                            thresholdValue = (T) Float.valueOf(((Float) thresholdValue) / 100f);
                        }
                    }
                    //比较大小,加入到对应待处理集合
                    if (compareType.compare(v, thresholdValue)) {
                        //进入工单直接下发
@@ -365,4 +641,15 @@
        }
    }
    public static boolean checkDuplic(List<WorkOrderWhiteExport> dataList) {
        Set<String> serialNumbers = new HashSet<>();
        for (WorkOrderWhiteExport white : dataList) {
            String serialNumber = white.getSerialNumber();
            if (!serialNumbers.add(serialNumber)) {
                return true;
            }
        }
        return false;
    }
}