EquipmentMaintenanceTaskController.java 32.5 KB
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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
package com.skua.modules.equipment.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.skua.aop.annotation.CustomExceptionAnno;
import com.skua.core.api.vo.Result;
import com.skua.core.aspect.annotation.AutoLog;
import com.skua.core.util.DateUtils;
import com.skua.modules.common.service.ICommonSqlService;
import com.skua.modules.equipment.dto.EquipmentMaintenanceTaskDTO;
import com.skua.modules.equipment.entity.*;
import com.skua.modules.equipment.enums.EquipmentMaintenanceEnums;
import com.skua.modules.equipment.service.*;
import com.skua.modules.equipment.util.EquipmentUtils;
import com.skua.modules.equipment.vo.EquipmentInfoVO;
import com.skua.modules.equipment.vo.EquipmentSparepartVO;
import com.skua.redis.component.Key2ValueService;
import com.skua.redis.util.CustomRedisUtil;
import com.skua.tool.javassist.JavassistFactory;
import com.skua.tool.query.WrapperFactory;
import com.skua.tool.util.BeanExtUtils;
import com.skua.tool.util.JoinSqlUtils;
import com.skua.tool.util.UniqIdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;

/**
 * 设备保养任务
 */
@Slf4j
@Api(tags = "设备保养任务")
@RestController
@RequestMapping("/equipment/equipmentMaintenanceTask")
public class EquipmentMaintenanceTaskController {

    @Autowired
    private IEquipmentMaintenanceTaskService equipmentMaintenanceTaskService;
    @Autowired
    private ICommonSqlService commonSqlService;
    @Autowired
    private IEquipmentInfoService equipmentInfoService;
    @Autowired
    private IEquipmentMaintenancePlanService equipmentMaintenancePlanService;
    @Autowired
    private IEquipmentMaintenanceRecordChildService equipmentMaintenanceRecordChildService;
    @Autowired
    private TransactionTemplate transactionTemplate;
    @Autowired
    private IEquipmentSparepartService iEquipmentSparepartService;
    @Autowired
    private IEquipmentMaintenanceRecordService equipmentMaintenanceRecordService;
    @Autowired
    private IEquipmentOutService equipmentOutService;
    @Autowired
    private IEquipmentOutChildService iEquipmentOutChildService;
    @Autowired
    private CustomRedisUtil customRedisUtil;
    @Autowired
    private Key2ValueService key2ValueService;
    @Autowired
    @Qualifier("taskExecutor")
    private ThreadPoolTaskExecutor taskExecutor;

