cnas-device/src/main/java/com/ruoyi/device/service/impl/DeviceMaintenanceImpl.java
@@ -1,42 +1,38 @@
package com.ruoyi.device.service.impl;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.device.dto.DeviceImpowerDetailsDto;
import com.ruoyi.device.dto.DeviceImpowerDto;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.device.dto.DeviceMaintenanceDto;
import com.ruoyi.device.mapper.DeviceMaintenanceMapper;
import com.ruoyi.device.mapper.DeviceMapper;
import com.ruoyi.device.pojo.Device;
import com.ruoyi.device.pojo.DeviceImpower;
import com.ruoyi.device.pojo.DeviceMaintenance;
import com.ruoyi.device.pojo.DeviceMaintenancePlanDetails;
import com.ruoyi.device.service.DeviceMaintenancePlanService;
import com.ruoyi.device.service.DeviceMaintenanceService;
import com.ruoyi.device.service.DeviceService;
import com.ruoyi.framework.exception.ErrorException;
import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
import com.ruoyi.inspect.util.UserUtils;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.AllArgsConstructor;
import com.ruoyi.system.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.format.DateTimeFormatter;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -45,14 +41,14 @@
 * 设备维护保养
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceMaintenanceImpl extends ServiceImpl<DeviceMaintenanceMapper, DeviceMaintenance> implements DeviceMaintenanceService {
    @Resource
    private DeviceService deviceService;
    @Resource
    private ISysDictTypeService iSysDictTypeService;
    @Value("${file.path}")
    private String imgUrl;
    private DeviceMaintenancePlanService deviceMaintenancePlanService;
    @Resource
    private UserMapper userMapper;
    /**
     * 设备维护分页查询
@@ -67,52 +63,160 @@
    }
    /**
     * 导出设备维护保养
     * 保存保养记录(关联保养计划明细,保存后进入待审核,不滚动设备档案日期)
     */
    @Override
    public boolean saveDeviceMaintenance(DeviceMaintenance deviceMaintenance) {
        if (deviceMaintenance == null) {
            throw new ErrorException("缺少保养记录");
        }
        if (deviceMaintenance.getDeviceId() == null) {
            throw new ErrorException("缺少设备id");
        }
        if (deviceMaintenance.getMaintenanceDate() == null) {
            throw new ErrorException("请选择保养日期");
        }
        if (deviceMaintenance.getMaintenanceUserId() == null) {
            throw new ErrorException("请选择维护人");
        }
        DeviceMaintenance exist = deviceMaintenance.getId() == null ? null : baseMapper.selectById(deviceMaintenance.getId());
        if (exist != null) {
            if (exist.getMaintenancePlanDetailId() == null) {
                throw new ErrorException("历史保养记录不允许修改");
            }
            if (exist.getReviewStatus() != null) {
                throw new ErrorException("已审核的保养记录不允许修改");
            }
            // 记录归属由库里的关联决定,避免改到别的设备或计划
            deviceMaintenance.setDeviceId(exist.getDeviceId());
            deviceMaintenance.setMaintenancePlanDetailId(exist.getMaintenancePlanDetailId());
            deviceMaintenance.setReviewStatus(null);
        } else {
            DeviceMaintenancePlanDetails detail = deviceMaintenancePlanService.resolveMaintenancePlanDetail(
                    deviceMaintenance.getDeviceId(), deviceMaintenance.getMaintenancePlanDetailId(), deviceMaintenance.getMaintenanceDate());
            if (!deviceMaintenance.getDeviceId().equals(detail.getDeviceId())) {
                throw new ErrorException("保养计划明细与设备不匹配");
            }
            DeviceMaintenance other = baseMapper.selectOne(Wrappers.<DeviceMaintenance>lambdaQuery()
                    .eq(DeviceMaintenance::getMaintenancePlanDetailId, detail.getMaintenancePlanDetailId())
                    .last("limit 1"));
            if (other != null) {
                throw new ErrorException("该计划已存在保养记录");
            }
            deviceMaintenance.setMaintenancePlanDetailId(detail.getMaintenancePlanDetailId());
            deviceMaintenance.setReviewStatus(null);
            deviceMaintenance.setReviewUserId(null);
            deviceMaintenance.setReviewUserName(null);
            deviceMaintenance.setReviewRemark(null);
            deviceMaintenance.setReviewTime(null);
        }
        User user = userMapper.selectById(deviceMaintenance.getMaintenanceUserId());
        deviceMaintenance.setMaintenanceUserName(user == null ? null : user.getName());
        return saveOrUpdate(deviceMaintenance);
    }
    /**
     * 审核保养记录;审核通过后按审核通过当天滚动设备档案的最近/下次保养日期(与核查计划一致)
     */
    @Override
    public boolean reviewDeviceMaintenance(DeviceMaintenanceDto deviceMaintenanceDto) {
        DeviceMaintenance record = findMaintenanceRecord(deviceMaintenanceDto);
        if (record == null) {
            throw new ErrorException("该计划暂无保养记录,请先填写保养记录");
        }
        if (record.getMaintenancePlanDetailId() == null) {
            throw new ErrorException("历史保养记录无需审核");
        }
        if (deviceMaintenanceDto.getReviewStatus() == null) {
            throw new ErrorException("请选择审核结果");
        }
        if (record.getReviewStatus() != null && record.getReviewStatus() == 1) {
            throw new ErrorException("该保养记录已审核通过");
        }
        if (record.getMaintenanceUserId() == null && StringUtils.isBlank(record.getMaintenanceUserName())) {
            throw new ErrorException("请先在编辑中填写维护人");
        }
        Integer reviewerId = SecurityUtils.getUserId().intValue();
        User reviewer = userMapper.selectById(reviewerId);
        boolean updated = this.update(Wrappers.<DeviceMaintenance>lambdaUpdate()
                .eq(DeviceMaintenance::getId, record.getId())
                .set(DeviceMaintenance::getReviewStatus, deviceMaintenanceDto.getReviewStatus())
                .set(DeviceMaintenance::getReviewUserId, reviewerId)
                .set(DeviceMaintenance::getReviewUserName, reviewer == null ? null : reviewer.getName())
                .set(DeviceMaintenance::getReviewRemark, deviceMaintenanceDto.getReviewRemark())
                .set(DeviceMaintenance::getReviewTime, LocalDateTime.now()));
        // 审核通过后,按审核通过当天回写档案的最近保养日期并推算下一轮(与核查计划一致)
        if (updated && deviceMaintenanceDto.getReviewStatus() == 1) {
            LocalDate reviewDate = LocalDate.now();
            // 审核完成年份即归类年份:提前完成的明细从原计划年份挪到审核年份
            deviceMaintenancePlanService.reclassifyMaintenanceDetailByReviewDate(record.getMaintenancePlanDetailId(), reviewDate);
            deviceMaintenancePlanService.updateDeviceMaintenanceDate(record.getDeviceId(), reviewDate);
        }
        return updated;
    }
    /**
     * 删除保养记录;审核通过和历史记录不允许删除
     */
    @Override
    public boolean deleteDeviceMaintenance(Integer id) {
        DeviceMaintenance record = id == null ? null : baseMapper.selectById(id);
        if (record == null) {
            return false;
        }
        if (record.getMaintenancePlanDetailId() == null) {
            throw new ErrorException("历史保养记录为留档内容,不允许删除");
        }
        if (record.getReviewStatus() != null && record.getReviewStatus() == 1) {
            throw new ErrorException("审核通过的保养记录为历史记录,不允许删除");
        }
        return removeById(id);
    }
    /**
     * 按记录id或计划明细id定位保养记录
     */
    private DeviceMaintenance findMaintenanceRecord(DeviceMaintenanceDto dto) {
        if (dto == null) {
            return null;
        }
        if (dto.getId() != null) {
            return baseMapper.selectById(dto.getId());
        }
        if (dto.getMaintenancePlanDetailId() != null) {
            return baseMapper.selectOne(Wrappers.<DeviceMaintenance>lambdaQuery()
                    .eq(DeviceMaintenance::getMaintenancePlanDetailId, dto.getMaintenancePlanDetailId())
                    .last("limit 1"));
        }
        return null;
    }
    /**
     * 导出仪器设备维护保养记录(只读台账,数据来自保养计划生成的保养记录)
     * @param deviceId
     * @param response
     */
    @Override
    public void exportDeviceMaintenance(Integer deviceId, HttpServletResponse response) {
        // 查询设备维护保养
        List<DeviceMaintenance> deviceMaintenanceList = baseMapper.selectList(Wrappers.<DeviceMaintenance>lambdaQuery()
                .eq(DeviceMaintenance::getDeviceId, deviceId));
        // 获取到第一个设备使用授权
        DeviceMaintenanceDto deviceMaintenanceDto = new DeviceMaintenanceDto();
        List<SysDictData> sysDictDataList = null;
        if (CollectionUtils.isNotEmpty(deviceMaintenanceList)) {
            BeanUtils.copyProperties(deviceMaintenanceList.get(0), deviceMaintenanceDto);
            // 查询设备信息
            Device device = deviceService.getById(deviceId);
            deviceMaintenanceDto.setDeviceName(device.getDeviceName());
            deviceMaintenanceDto.setManagementNumber(device.getManagementNumber());
            //查询维护保养导出字典值
            sysDictDataList = getDeviceMaintenanceDict(device);
        Device device = deviceId == null ? null : deviceService.getById(deviceId);
        if (device == null) {
            throw new ErrorException("设备不存在");
        }
        // 添加字典枚举值
        for (DeviceMaintenance deviceMaintenance : deviceMaintenanceList) {
            StringBuilder maintenanceContent = new StringBuilder(deviceMaintenance.getMaintenanceContent());
            if (CollectionUtils.isNotEmpty(sysDictDataList) && StringUtils.isNotBlank(deviceMaintenance.getMaintenanceContent())) {
                maintenanceContent = new StringBuilder();
                List<String> splitList = StrUtil.split(deviceMaintenance.getMaintenanceContent(), ',');
                // 循环判断是否有一样key
                for (SysDictData sysDictData : sysDictDataList) {
                    if (splitList.contains(sysDictData.getDictLabel())) {
                        maintenanceContent.append("☑").append(sysDictData.getDictLabel()).append(" ");
                    } else {
                        maintenanceContent.append("□").append(sysDictData.getDictLabel()).append(" ");
        // 台账按维护日期正序排列
        List<DeviceMaintenance> records = baseMapper.selectList(Wrappers.<DeviceMaintenance>lambdaQuery()
                .eq(DeviceMaintenance::getDeviceId, deviceId)
                .orderByAsc(DeviceMaintenance::getMaintenanceDate)
                .orderByAsc(DeviceMaintenance::getId));
        List<DeviceMaintenanceDto> deviceMaintenances = new ArrayList<>();
        int index = 1;
        for (DeviceMaintenance record : records) {
            DeviceMaintenanceDto dto = new DeviceMaintenanceDto();
            BeanUtils.copyProperties(record, dto);
            dto.setIndex(index++);
            // 维护人列展示签名图片,未配置签名时用透明图片兜底
            dto.setMaintenanceUserUrlRender(UserUtils.getFinalUserSignatureOrTransparent(record.getMaintenanceUserId()));
            deviceMaintenances.add(dto);
                    }
                }
            }
            deviceMaintenance.setMaintenanceContent(maintenanceContent.toString());
            // 添加维护人图片
            deviceMaintenance.setMaintenanceUserUrlRender(UserUtils.getFinalUserSignatureOrTransparent(deviceMaintenance.getMaintenanceUserId()));
        }
        // 获取路径
        InputStream inputStream = this.getClass().getResourceAsStream("/static/word/device-maintenance.docx");
@@ -121,14 +225,17 @@
                .build();
        XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
                new HashMap<String, Object>() {{
                    put("device", deviceMaintenanceDto);
                    put("deviceMaintenances", deviceMaintenanceList);
                    put("deviceName", device.getDeviceName());
                    put("specificationModel", device.getSpecificationModel());
                    put("managementNumber", device.getManagementNumber());
                    put("cycleNote", buildCycleNote(device.getMaintenanceCycle()));
                    put("deviceMaintenances", deviceMaintenances);
                }});
        try {
            response.setContentType("application/msword");
            String fileName = URLEncoder.encode(
                    "设备保养维护", "UTF-8");
                    "仪器设备维护保养记录", "UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName + ".docx");
            OutputStream os = response.getOutputStream();
@@ -144,54 +251,36 @@
    }
    /**
     * ****查询维护保养导出字典值***
     * @param device
     * 表格底部的维护保养频率说明,按档案里的保养周期(月)生成
     */
    private List<SysDictData> getDeviceMaintenanceDict(Device device) {
        List<SysDictData> sysDictDataList = new ArrayList<>();
        // 查询维护保养导出字典值
        if (StringUtils.isNotBlank(device.getStoragePoint())) {
            String dictType = null;
            switch (device.getStoragePoint()) {
                case "老化室":
                    dictType = "aging_maintenance_content";
                    break;
                case "老化实验室":
                    dictType = "aging_maintenance_content";
                    break;
                case "电性能实验室":
                    dictType = "electrical_maintenance_content";
                    break;
                case "环境实验室":
                    dictType = "environmental_maintenance_content";
                    break;
                case "燃烧实验室":
                    dictType = "burn_maintenance_content";
                    break;
                case "混炼实验室":
                    dictType = "mixing_maintenance_content";
                    break;
                case "检测中心电性能实验室":
                    dictType = "center_electrical_maintenance_content";
                    break;
                case "恒温二":
                    dictType = "temperature2_maintenance_content";
                    break;
                case "恒温一":
                    dictType = "temperature1_maintenance_content";
                    break;
                case "化学实验室":
                    dictType = "chemistry_maintenance_content";
                    break;
                case "制样室":
                    dictType = "sample_maintenance_content";
                    break;
                case "低温实验室":
                    dictType = "hypothermia_maintenance_content";
                    break;
    private String buildCycleNote(String maintenanceCycle) {
        if (StringUtils.isBlank(maintenanceCycle)) {
            return "";
            }
            sysDictDataList = iSysDictTypeService.selectDictDataByType(dictType);
        int months;
        try {
            months = Integer.parseInt(maintenanceCycle.trim());
        } catch (NumberFormatException e) {
            return "";
        }
        return sysDictDataList;
        if (months <= 0) {
            return "";
        }
        if (months == 1) {
            return "维护保养每月 1 次";
        }
        if (months == 3) {
            return "维护保养每季度 1 次";
        }
        if (months == 6) {
            return "维护保养每半年 1 次";
        }
        if (months == 12) {
            return "维护保养每年 1 次";
        }
        if (months % 12 == 0) {
            return "维护保养每 " + months / 12 + " 年 1 次";
        }
        return "维护保养每 " + months + " 个月 1 次";
    }
}