吴羡
7 小时以前 2f07589b54d56085af77b50d580890cd4130b444
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
package com.ruoyi.device.service.impl;
 
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
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.ruoyi.common.constant.MenuJumpPathConstants;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.common.core.domain.entity.InformationNotification;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.utils.QueryWrappers;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.WxCpUtils;
import com.ruoyi.device.dto.DeviceMaintenancePlanDetailsDto;
import com.ruoyi.device.dto.DeviceMaintenancePlanDto;
import com.ruoyi.device.mapper.DeviceMaintenancePlanDetailsMapper;
import com.ruoyi.device.mapper.DeviceMaintenancePlanMapper;
import com.ruoyi.device.mapper.DeviceMapper;
import com.ruoyi.device.pojo.Device;
import com.ruoyi.device.pojo.DeviceMaintenancePlan;
import com.ruoyi.device.pojo.DeviceMaintenancePlanDetails;
import com.ruoyi.device.service.DeviceMaintenancePlanDetailsService;
import com.ruoyi.device.service.DeviceMaintenancePlanService;
import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
import com.ruoyi.inspect.util.UserUtils;
import com.ruoyi.system.mapper.UserMapper;
import com.ruoyi.system.service.InformationNotificationService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
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.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
 
/**
 * <p>
 * 设备保养计划表 服务实现类
 * </p>
 *
 * @author 江苏鵷雏网络科技有限公司
 * @since 2024-12-16 06:10:52
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DeviceMaintenancePlanServiceImpl extends ServiceImpl<DeviceMaintenancePlanMapper, DeviceMaintenancePlan> implements DeviceMaintenancePlanService {
 
    @Resource
    private DeviceMaintenancePlanDetailsService deviceMaintenancePlanDetailsService;
    @Resource
    private DeviceMaintenancePlanDetailsMapper deviceMaintenancePlanDetailsMapper;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private InformationNotificationService informationNotificationService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DeviceMapper deviceMapper;
 
    /**
     * 分页查询设备保养计划
     *
     * @param page
     * @return
     */
    @Override
    public Result<IPage<DeviceMaintenancePlan>> selectDeviceMaintenancePlanByPage(Page page, DeviceMaintenancePlanDto deviceMaintenancePlanDto) {
        IPage<DeviceMaintenancePlan> iPage = baseMapper.selectDeviceParameterPage(page, QueryWrappers.queryWrappers(deviceMaintenancePlanDto));
        return Result.success(iPage);
    }
 
    /**
     * 新增设备保养计划
     *
     * @param deviceMaintenancePlanDto 设备保养计划
     */
    @Override
    public Result addMaintenancePlan(DeviceMaintenancePlanDto deviceMaintenancePlanDto) {
        Integer userId = SecurityUtils.getUserId().intValue();
        User user = userMapper.selectById(userId);
        deviceMaintenancePlanDto.setCompilerId(userId);
        deviceMaintenancePlanDto.setCompiler(user.getName());
        deviceMaintenancePlanDto.setDatePreparation(LocalDateTime.now());
 
        // 查询审核人id
        if (deviceMaintenancePlanDto.getAuditId() != null) {
            User auditUser = userMapper.selectById(deviceMaintenancePlanDto.getAuditId());
            deviceMaintenancePlanDto.setAudit(auditUser.getName());
        }
        this.saveOrUpdate(deviceMaintenancePlanDto);
 
        // 详情赋值并保存
        List<DeviceMaintenancePlanDetailsDto> deviceMaintenancePlanDetails = deviceMaintenancePlanDto.getDeviceMaintenancePlanDetails();
        if (CollectionUtils.isNotEmpty(deviceMaintenancePlanDetails)) { // 详情不为空
            List<DeviceMaintenancePlanDetails> collect = deviceMaintenancePlanDetails.stream().map(deviceMaintenancePlanDetail -> { // 遍历详情
                deviceMaintenancePlanDetail.setDeviceId(deviceMaintenancePlanDetail.getDeviceId()); // 设备ID
                deviceMaintenancePlanDetail.setMaintenancePlanId(deviceMaintenancePlanDto.getMaintenancePlanId()); // 保养计划ID
                DeviceMaintenancePlanDetails planDetails = new DeviceMaintenancePlanDetails();
                BeanUtils.copyProperties(deviceMaintenancePlanDetail, planDetails);
                return planDetails;
            }).collect(Collectors.toList());
            deviceMaintenancePlanDetailsService.saveBatch(collect);
        }
 
        return Result.success();
    }
 
    /**
     * 修改设备保养计划
     * @param deviceMaintenancePlanDto 设备保养计划
     */
    @Override
    public Result updateMaintenancePlan(DeviceMaintenancePlanDto deviceMaintenancePlanDto) {
        // 查询审核人id
        if (deviceMaintenancePlanDto.getAuditId() != null) {
            User auditUser = userMapper.selectById(deviceMaintenancePlanDto.getAuditId());
            deviceMaintenancePlanDto.setAudit(auditUser.getName());
        }
        this.saveOrUpdate(deviceMaintenancePlanDto);
 
        // 删除原本的详情
        deviceMaintenancePlanDetailsService.remove(Wrappers.<DeviceMaintenancePlanDetails>lambdaQuery().eq(DeviceMaintenancePlanDetails::getMaintenancePlanId, deviceMaintenancePlanDto.getMaintenancePlanId()));
        // 详情赋值并保存
        List<DeviceMaintenancePlanDetailsDto> deviceMaintenancePlanDetails = deviceMaintenancePlanDto.getDeviceMaintenancePlanDetails();
        if (CollectionUtils.isNotEmpty(deviceMaintenancePlanDetails)) { // 详情不为空
            List<DeviceMaintenancePlanDetails> collect = deviceMaintenancePlanDetails.stream().map(deviceMaintenancePlanDetail -> { // 遍历详情
                deviceMaintenancePlanDetail.setDeviceId(deviceMaintenancePlanDto.getDeviceId()); // 设备ID
                deviceMaintenancePlanDetail.setMaintenancePlanId(deviceMaintenancePlanDto.getMaintenancePlanId()); // 保养计划ID
                DeviceMaintenancePlanDetails planDetails = new DeviceMaintenancePlanDetails();
                BeanUtils.copyProperties(deviceMaintenancePlanDetail, planDetails);
                return planDetails;
            }).collect(Collectors.toList());
            deviceMaintenancePlanDetailsService.saveBatch(collect);
        }
        return Result.success();
    }
 
    /**
     * 删除设备保养计划
     *
     * @param deviceMaintenancePlanDto 设备保养计划
     */
    @Override
    public Result deleteMaintenancePlan(DeviceMaintenancePlanDto deviceMaintenancePlanDto) {
        this.removeById(deviceMaintenancePlanDto);
        deviceMaintenancePlanDetailsService.remove(Wrappers.<DeviceMaintenancePlanDetails>lambdaQuery().eq(DeviceMaintenancePlanDetails::getMaintenancePlanId, deviceMaintenancePlanDto.getMaintenancePlanId()));
        return Result.success();
    }
 
    /**
     * 导出设备保养计划
     *
     * @param maintenancePlanId 设备保养计划id
     * @param response          响应
     */
    @Override
    public Result exportDeviceMaintenancePlanDto(Integer maintenancePlanId, HttpServletResponse response) {
        // 查询设备保养计划
        DeviceMaintenancePlanDto deviceMaintenancePlan = baseMapper.selectMaintenancePlanById(maintenancePlanId);
 
        // 查询设备保养计划详情
        List<DeviceMaintenancePlanDetailsDto> deviceMaintenancePlanDetailsDtoList = deviceMaintenancePlanDetailsMapper.deviceInspectionRecordDetailsList(maintenancePlanId);
        // 设置序号
        deviceMaintenancePlanDetailsDtoList.forEach(deviceInspectionRecordDetails -> {
            deviceInspectionRecordDetails.setIndex(deviceMaintenancePlanDetailsDtoList.indexOf(deviceInspectionRecordDetails) + 1);
        });
 
        // 获取路径
        InputStream inputStream = this.getClass().getResourceAsStream("/static/word/maintenance-plan.docx");
        Configure configure = Configure.builder()
                .bind("deviceMaintenancePlanDetailsDtoList", new HackLoopTableRenderPolicy())
                .build();
        XWPFTemplate template = XWPFTemplate.compile(inputStream, configure).render(
                new HashMap<String, Object>() {{
                    put("deviceMaintenancePlan", deviceMaintenancePlan);
                    put("deviceMaintenancePlanDetailsDtoList", deviceMaintenancePlanDetailsDtoList);
                    // 编制人签名地址
                    put("compilerUrl", UserUtils.getFinalUserSignatureOrTransparent(deviceMaintenancePlan.getCompilerId()));
                    // 审核人签名地址
                    put("auditUrl", UserUtils.getFinalUserSignatureOrTransparent(deviceMaintenancePlan.getAuditId()));
                }});
 
        try {
            response.setContentType("application/msword");
            String fileName = URLEncoder.encode(
                    "设备保养计划表", "UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + fileName + ".docx");
            OutputStream os = response.getOutputStream();
            template.write(os);
            os.flush();
            os.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败");
        }
        return Result.success();
    }
 
    /**
     * 查询设备保养计划详情
     *
     * @param maintenancePlanId 设备保养计划id
     */
    @Override
    public Result<DeviceMaintenancePlanDto> getMaintenancePlanDetail(Integer maintenancePlanId) {
        // 查询设备保养计划
        DeviceMaintenancePlan deviceMaintenancePlan = baseMapper.selectById(maintenancePlanId);
        // 查询详情
        DeviceMaintenancePlanDto deviceMaintenancePlanDto = new DeviceMaintenancePlanDto();
        BeanUtils.copyProperties(deviceMaintenancePlan, deviceMaintenancePlanDto);
        deviceMaintenancePlanDto.setDeviceMaintenancePlanDetails(deviceMaintenancePlanDetailsMapper.deviceInspectionRecordDetailsList(maintenancePlanId));
        return Result.success(deviceMaintenancePlanDto);
    }
 
    /**
     * 提交审核
     * @param deviceMaintenancePlanDto
     * @return
     */
    @Override
    public Result submitReviewMaintenancePlanStatus(DeviceMaintenancePlanDto deviceMaintenancePlanDto) {
        User audit = userMapper.selectById(deviceMaintenancePlanDto.getAuditId());
        this.update(Wrappers.<DeviceMaintenancePlan>lambdaUpdate()
                .eq(DeviceMaintenancePlan::getMaintenancePlanId, deviceMaintenancePlanDto.getMaintenancePlanId())
                .set(DeviceMaintenancePlan::getAuditId, audit.getId())
                .set(DeviceMaintenancePlan::getAudit, audit.getName())
                .set(DeviceMaintenancePlan::getStatus, null)
                .set(DeviceMaintenancePlan::getAuditRemark, null)
                .set(DeviceMaintenancePlan::getAuditDate, null)
        );
 
        DeviceMaintenancePlan deviceMaintenancePlan = baseMapper.selectById(deviceMaintenancePlanDto.getMaintenancePlanId());
 
        // 发送消息
        Integer userId = SecurityUtils.getUserId().intValue();
        User user = userMapper.selectById(userId);
        // 消息发送
        InformationNotification info = new InformationNotification();
        // 发送人
        info.setCreateUser(user.getName());
        info.setMessageType("6");
        info.setTheme("CNAS设备保养计划审核通知");
        info.setContent(deviceMaintenancePlan.getPlanYear() + "年的设备保养计划待审核");
        info.setSenderId(userId);
        // 接收人
        info.setConsigneeId(audit.getId());
        info.setJumpPath(MenuJumpPathConstants.DEVICE);
        informationNotificationService.addInformationNotification(info);
 
        // 发送企业微信通知
        threadPoolTaskExecutor.execute(() -> {
            String message = "";
            message += "CNAS设备保养计划核通知";
            message += "\n请去资源管理-设备一层目录-设备保养计划填写";
            message += "\n" + deviceMaintenancePlan.getPlanYear() + "年的设备保养计划待核";
            //发送企业微信消息通知
            try {
                WxCpUtils.inform(audit.getAccount(), message, null);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        return Result.success();
    }
 
    /**
     * 审核设备保养计划
     *
     * @param deviceMaintenancePlanDto 设备保养计划
     */
    @Override
    public Result reviewMaintenancePlanStatus(DeviceMaintenancePlanDto deviceMaintenancePlanDto) {
        LambdaUpdateWrapper<DeviceMaintenancePlan> wrapper = Wrappers.<DeviceMaintenancePlan>lambdaUpdate()
                .eq(DeviceMaintenancePlan::getMaintenancePlanId, deviceMaintenancePlanDto.getMaintenancePlanId())
                .set(DeviceMaintenancePlan::getStatus, deviceMaintenancePlanDto.getStatus())
                .set(DeviceMaintenancePlan::getAuditRemark, deviceMaintenancePlanDto.getAuditRemark())
                .set(DeviceMaintenancePlan::getAuditDate, LocalDateTime.now());
 
        this.update(wrapper); // 更新
        return Result.success();
    }
 
    /**
     * 按年份查询设备保养计划(不存在则自动创建),并自动补全已到点的设备明细
     */
    @Override
    public DeviceMaintenancePlanDto getOrCreatePlanByYear(String planYear) {
        if (StringUtils.isBlank(planYear)) {
            planYear = String.valueOf(LocalDate.now().getYear());
        }
        DeviceMaintenancePlan plan = getOrCreatePlanEntity(planYear);
        ensureMaintenanceDetails(plan);
        DeviceMaintenancePlanDto planDto = new DeviceMaintenancePlanDto();
        BeanUtils.copyProperties(plan, planDto);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        planDto.setDatePreparationStr(plan.getDatePreparation() == null ? null : plan.getDatePreparation().format(formatter));
        planDto.setAuditDateStr(plan.getAuditDate() == null ? null : plan.getAuditDate().format(formatter));
        if (StringUtils.isBlank(planDto.getCompiler()) && plan.getCompilerId() != null) {
            User compiler = userMapper.selectById(plan.getCompilerId());
            if (compiler != null) {
                planDto.setCompiler(compiler.getName());
            }
        }
        if (StringUtils.isBlank(planDto.getAudit()) && plan.getAuditId() != null) {
            User audit = userMapper.selectById(plan.getAuditId());
            if (audit != null) {
                planDto.setAudit(audit.getName());
            }
        }
        return planDto;
    }
 
    /**
     * 设备档案变更后,把已到点的设备同步到对应年份的设备保养计划明细
     */
    @Override
    public void syncDeviceMaintenanceDetail(Device device) {
        LocalDate remind = calcMaintenanceRemindDate(device);
        if (remind == null || remind.isAfter(LocalDate.now())) {
            return;
        }
        DeviceMaintenancePlan plan = getOrCreatePlanEntity(String.valueOf(remind.getYear()));
        fillMaintenanceDetailIfAbsent(plan, device);
    }
 
    /**
     * 保养记录保存后,滚动设备档案的最近/下次保养日期
     */
    @Override
    public void updateDeviceMaintenanceDate(Integer deviceId, LocalDate maintenanceDate) {
        if (deviceId == null || maintenanceDate == null) {
            return;
        }
        Device device = deviceMapper.selectById(deviceId);
        if (device == null) {
            return;
        }
        LocalDateTime recordDate = maintenanceDate.atStartOfDay();
        // 只允许向前滚动,避免补录旧记录时把日期改回去
        if (device.getLastMaintenanceDate() != null && !recordDate.isAfter(device.getLastMaintenanceDate())) {
            return;
        }
        device.setLastMaintenanceDate(recordDate);
        if (StringUtils.isNotBlank(device.getMaintenanceCycle())) {
            try {
                device.setNextMaintenanceDate(recordDate.plusMonths(Long.parseLong(device.getMaintenanceCycle().trim())));
            } catch (NumberFormatException ignored) {
            }
        }
        deviceMapper.updateById(device);
    }
 
    /**
     * 分页查询设备保养计划详情(含到点标红)
     */
    @Override
    public IPage<DeviceMaintenancePlanDetailsDto> pageMaintenancePlanDetail(Page page, Integer planId, String deviceName, String deviceNumber) {
        if (planId == null) {
            return new Page<>();
        }
        return deviceMaintenancePlanDetailsMapper.pageMaintenancePlanDetail(page, planId, deviceName, deviceNumber);
    }
 
    /**
     * 查询年份对应的计划,不存在则创建
     */
    private DeviceMaintenancePlan getOrCreatePlanEntity(String planYear) {
        DeviceMaintenancePlan plan = baseMapper.selectOne(Wrappers.<DeviceMaintenancePlan>lambdaQuery()
                .eq(DeviceMaintenancePlan::getPlanYear, planYear)
                .orderByDesc(DeviceMaintenancePlan::getMaintenancePlanId)
                .last("limit 1"));
        if (plan == null) {
            plan = new DeviceMaintenancePlan();
            plan.setPlanName(planYear + "年度设备保养计划");
            plan.setPlanYear(planYear);
            Integer userId = SecurityUtils.getUserId().intValue();
            User user = userMapper.selectById(userId);
            plan.setCompilerId(userId);
            plan.setCompiler(user == null ? null : user.getName());
            plan.setDatePreparation(LocalDateTime.now());
            baseMapper.insert(plan);
        }
        return plan;
    }
 
    /**
     * 扫描所有设备,把已到点(下次保养日期前1个月起,含已过期)的设备补进本年度计划
     */
    private void ensureMaintenanceDetails(DeviceMaintenancePlan plan) {
        List<Device> devices = deviceMapper.selectList(null);
        for (Device device : devices) {
            fillMaintenanceDetailIfAbsent(plan, device);
        }
    }
 
    /**
     * 设备提醒起点:下次保养日期前1个月(没填下次日期时用最近日期+保养周期兜底)
     */
    private LocalDate calcMaintenanceRemindDate(Device device) {
        LocalDateTime base = device.getNextMaintenanceDate();
        if (base == null && device.getLastMaintenanceDate() != null && StringUtils.isNotBlank(device.getMaintenanceCycle())) {
            try {
                base = device.getLastMaintenanceDate().plusMonths(Long.parseLong(device.getMaintenanceCycle().trim()));
            } catch (NumberFormatException ignored) {
            }
        }
        return base == null ? null : base.toLocalDate().minusMonths(1);
    }
 
    /**
     * 已到点且计划中尚无该设备本轮明细时自动补一条
     */
    private void fillMaintenanceDetailIfAbsent(DeviceMaintenancePlan plan, Device device) {
        LocalDate remind = calcMaintenanceRemindDate(device);
        if (remind == null || remind.isAfter(LocalDate.now())) {
            return;
        }
        if (plan.getPlanYear() != null && String.valueOf(remind.getYear()).compareTo(plan.getPlanYear()) > 0) {
            return;
        }
        Long exist = deviceMaintenancePlanDetailsMapper.selectCount(Wrappers.<DeviceMaintenancePlanDetails>lambdaQuery()
                .eq(DeviceMaintenancePlanDetails::getMaintenancePlanId, plan.getMaintenancePlanId())
                .eq(DeviceMaintenancePlanDetails::getDeviceId, device.getId())
                .eq(DeviceMaintenancePlanDetails::getMaintenanceDate, remind));
        if (exist != null && exist > 0) {
            return;
        }
        DeviceMaintenancePlanDetails detail = new DeviceMaintenancePlanDetails();
        detail.setMaintenancePlanId(plan.getMaintenancePlanId());
        detail.setDeviceId(device.getId());
        detail.setMaintenanceIntervals(device.getMaintenanceCycle());
        detail.setMaintenanceDate(remind);
        deviceMaintenancePlanDetailsMapper.insert(detail);
    }
 
}