    /**
     * 分页列表查询
     *
     * @param equipmentMaintenanceTaskDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "设备保养任务-分页列表查询")
    @ApiOperation(value = "设备保养任务-分页列表查询", notes = "设备保养任务-分页列表查询")
    @GetMapping(value = "/list")
    @CustomExceptionAnno(description = "设备保养任务-分页列表查询")
    public Result<Object> queryPageList(EquipmentMaintenanceTaskDTO equipmentMaintenanceTaskDTO,
                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
        Result<Object> result = new Result<>();
        updateTaskResultFunc();
        Page page = new Page(pageNo, pageSize);
        Page<Map<String, Object>> mapPage = WrapperFactory.joinWrapper()
                .from(EquipmentMaintenancePlan.class)
                .innerJoin(EquipmentMaintenanceTask.class, EquipmentMaintenanceTask.class.getDeclaredField("planId"), EquipmentMaintenancePlan.class.getDeclaredField("id"))
                .where()
                .eq(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getTaskExecutor()), "equipment_maintain_task.task_executor", equipmentMaintenanceTaskDTO.getTaskExecutor())
                .eq(equipmentMaintenanceTaskDTO.getTaskResult() != null, "equipment_maintain_task.task_result", equipmentMaintenanceTaskDTO.getTaskResult())
                .like(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getPlanName()), "equipment_maintenance_plan.plan_name", equipmentMaintenanceTaskDTO.getPlanName())
                .like(equipmentMaintenanceTaskDTO.getTaskStatus() != null, "equipment_maintain_task.task_status", equipmentMaintenanceTaskDTO.getTaskStatus())
                .between(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getStartTime()) && StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getEndTime()), "equipment_maintain_task.task_start_time", equipmentMaintenanceTaskDTO.getStartTime() + " 00:00:00", equipmentMaintenanceTaskDTO.getEndTime() + " 23:59:59")
                .orderBy(true, false, "equipment_maintain_task.task_start_time")
                .queryWrapperForPage(page);
        Map<String, String> sysUserVal2KeyMap = EquipmentUtils.convertFunc("sysUser", false);
        List<Map<String, Object>> convertMapList = WrapperFactory.result()
                .addCallback(EquipmentMaintenancePlan.class.getDeclaredField("departId"), "departId_dictText")
                .addCallback(EquipmentMaintenanceTask.class.getDeclaredField("taskExecutor"), "taskExecutor_dictText")
                .maps2MapsWithoutPrefix(mapPage.getRecords(), (targetFieldName, srcFieldVal) -> {
                    if ("departId_dictText".equals(targetFieldName)) {
                        return customRedisUtil.hget("sys_depart", srcFieldVal.toString(), "id", "depart_name");
                    } else if ("taskExecutor_dictText".equals(targetFieldName)) {
                        return sysUserVal2KeyMap.getOrDefault("" + srcFieldVal, "" + srcFieldVal);
                    }
                    return srcFieldVal;
                });
        page.setTotal(mapPage.getTotal());
        page.setRecords(convertMapList);
        result.setResult(page);
        return result;
    }

    @AutoLog(value = "设备保养任务-按天聚合")
    @ApiOperation(value = "设备保养任务-按天聚合", notes = "设备保养任务-按天聚合")
    @GetMapping(value = "/dayList")
    @CustomExceptionAnno(description = "设备保养任务-分页列表查询")
    public Result<Object> dayListCtrl(EquipmentMaintenanceTaskDTO equipmentMaintenanceTaskDTO) throws Exception {
        Result<Object> result = new Result<>();
        updateTaskResultFunc();
        Map<String, String> sysUserVal2KeyMap = key2ValueService.dictKey2Val("sysUser", false);
        List<Map<String, Object>> mapList = WrapperFactory.joinWrapper()
                .from(EquipmentMaintenancePlan.class)
                .innerJoin(EquipmentMaintenanceTask.class, EquipmentMaintenanceTask.class.getDeclaredField("planId"), EquipmentMaintenancePlan.class.getDeclaredField("id"))
                .where()
                .eq(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getDepartId()), "equipment_maintain_plan.depart_id", equipmentMaintenanceTaskDTO.getDepartId())
                .eq(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getTaskExecutor()), "equipment_maintain_task.task_executor", equipmentMaintenanceTaskDTO.getTaskExecutor())
                .eq(equipmentMaintenanceTaskDTO.getTaskResult() != null, "equipment_maintain_task.task_result", equipmentMaintenanceTaskDTO.getTaskResult())
                .like(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getPlanName()), "equipment_maintain_plan.plan_name", equipmentMaintenanceTaskDTO.getPlanName())
                .like(equipmentMaintenanceTaskDTO.getTaskStatus() != null, "equipment_maintain_task.task_status", equipmentMaintenanceTaskDTO.getTaskStatus())
                .between(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getStartTime()) && StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getEndTime()), "equipment_maintain_task.task_start_time", equipmentMaintenanceTaskDTO.getStartTime() + " 00:00:00", equipmentMaintenanceTaskDTO.getEndTime() + " 23:59:59")
                .orderBy(true, true, "equipment_maintain_task.task_start_time")
                .queryWrapperForList();
        List<Map<String, Object>> convertMapList = WrapperFactory.result()
                .addCallback(EquipmentMaintenancePlan.class.getDeclaredField("departId"), "departId_dictText")
                .addCallback(EquipmentMaintenanceTask.class.getDeclaredField("taskExecutor"), "taskExecutor_dictText")
                .maps2MapsWithoutPrefix(mapList, (targetFieldName, srcFieldVal) -> {
                    if ("departId_dictText".equals(targetFieldName)) {
                        return customRedisUtil.hget("sys_depart", srcFieldVal.toString(), "id", "depart_name");
                    } else if ("taskExecutor_dictText".equals(targetFieldName)) {
                        return sysUserVal2KeyMap.getOrDefault("" + srcFieldVal, "" + srcFieldVal);
                    }
                    return srcFieldVal;
                });
        Map<String, List<Map<String, Object>>> day2EntitiesMap = new LinkedHashMap<>();
        for (Map<String, Object> item : convertMapList) {
            String curDay = item.get("taskStartTime").toString().split(" ")[0];
            List<Map<String, Object>> taskList = day2EntitiesMap.get(curDay);
            if (taskList == null) {
                taskList = new ArrayList<>();
                taskList.add(item);
                day2EntitiesMap.put(curDay, taskList);
            } else {
                taskList.add(item);
            }
        }
        // web端返回结果集
        result.setResult(day2EntitiesMap);
        // app端返回结果集
        if (equipmentMaintenanceTaskDTO.getIsApp() == 1) {
            List<Map<String, Object>> resList = new ArrayList<>();
            for (Map.Entry<String, List<Map<String, Object>>> item : day2EntitiesMap.entrySet()) {
                Map<String, Object> tmp = new HashMap<>();
                tmp.put("time", item.getKey());
                tmp.put("data", item.getValue());
                resList.add(tmp);
            }
            result.setResult(resList);
        }
        return result;
    }

    /**
     * 更新任务结果状态
     */
    private void updateTaskResultFunc() {
        // 更新结果状态
        String curDayStr = DateUtils.getDate("yyyy-MM-dd") + " 23:59:59";
        UpdateWrapper<?> updateWrapper = new UpdateWrapper<>()
                .set("task_result", EquipmentMaintenanceEnums.RUNNING.getKey())
                .eq("task_result", 0)
                .le("task_start_time", curDayStr);
        commonSqlService.updateWrapper("equipment_maintain_task", updateWrapper);
        // 更新任务状态是否异常
        UpdateWrapper<?> updateWrapper2 = new UpdateWrapper<>()
                .set("task_status", 0)
                .apply("complete_time > task_end_time");
        commonSqlService.updateWrapper("equipment_maintain_task", updateWrapper2);
    }

    /**
     * 保存
     *
     * @param equipmentMaintenanceTaskDTO
     * @return
     */
    @AutoLog(value = "设备保养任务-保存")
    @ApiOperation(value = "设备保养任务-保存", notes = "设备保养任务-保存")
    @PutMapping(value = "/edit")
    @CustomExceptionAnno(description = "设备保养任务-保存")
    public Result<EquipmentMaintenanceTask> editCtrl(@RequestBody EquipmentMaintenanceTaskDTO equipmentMaintenanceTaskDTO) throws Exception {
        Result<EquipmentMaintenanceTask> result = new Result<>();
        // 备件是否存在 默认true, 若不存在则为false
        List<EquipmentMaintenanceRecordChild> equipmentMaintenanceRecordChildList = equipmentMaintenanceTaskDTO.getEquipmentMaintenanceRecordChildList();
        EquipmentMaintenanceTask equipmentMaintenanceTask = equipmentMaintenanceTaskService.getById(equipmentMaintenanceTaskDTO.getId());
        // 更新保养任务, 同"保存"相比, 多了 完成时间 和 任务状态
        UpdateWrapper<EquipmentMaintenanceTask> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("actual_cost_time", equipmentMaintenanceTaskDTO.getActualCostTime())
                .set(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getRemark()), "remark", equipmentMaintenanceTaskDTO.getRemark())
                .set(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getFinishPhoto()), "finish_photo", equipmentMaintenanceTaskDTO.getFinishPhoto())
                .eq("id", equipmentMaintenanceTask.getId());
        // 设置child: taskId
        if (equipmentMaintenanceRecordChildList != null && !equipmentMaintenanceRecordChildList.isEmpty()) {
            equipmentMaintenanceRecordChildList.forEach(item -> item.setTaskId(equipmentMaintenanceTaskDTO.getId()));
        }
        // 删除旧的任务关联关系
        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", equipmentMaintenanceTask.getId());
        Integer res = transactionTemplate.execute((transactionStatus -> {
            commonSqlService.updateWrapper("equipment_maintain_task", updateWrapper);
            commonSqlService.deleteWrapper("equipment_maintenance_record_child", queryWrapper);
            if (equipmentMaintenanceRecordChildList != null && !equipmentMaintenanceRecordChildList.isEmpty()) {
                equipmentMaintenanceRecordChildService.saveBatch(equipmentMaintenanceRecordChildList);
            }
            return 1;
        }));
        if (res != null && res == 1) {
            result.success("保存成功!");
        } else {
            result.success("保存失败!");
        }
        return result;
    }

    @AutoLog(value = "设备保养任务-保存并执行")
    @ApiOperation(value = "设备保养任务-保存并执行", notes = "设备保养任务-保存并执行")
    @PutMapping(value = "/finish")
    @CustomExceptionAnno(description = "设备保养任务-保存并执行")
    public Result<EquipmentMaintenanceTask> finishCtrl(@RequestBody EquipmentMaintenanceTaskDTO equipmentMaintenanceTaskDTO) throws Exception {
        Result<EquipmentMaintenanceTask> result = new Result<>();
        List<EquipmentMaintenanceRecordChild> equipmentMaintenanceRecordChildList = equipmentMaintenanceTaskDTO.getEquipmentMaintenanceRecordChildList();
        // 设置child: taskId
        if (equipmentMaintenanceRecordChildList != null && !equipmentMaintenanceRecordChildList.isEmpty()) {
            equipmentMaintenanceRecordChildList.forEach(item -> item.setTaskId(equipmentMaintenanceTaskDTO.getId()));

        }
        EquipmentMaintenanceTask equipmentMaintenanceTask = equipmentMaintenanceTaskService.getById(equipmentMaintenanceTaskDTO.getId());
        // 更新保养任务, 同"保存"相比, 多了 完成时间 和 任务状态
        UpdateWrapper<EquipmentMaintenanceTask> updateWrapper = new UpdateWrapper<>();
        equipmentMaintenanceTask.setCompleteTime(new Date());
        equipmentMaintenanceTask.setTaskResult(EquipmentMaintenanceEnums.FINISHED.getKey());
        updateWrapper.set("actual_cost_time", equipmentMaintenanceTaskDTO.getActualCostTime())
                .set(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getRemark()), "remark", equipmentMaintenanceTaskDTO.getRemark())
                .set("complete_time", equipmentMaintenanceTask.getCompleteTime())
                .set("task_result", equipmentMaintenanceTask.getTaskResult())
                .set(StringUtils.isNotEmpty(equipmentMaintenanceTaskDTO.getFinishPhoto()), "finish_photo", equipmentMaintenanceTaskDTO.getFinishPhoto())
                .eq("id", equipmentMaintenanceTask.getId());
        // 保养记录
        EquipmentMaintenanceRecord equipmentMaintenanceRecord = BeanExtUtils.bean2Bean(equipmentMaintenanceTask, EquipmentMaintenanceRecord.class);
        EquipmentMaintenancePlan equipmentMaintenancePlan = equipmentMaintenancePlanService.getById(equipmentMaintenanceRecord.getPlanId());
        String recordId = UniqIdUtils.getInstance().getUniqID();
        equipmentMaintenanceRecord.setId(recordId);
        equipmentMaintenanceRecord.setDescription(equipmentMaintenancePlan.getDescription());
        equipmentMaintenanceRecord.setPlanName(equipmentMaintenancePlan.getPlanName());
        equipmentMaintenanceRecord.setDepartId(equipmentMaintenancePlan.getDepartId());
        equipmentMaintenanceRecord.setPlanCode(equipmentMaintenancePlan.getPlanCode());
        equipmentMaintenanceRecord.setPlanContent(equipmentMaintenancePlan.getPlanContent());
        equipmentMaintenanceRecord.setTaskResult(EquipmentMaintenanceEnums.FINISHED.getKey());
        equipmentMaintenanceRecord.setPlanTimeLimit(equipmentMaintenancePlan.getPlanTimeLimit());
        equipmentMaintenanceRecord.setActualCostTime(equipmentMaintenanceTaskDTO.getActualCostTime());
        equipmentMaintenanceRecord.setRemark(equipmentMaintenanceTaskDTO.getRemark());
        // 设置child: recordId
        if (equipmentMaintenanceRecordChildList != null && !equipmentMaintenanceRecordChildList.isEmpty()) {
            equipmentMaintenanceRecordChildList.forEach(item -> {
                item.setId(UniqIdUtils.getInstance().getUniqID());
                item.setRecordId(recordId);
                item.setTaskId(equipmentMaintenanceTaskDTO.getId());
            });
        }
        // 删除旧的任务关联关系
        QueryWrapper<?> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("task_id", equipmentMaintenanceTask.getId());
        // 生成出库记录
        EquipmentOut equipmentOut = handleEquipmentOutFunc(equipmentMaintenanceRecord);
        Integer res = transactionTemplate.execute((transactionStatus -> {
            commonSqlService.updateWrapper("equipment_maintain_task", updateWrapper);
            commonSqlService.deleteWrapper("equipment_maintenance_record_child", queryWrapper);
            if (equipmentMaintenanceRecordChildList != null && !equipmentMaintenanceRecordChildList.isEmpty()) {
                equipmentMaintenanceRecordChildService.saveBatch(equipmentMaintenanceRecordChildList);
            }
            equipmentMaintenanceRecordService.save(equipmentMaintenanceRecord);
            equipmentOutService.save(equipmentOut);
            return 1;
        }));
        if (res != null && res == 1) {
            // 减少备件
            if (equipmentMaintenanceRecordChildList != null) {
                List<EquipmentMaintenanceRecordChild> tmp = new ArrayList<>(equipmentMaintenanceRecordChildList);
                tmp.removeIf(item -> StringUtils.isEmpty(item.getSparepartId()) || item.getConsumeNum() == null || item.getConsumeNum() == 0);
                if (!tmp.isEmpty()) {
                    handleSparepartFunc(equipmentOut, tmp);
                }
            }
            result.success("执行成功!");
        } else {
            result.success("执行失败!");
        }
        return result;
    }

    private void handleSparepartFunc(EquipmentOut equipmentOut, List<EquipmentMaintenanceRecordChild> equipmentMaintenanceRecordChildList) throws Exception {
        if (equipmentMaintenanceRecordChildList != null && !equipmentMaintenanceRecordChildList.isEmpty()) {
            // 生成出库记录详情
            List<EquipmentOutChild> equipmentOutChildList = handleEquipmentOutChildFunc(equipmentOut, equipmentMaintenanceRecordChildList);
            CountDownLatch countDownLatch = new CountDownLatch(equipmentMaintenanceRecordChildList.size());
            for (EquipmentMaintenanceRecordChild equipmentMaintenanceRecordChild : equipmentMaintenanceRecordChildList) {
                taskExecutor.execute(() -> {
                    try {
                        String sparepartId = equipmentMaintenanceRecordChild.getSparepartId();
                        long startTime = System.currentTimeMillis();
                        long endTime = System.currentTimeMillis();
                        while (endTime - startTime < 1000 * 60 * 1.5) {
                            EquipmentSparepart equipmentSparepart = iEquipmentSparepartService.getById(sparepartId);
                            Integer resetStorageNum = 0;//equipmentSparepart.getStorageNum() - equipmentMaintenanceRecordChild.getConsumeNum();
                            if (resetStorageNum < 0) {
                                break;
                            }
                            Integer executeRes = transactionTemplate.execute(transactionStatus -> {
                                int val0 = 0;//iEquipmentSparepartService.updateStorageNumById(sparepartId, resetStorageNum, equipmentSparepart.getVersion());
                                if (val0 == 1) {
                                    return 1;
                                }
                                transactionStatus.setRollbackOnly();
                                return 0;
                            });
                            if (executeRes != null && executeRes == 1) {
                                break;
                            }
                            endTime = System.currentTimeMillis();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("异常error: {}", e.getMessage());
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }
            countDownLatch.await();
            iEquipmentOutChildService.saveBatch(equipmentOutChildList);
        }
    }

    private EquipmentOut handleEquipmentOutFunc(EquipmentMaintenanceRecord equipmentMaintenanceRecord) {
        EquipmentOut equipmentOut = new EquipmentOut();
        // 生成出库主键
        String outId = UniqIdUtils.getInstance().getUniqID();
        // 生成出库单号
        String outOrder = "CK-" + DateUtils.format(new Date(), "YYYYMMdd" + "-" + System.currentTimeMillis());
        equipmentOut.setId(outId);
        equipmentOut.setOutOrder(outOrder);
        equipmentOut.setDepartId(equipmentMaintenanceRecord.getDepartId());
        equipmentOut.setOutType("保养领用出库");
        equipmentOut.setUseBy(equipmentMaintenanceRecord.getTaskExecutor());
        return equipmentOut;
    }

    private List<EquipmentOutChild> handleEquipmentOutChildFunc(EquipmentOut equipmentOut, List<EquipmentMaintenanceRecordChild> equipmentMaintenanceRecordChildList) {
        List<EquipmentOutChild> equipmentOutChildList = new ArrayList<>();
        // 统计每个备件消耗的数量
        Map<String, Integer> sparepartId2NumMap = new HashMap<>();
        for (EquipmentMaintenanceRecordChild item : equipmentMaintenanceRecordChildList) {
            sparepartId2NumMap.put(item.getSparepartId(), sparepartId2NumMap.getOrDefault(item.getSparepartId(), 0) + item.getConsumeNum());
        }
        for (Map.Entry<String, Integer> item : sparepartId2NumMap.entrySet()) {
            EquipmentOutChild equipmentOutChild = new EquipmentOutChild();
            equipmentOutChild.setOutId(equipmentOut.getId());
            equipmentOutChild.setSparepartId(item.getKey());
            //equipmentOutChild.setOutNum(item.getValue());
            equipmentOutChildList.add(equipmentOutChild);
        }
        return equipmentOutChildList;
    }

    @AutoLog(value = "设备保养任务-转派任务")
    @ApiOperation(value = "设备保养任务-转派任务", notes = "设备保养任务-转派任务")
    @PutMapping(value = "/reDeploy")
    public Result<?> reDeployCtrl(@RequestBody EquipmentMaintenanceTaskDTO equipmentMaintenanceTaskDTO) {
        Result<?> result = new Result<>();
        UpdateWrapper<EquipmentMaintenanceTask> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("task_executor", equipmentMaintenanceTaskDTO.getTaskExecutor());
        updateWrapper.eq("id", equipmentMaintenanceTaskDTO.getId());
        commonSqlService.updateWrapper("equipment_maintain_task", updateWrapper);
        result.success("转派成功!");
        return result;
    }

    @AutoLog(value = "设备保养任务-设备详情")
    @ApiOperation(value = "设备保养任务-设备详情", notes = "设备保养任务-设备详情")
    @CustomExceptionAnno(description = "设备保养任务-设备详情")
    @GetMapping(value = "/infoDetail")
    public Result<Object> infoDetailCtrl(@RequestParam("id") String id) throws Exception {
        Result<Object> result = new Result<>();
        List<Map<String, Object>> mapList = WrapperFactory.joinWrapper()
                .from(EquipmentMaintenanceRecordChild.class)
                .innerJoin(EquipmentMaintenanceTask.class, EquipmentMaintenanceTask.class.getDeclaredField("id"), EquipmentMaintenanceRecordChild.class.getDeclaredField("taskId"))
                .innerJoin(EquipmentInfo.class, EquipmentInfo.class.getDeclaredField("id"), EquipmentMaintenanceRecordChild.class.getDeclaredField("infoId"))
                .innerJoin(EquipmentSparepart.class, EquipmentSparepart.class.getDeclaredField("id"), EquipmentMaintenanceRecordChild.class.getDeclaredField("sparepartId"))
                .where()
                .eq(true, "equipment_maintenance_record_child.task_id", id)
                .queryWrapperForList();
        Map<String, String> installPositionVal2KeyMap = EquipmentUtils.convertFunc("installPosition", false);
        Map<String, Integer> sparepartId2StorageNumMap = null;//iEquipmentSparepartService.list().stream().collect(Collectors.toMap(EquipmentSparepart::getId, EquipmentSparepart::getStorageNum));
        if (mapList.isEmpty()) {
            EquipmentMaintenanceTask equipmentMaintenanceTask = equipmentMaintenanceTaskService.getById(id);
            if (equipmentMaintenanceTask == null) {
                result.setResult(new ArrayList<>());
                return result;
            }
            String infoIds = equipmentMaintenanceTask.getInfoIds();
            QueryWrapper<EquipmentInfo> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("id", Arrays.asList(infoIds.split(",")));
            List<EquipmentInfo> equipmentInfoList = equipmentInfoService.list(queryWrapper2);
            List<EquipmentInfoVO> equipmentInfoVOList = BeanExtUtils.beans2Beans(equipmentInfoList, EquipmentInfoVO.class, (targetFieldName, srcFieldVal) -> {
                if ("departId_dictText".equals(targetFieldName)) {
                    return customRedisUtil.hget("sys_depart", "" + srcFieldVal, "id", "depart_name");
                } else if ("installPosition_dictText".equals(targetFieldName)) {
                    return installPositionVal2KeyMap.getOrDefault(srcFieldVal, "");
                }
                return srcFieldVal;
            });
            equipmentInfoVOList.forEach(item -> item.setEquipmentSparepartList(new ArrayList<>()));
            result.setResult(equipmentInfoVOList);
        } else {
            Map<String, Map<String, Object>> infoId2EntityMap = new LinkedHashMap<>();
            List<EquipmentSparepartVO> equipmentSparepartList;
            Map<String, Object> entity;
            for (Map<String, Object> map : mapList) {
                if (infoId2EntityMap.get("" + map.get("EquipmentInfo_id")) == null) {
                    String includeStr = "EquipmentInfo_equipmentBitNumber,EquipmentInfo_id,EquipmentInfo_departId,EquipmentInfo_equipmentName,EquipmentInfo_equipmentImg,EquipmentInfo_equipmentCode,EquipmentInfo_installPosition";
                    Map<String, String> callbackMap = new HashMap<>();
                    callbackMap.put("EquipmentInfo_departId", "EquipmentInfo_departId_dictText");
                    callbackMap.put("EquipmentInfo_installPosition", "EquipmentInfo_installPosition_dictText");
                    entity = JoinSqlUtils.map2MapWithoutPrefix(map, Arrays.asList(includeStr.split(",")), callbackMap, (targetFieldName, srcFieldVal) -> {
                        if ("EquipmentInfo_departId_dictText".equals(targetFieldName)) {
                            return customRedisUtil.hget("sys_depart", "" + srcFieldVal, "id", "depart_name");
                        } else if ("EquipmentInfo_installPosition_dictText".equals(targetFieldName)) {
                            return installPositionVal2KeyMap.getOrDefault(srcFieldVal, "");
                        }
                        return srcFieldVal;
                    });
                    equipmentSparepartList = new ArrayList<>();
                } else {
                    entity = infoId2EntityMap.get("" + map.get("EquipmentInfo_id"));
                    equipmentSparepartList = (List<EquipmentSparepartVO>) entity.get("equipmentSparepartList");
                }
                EquipmentSparepartVO equipmentSparepartVO = new EquipmentSparepartVO();
                equipmentSparepartVO.setId("" + map.get("EquipmentSparepart_id"));
                equipmentSparepartVO.setSparepartName("" + map.get("EquipmentSparepart_sparepartName"));
                equipmentSparepartVO.setConsumeNum("" + map.get("EquipmentMaintenanceRecordChild_consumeNum"));
                //equipmentSparepartVO.setStorageNum(sparepartId2StorageNumMap.get("" + map.get("EquipmentSparepart_id")));
                equipmentSparepartList.add(equipmentSparepartVO);
                entity.put("equipmentSparepartList", equipmentSparepartList);
                infoId2EntityMap.put("" + map.get("EquipmentInfo_id"), entity);
            }
            result.setResult(infoId2EntityMap.values());
        }
        result.setSuccess(true);
        return result;
    }

    /**
     * 编辑
     *
     * @param equipmentMaintenanceTask
     * @return
     */
    @AutoLog(value = "设备保养任务-编辑")
    @ApiOperation(value = "设备保养任务-编辑", notes = "设备保养任务-编辑")
    @PutMapping(value = "/update")
    public Result<EquipmentMaintenanceTask> updateCtrl(@RequestBody EquipmentMaintenanceTask equipmentMaintenanceTask) {
        Result<EquipmentMaintenanceTask> result = new Result<>();
        EquipmentMaintenanceTask entity = equipmentMaintenanceTaskService.getById(equipmentMaintenanceTask.getId());
        if (entity == null) {
            result.error500("未找到对应实体");
        } else {
            boolean ok = equipmentMaintenanceTaskService.updateById(equipmentMaintenanceTask);
            //TODO 返回false说明什么?
            if (ok) {
                result.success("修改成功!");
            }
        }
        return result;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备保养任务-通过id删除")
    @ApiOperation(value = "设备保养任务-通过id删除", notes = "设备保养任务-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id") String id) {
        try {
            QueryWrapper<?> queryWrapper = new QueryWrapper<>()
                    .eq("id", id)
                    .isNull("record_id");
            transactionTemplate.execute(transactionStatus -> {
                equipmentMaintenanceTaskService.removeById(id);
                commonSqlService.deleteWrapper("equipment_maintenance_record_child", queryWrapper);
                return 1;
            });
        } catch (Exception e) {
            log.error("删除失败: {}", e.getMessage());
            return Result.error("删除失败!");
        }
        return Result.ok("删除成功!");
    }

    @AutoLog(value = "设备保养任务-转派任务选择人")
    @ApiOperation(value = "设备保养任务-转派任务选择人", notes = "设备保养任务-转派任务选择人")
    @CustomExceptionAnno(description = "设备保养任务-转派任务选择人")
    @GetMapping(value = "/reDeployOfUser")
    public Result<Object> reDeployOfUserCtrl(@RequestParam String departId,
                                             @RequestParam String userId) throws Exception {
        Result<Object> result = new Result<>();
        Class sysUser = JavassistFactory.create().getClass("SysUser");
        Class sysUserDepart = JavassistFactory.create().getClass("SysUserDepart");
        Class sysDepart = JavassistFactory.create().getClass("SysDepart");
        List<Map<String, Object>> mapList = WrapperFactory.joinWrapper()
                .select("sys_user.id as userId", "sys_user.realname")
                .from(sysDepart)
                .innerJoin(sysUserDepart, sysUserDepart.getDeclaredField("depId"), sysDepart.getDeclaredField("id"))
                .innerJoin(sysUser, sysUser.getDeclaredField("id"), sysUserDepart.getDeclaredField("userId"))
                .where()
                .eq(true, "sys_depart.id", departId)
                .ne(true, "sys_user.id", userId)
                .queryWrapperForList();
        result.setResult(mapList);
        return result;
    }

}