package com.rongwei.bscommon.sys.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rongwei.bscommon.sys.config.EquMaintenanceStandardListener;
import com.rongwei.bscommon.sys.excel.EquMaintenanceStandardTemplate;
import com.rongwei.bscommon.sys.feign.RwAdminFeign;
import com.rongwei.bscommon.sys.service.*;
import com.rongwei.bscommon.sys.utils.CommonUtils;
import com.rongwei.bsentity.domain.*;
import com.rongwei.bsentity.dto.BatchCreateDTO;
import com.rongwei.bsentity.dto.PlanYearCopyDTO;
import com.rongwei.bsentity.dto.TaskCreatorDTO;
import com.rongwei.bsentity.enums.EquipmentTypeEnum;
import com.rongwei.bsentity.enums.MaintenanceTypeEnum;
import com.rongwei.bsentity.enums.PlannedStatusEnum;
import com.rongwei.bsentity.enums.PlantEnum;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommonentity.commonservers.vo.SysSerialVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author shangmi
 * @title MaintenanceServiceImpl
 * @date 2023/11/27 14:41
 * @description 保养检修ServiceImpl
 */
@Service
public class MaintenanceServiceImpl implements MaintenanceService {

    @Autowired
    private EquMaintenanceTaskService maintenanceTaskService;

    @Autowired
    private EquMaintenanceScheduleService maintenanceScheduleService;

    @Autowired
    private EquMaintenancePartService maintenancePartService;

    @Autowired
    private EquPartsSetoutStandardService partsSetoutStandardService;

    @Autowired
    private EquPartsSetoutTaskService partsSetoutTaskService;

    @Autowired
    private EquMaintenanceStandardService maintenanceStandardService;

    @Autowired
    private AspCheckItemsService aspCheckItemsService;

    @Autowired
    private RwAdminFeign rwAdminFeign;

    /**
     * 发布任务
     *
     * @param taskCreator 入参
     * @return {@link R}
     * @date 2023/11/27 16:25
     * @author shangmi
     */

    @Override
    @Transactional
    public R saveTask(TaskCreatorDTO taskCreator) {
        // 查询主表信息
        EquMaintenanceScheduleDo maintenanceSchedule = maintenanceScheduleService.getMaintenanceSiteByList(taskCreator);
        // 查询子表信息
        Integer month = Integer.parseInt(taskCreator.getMonth());
        List<EquMaintenancePartDo> maintenancePartList = maintenancePartService.getMasterIdAndMonthByList(maintenanceSchedule.getId(), month, null);
        // 查询是否有生成过任务
        List<EquMaintenanceTaskDo> maintenanceSiteList = maintenanceTaskService.getMaintenanceSite(taskCreator);
        // 判断所有部位是否都有生成过任务
        if (maintenanceSiteList.size() == maintenancePartList.size()) {
            return R.error(maintenanceSchedule.getEquipmentname() + "在" + taskCreator.getYear() + "年" + month + "月的所有部位已发布任务或没有可发布的任务！");
        }
        // 任务表没有数据则全部添加
        if (maintenanceSiteList.size() != 0) {
            // 去重
            maintenancePartList = removeDuplicates(maintenancePartList, maintenanceSiteList);
        }
        // 通过主表ID查询备品备件信息
        List<EquPartsSetoutStandardDo> partsSetoutStandardList = partsSetoutStandardService.getMasterIdByList(maintenancePartList.stream().map(EquMaintenancePartDo::getMaintenancestandid).collect(Collectors.toList()));
        // 转移数据
        List<EquMaintenanceTaskDo> equMaintenanceTaskDos = dataTransfer(maintenancePartList, maintenanceSchedule, month);
        List<EquPartsSetoutTaskDo> partsSetoutTaskDoList = sparePartsConversion(partsSetoutStandardList, equMaintenanceTaskDos);
        // 插入
        int number = maintenanceTaskService.insertBatch(equMaintenanceTaskDos);
        if (partsSetoutTaskDoList.size() != 0) {
            partsSetoutTaskService.batchSave(partsSetoutTaskDoList);
        }
        maintenanceScheduleService.updatePlannedstatusByIds(Collections.singletonList(maintenanceSchedule.getId()), PlannedStatusEnum.PUBLISHED_TASK);
        // 判断是否全部插入成功
        if (number == equMaintenanceTaskDos.size()) {
            return R.ok();
        } else {
            return R.ok("数据添加不完整,请核对数据!");
        }
    }

    /**
     * 批量生成保养计划
     *
     * @param batchCreate 入参
     * @return {@link R}
     * @date 2023/11/29 14:01
     * @author shangmi
     */
    @Override
    @Transactional
    public R batchSavePlans(BatchCreateDTO batchCreate) {
        // 该设备分类下的所以部位保养标准
        List<EquMaintenanceStandardDo> partsSetoutStandardList = maintenanceStandardService.getPlanTypeByList(batchCreate.getEquipmentId());
        if (partsSetoutStandardList.size() == 0) {
            return R.error("选中的设备没有保养标准！");
        }
        // 明细表数组
        List<EquMaintenancePartDo> equMaintenancePartList = new ArrayList<>();

        // 获取设备ID并拆分
        List<String> equipmentId = Arrays.asList(batchCreate.getEquipmentId().split(","));
        // 设备计划数组
        List<EquMaintenanceScheduleDo> maintenancePartList = maintenanceScheduleService.getYearAndEquipmentByList(equipmentId, batchCreate);
        List<EquMaintenanceScheduleDo> maintenanceScheduleDos = new ArrayList<>();
        if (maintenancePartList.size() != 0) {
            maintenanceScheduleDos = maintenancePartList.stream().filter(info ->
                    equipmentId.contains(info.getEquipmentid())
            ).collect(Collectors.toList());
        }
        // 判断是否选中的设备以全部生成
        if (equipmentId.size() == maintenanceScheduleDos.size()) {
            return R.error("选中的设备已全部生成过" + batchCreate.getYear() + "年的保养计划，请勿重复生成！");
        }
        // 如果有重复则添加警告
        StringBuilder wrongData = new StringBuilder();
        if (maintenanceScheduleDos.size() != 0) {
            for (int i = 0; i < maintenanceScheduleDos.size(); i++) {
                wrongData.append(maintenanceScheduleDos.get(i).getEquipmentname());
                if (i != maintenanceScheduleDos.size() - 1) {
                    wrongData.append("、");
                }
            }
            wrongData.append("已存在").append(batchCreate.getYear()).append("年的保养计划记录，不可重复添加，其余设备保养计划系统正常生成成功。");
        }
        List<AspCheckItems> aspCheckItems = new ArrayList<>(aspCheckItemsService.listByIds(equipmentId));
        List<EquMaintenanceScheduleDo> maintenanceScheduleList = aspCheckItems.stream().map(info -> {
            // 数据转换（设备——计划）
            EquMaintenanceScheduleDo maintenanceScheduleDo = dataShiftFacilityToPlan(info, batchCreate.getYear());
            equMaintenancePartList.addAll(dataShiftSpareStandToPlan(partsSetoutStandardList, maintenanceScheduleDo.getId()));
            return maintenanceScheduleDo;
        }).collect(Collectors.toList());
        maintenanceScheduleService.saveBatchList(maintenanceScheduleList);
        maintenancePartService.saveBatchList(equMaintenancePartList);
        if (wrongData.length() == 0) {
            return R.ok();
        } else {
            return R.error(wrongData.toString());
        }
    }

    /**
     * 复制年度计划
     *
     * @param planYearCopy 入参
     * @return {@link R}
     * @date 2023/11/30 17:36
     * @author shangmi
     */
    @Override
    @Transactional
    public R saveYearByTask(PlanYearCopyDTO planYearCopy) {

        Date newDate = new Date();
        SysUserVo currentUser = CommonUtils.getCurrentUser();
        // 获得指定年——工厂下所以计划及其备件信息
        List<EquMaintenanceScheduleDo> maintenanceScheduleOldList = maintenanceScheduleService.getYearAndTenantIdByList(planYearCopy.getOldYear(), planYearCopy.getTenantId());
        List<EquMaintenanceScheduleDo> maintenanceScheduleNewList = maintenanceScheduleService.getYearAndTenantIdByList(planYearCopy.getNewYear(), planYearCopy.getTenantId());
        List<EquMaintenanceScheduleDo> maintenanceScheduleList = maintenanceScheduleOldList;
        if (maintenanceScheduleNewList.size() != 0) {
            // 获取不重复数据（去重）
            maintenanceScheduleList = Stream.concat(maintenanceScheduleOldList.stream(), maintenanceScheduleNewList.stream())
                    .collect(Collectors.groupingBy(info -> info.getEquipmentid() + info.getPlantype(), Collectors.counting()))
                    .entrySet().stream()
                    .filter(info -> info.getValue() == 1)
                    .map(Map.Entry::getKey)
                    .map(info -> Stream.concat(maintenanceScheduleOldList.stream(), maintenanceScheduleNewList.stream())
                            .filter(item -> (item.getEquipmentid() + item.getPlantype()).equals(info))
                            .findFirst().orElse(null))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        }
        if (maintenanceScheduleList.size() == 0) {
            return R.error(PlantEnum.nameOf(planYearCopy.getTenantId()) + "已存在" + planYearCopy.getNewYear() + "年的保养计划记录，不可重复生成");
        }

        List<EquMaintenancePartDo> masterIdByList = maintenancePartService.getMasterIdByList(maintenanceScheduleList.stream().map(EquMaintenanceScheduleDo::getId).collect(Collectors.toList()));
        // 计划备件信息
        List<EquMaintenancePartDo> maintenancePartList = new ArrayList<>();
        // 赋值
        maintenanceScheduleList.forEach(info -> {
            List<EquMaintenancePartDo> collect = masterIdByList.stream().filter(item -> item.getMasterid().equals(info.getId())).collect(Collectors.toList());
            info.setId(SecurityUtil.getUUID())
                    .setPlanyear(planYearCopy.getNewYear())
                    .setCreateusername(currentUser.getName())
                    .setCreatedate(newDate)
                    .setCreateuserid(currentUser.getId())
                    .setModifyusername(currentUser.getName())
                    .setModifyuserid(currentUser.getId())
                    .setModifydate(newDate)
                    .setPlannedstatus(PlannedStatusEnum.UNLOCKED.getValue());

            collect.forEach(item -> {
                item.setId(SecurityUtil.getUUID())
                        .setMasterid(info.getId())
                        .setCreateusername(currentUser.getName())
                        .setCreatedate(newDate)
                        .setCreateuserid(currentUser.getId())
                        .setModifyusername(currentUser.getName())
                        .setModifyuserid(currentUser.getId())
                        .setModifydate(newDate);
            });
            maintenancePartList.addAll(collect);

        });
        boolean b = maintenanceScheduleService.saveBatch(maintenanceScheduleList, 100);
        maintenancePartService.saveBatch(maintenancePartList, 100);
        if (b) {
            return R.ok();
        } else {
            return R.error("数据添加不完整,请核对数据!");
        }
    }

    /**
     * Excel导入
     *
     * @param multipartFile 二进制文件内
     * @return {@link R}
     * @date 2023/12/11 11:14
     * @author shangmi
     */
    @Override
    public R uploadStandardSave(MultipartFile multipartFile) throws IOException {
        Date date = new Date();
        EquMaintenanceStandardListener standardListener = new EquMaintenanceStandardListener();
        // 解析Excel
        EasyExcel.read(multipartFile.getInputStream(), EquMaintenanceStandardTemplate.class, standardListener).sheet().headRowNumber(4).doRead();
        // 解析有误信息
        List<String> errorData = standardListener.getErrorData();
        // 解析数据
        List<EquMaintenanceStandardDo> newMaintenanceStandardList = standardListener.getMaintenanceStandardList();
        // 唯一性数据
        List<EquMaintenanceStandardDo> oldMaintenanceStandardList = maintenanceStandardService.getUniqueDateByAll();
        // 将新旧两组数据拼接为一个stream，再对stream进行分组，找到分组数量大于1的(说明又重复)，将重复的数据拿到原始数据中找到源数据返回回来
        List<EquMaintenanceStandardDo> maintenanceStandardDoList = Stream.concat(newMaintenanceStandardList.stream(), oldMaintenanceStandardList.stream()).collect(Collectors.groupingBy(info ->
                info.getTenantid() + info.getEquipmenttype() + info.getMaintenancetype() + info.getMaintenancesite() + info.getMaintenancecontext(), Collectors.counting()))
                .entrySet().stream()
                .filter(info -> info.getValue() > 1)
                .map(Map.Entry::getKey)
                .map(info -> newMaintenanceStandardList.stream()
                        .filter(item -> (item.getTenantid() + item.getEquipmenttype() + item.getMaintenancetype() + item.getMaintenancesite() + item.getMaintenancecontext()).equals(info))
                        .findFirst().orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 拼接返回错误数据
        if (maintenanceStandardDoList.size() != 0) {
            jointErrorData(maintenanceStandardDoList, errorData);
        }
        // 判断是否又错误数据
        if (errorData.size() != 0) {
            return R.error(JSON.toJSONString(errorData));
        }
        SysUserVo currentUser = CommonUtils.getCurrentUser();
        // 生成流水号
        for (EquMaintenanceStandardDo maintenanceStandard : newMaintenanceStandardList) {
            SysSerialVo sysSerialVo = new SysSerialVo();
            String plantSimp = PlantEnum.addrOf(maintenanceStandard.getTenantid());
            sysSerialVo.setModulecode("equ_maintenance_standard_aq_code_" + plantSimp);
            // sysSerialVo.setResetrule("date:yyyy");
            sysSerialVo.setRuleTemplateStr(plantSimp + "-BYBZ-@{serialNumber:#00000}");
            R serialNumberCode = rwAdminFeign.getSerialNumberCode(sysSerialVo);
            if ("200".equals(serialNumberCode.getCode())) {
                Object data = serialNumberCode.getData();
                maintenanceStandard.setStandardid(JSONObject.parseObject(JSONObject.toJSONString(data), Map.class).get("code").toString());
            }
            maintenanceStandard.setTenantid(currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1])
                    .setCreatedate(date)
                    .setModifydate(date)
                    .setCreateuserid(currentUser.getId())
                    .setCreateusername(currentUser.getName())
                    .setModifyusername(currentUser.getName())
                    .setModifyuserid(currentUser.getId());
        }
        maintenanceStandardService.saveBatch(newMaintenanceStandardList, 200);
        return R.ok("导入成功");
    }

    @Override
    @Transactional
    public R batchSavePlansTiming() {
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, +1);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);
        List<EquMaintenancePartDo> masterIdAndMonthByList = maintenancePartService.getMasterIdAndMonthByList(null, month, year);
        // 获取主表ID
        List<String> masterIds = new ArrayList<>(masterIdAndMonthByList.stream()
                .collect(Collectors.groupingBy(EquMaintenancePartDo::getMasterid)).keySet());
        if (masterIds.size() == 0) {
            return R.ok();
        }
        // 通过主表ID查询部位表
        List<EquMaintenanceScheduleDo> maintenanceScheduleList = maintenanceScheduleService.getListByIds(masterIds);

        // 通过主表ID查询备品备件信息
        List<EquPartsSetoutStandardDo> partsSetoutStandardList = partsSetoutStandardService.getMasterIdByList(masterIdAndMonthByList.stream().map(EquMaintenancePartDo::getMaintenancestandid).collect(Collectors.toList()));
        // 转移数据
        List<EquMaintenanceTaskDo> newMaintenanceTaskList = new ArrayList<>();
        for (EquMaintenanceScheduleDo maintenanceScheduleDo : maintenanceScheduleList) {
            List<EquMaintenancePartDo> maintenancePartDos = masterIdAndMonthByList.stream().filter(info -> info.getMasterid().equals(maintenanceScheduleDo.getId())).collect(Collectors.toList());
            newMaintenanceTaskList.addAll(dataTransfer(maintenancePartDos, maintenanceScheduleDo, month));
        }
        // 通过年月查询存在的任务
        List<EquMaintenanceTaskDo> oldMaintenanceSite = maintenanceTaskService.getListByYearAndMonth(year, month);
        // 去重重复任务
        List<EquMaintenanceTaskDo> equMaintenanceTaskList = Stream.concat(oldMaintenanceSite.stream(), newMaintenanceTaskList.stream())
                .collect(Collectors.groupingBy(info -> info.getEquipmentid() + info.getMaintenancesite(), Collectors.counting()))
                .entrySet().stream()
                .filter(info -> info.getValue() == 1)
                .map(Map.Entry::getKey)
                .map(info -> newMaintenanceTaskList.stream().filter(item -> info.equals(item.getEquipmentid() + item.getMaintenancesite()))
                        .findFirst().orElse(null))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // 匹配备品备件库信息
        List<EquPartsSetoutTaskDo> partsSetoutTaskDoList = sparePartsConversion(partsSetoutStandardList, equMaintenanceTaskList);

        // 插入
        int number = maintenanceTaskService.insertBatch(equMaintenanceTaskList);
        partsSetoutTaskService.batchSave(partsSetoutTaskDoList);
        if (month == 12) {
            List<EquMaintenanceScheduleDo> maintenancePartYearAll = maintenanceScheduleService.getYearByList(year);
            maintenanceScheduleService.updatePlannedstatusByIds(maintenancePartYearAll.stream().map(EquMaintenanceScheduleDo::getId).collect(Collectors.toList()), PlannedStatusEnum.PUBLISHED_TASK_ALL);
        } else {
            maintenanceScheduleService.updatePlannedstatusByIds(masterIds, PlannedStatusEnum.PUBLISHED_TASK);
        }
        // 判断是否全部插入成功
        if (number == equMaintenanceTaskList.size()) {
            return R.ok();
        } else {
            return R.ok("数据添加不完整,请核对数据!");
        }
    }


    /**
     * 拼接错误数据
     *
     * @param maintenanceStandardList
     * @param errorData
     * @return
     * @date 2023/12/8 16:43
     * @author shangmi
     */

    public void jointErrorData(List<EquMaintenanceStandardDo> maintenanceStandardList, List<String> errorData) {
        maintenanceStandardList.forEach(info -> {
            errorData.add(PlantEnum.nameOf(info.getTenantid()) + ",已存在了" + "-" + MaintenanceTypeEnum.typeOf(info.getMaintenancetype()) + "-" + info.getMaintenancesite() + "部位" + info.getMaintenancecontext() + "的保养标准内容，不可重复导入，请检查");
        });

    }

    /**
     * 详细库转移（标准——计划明细）
     *
     * @param partsSetoutStandardList 标准库备品备件
     * @param id                      主表ID
     * @return {@link Collection<? extends  EquMaintenancePartDo>}
     * @date 2023/11/29 16:21
     * @author shangmi
     */

    private Collection<? extends EquMaintenancePartDo> dataShiftSpareStandToPlan(List<EquMaintenanceStandardDo> partsSetoutStandardList, String id) {
        Date newDate = new Date();
        // SysUserVo currentUser = CommonUtils.getCurrentUser();
        return partsSetoutStandardList.stream().map(info -> {
            EquMaintenancePartDo maintenancePart = new EquMaintenancePartDo();
            BeanUtils.copyProperties(info, maintenancePart);
            maintenancePart.setId(SecurityUtil.getUUID())
                    .setCreatedate(newDate)
                    // .setCreateusername(currentUser.getName())
                    // .setCreateuserid(currentUser.getId())
                    // .setModifyuserid(currentUser.getId())
                    .setModifydate(newDate)
                    // .setModifyusername(currentUser.getName())
                    .setStandardrequest(info.getEquipmentsupport())
                    .setMaintenancestand(info.getStandardid())
                    .setMaintenancestandid(info.getId())
                    .setMaintenancecontent(info.getMaintenancecontext())
                    .setMasterid(id);
            return maintenancePart;
        }).collect(Collectors.toList());
    }


    /**
     * 处理数据转移 （任务——计划）
     *
     * @param maintenancePartList 保养部位
     * @param maintenanceSchedule 设备
     * @param month               月份
     * @return {@link List<EquMaintenanceTaskDo>}
     * @date 2023/11/27 17:55 创建时间
     * @author shangmi
     */

    public List<EquMaintenanceTaskDo> dataTransfer(
            List<EquMaintenancePartDo> maintenancePartList,
            EquMaintenanceScheduleDo maintenanceSchedule,
            Integer month) {
        Date newDate = new Date();
        // SysUserVo currentUser = CommonUtils.getCurrentUser();
        List<EquMaintenanceTaskDo> maintenanceTaskList = new ArrayList<>();
        // 遍历计划部位
        for (EquMaintenancePartDo maintenancePart : maintenancePartList) {
            SysSerialVo sysSerialVo = new SysSerialVo();
            // String plantSimp = PlantEnum.addrOf(currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1]);
            String plantSimp = PlantEnum.addrOf(maintenancePart.getTenantid());
            sysSerialVo.setModulecode("equ_maintenance_task_aq_code_" + plantSimp);
            sysSerialVo.setResetrule("date:yyyy");
            sysSerialVo.setIfautomaticreset("y");
            sysSerialVo.setRuleTemplateStr(plantSimp + "-" + maintenanceSchedule.getPlantype() + "-@{date:yyyyMM}-@{serialNumber:#00000}");
            // 获取流水号
            R serialNumberCode = rwAdminFeign.getSerialNumberCode(sysSerialVo);
            EquMaintenanceTaskDo equMaintenanceTask = new EquMaintenanceTaskDo();
            BeanUtils.copyProperties(maintenanceSchedule, equMaintenanceTask);
            BeanUtils.copyProperties(maintenancePart, equMaintenanceTask);
            equMaintenanceTask.setId(SecurityUtil.getUUID())
                    .setMonth(month.toString())
                    .setEquipmentnumber(maintenanceSchedule.getEquipmentnumber())
                    .setCreatedate(newDate)
                    .setModifydate(newDate)
                    .setTenantid(maintenanceSchedule.getTenantid());
            if ("200".equals(serialNumberCode.getCode())) {
                Object data = serialNumberCode.getData();
                equMaintenanceTask.setTaskid(JSONObject.parseObject(JSONObject.toJSONString(data), Map.class).get("code").toString());
            }
            maintenanceTaskList.add(equMaintenanceTask);
        }

        return maintenanceTaskList;
    }


    /**
     * 转移子表数据
     *
     * @param partsSetoutStandardList 标准库备品备件
     * @param equMaintenanceTaskDos   任务信息
     * @return {@link List<EquPartsSetoutTaskDo>}
     * @date 2023/11/28 19:16
     * @author shangmi
     */

    public List<EquPartsSetoutTaskDo> sparePartsConversion(
            List<EquPartsSetoutStandardDo> partsSetoutStandardList,
            List<EquMaintenanceTaskDo> equMaintenanceTaskDos) {
        Date newDate = new Date();
        SysUserVo currentUser = CommonUtils.getCurrentUser();
        // 遍历赛选出标准库备品备件主表ID和任务表标准库ID对应的字段并塞入任务表备品备件库中
        return equMaintenanceTaskDos.stream().map(info -> partsSetoutStandardList.stream()
                .filter(item -> item.getMasterid().equals(info.getMaintenancestandid()))
                .map(item -> {
                    EquPartsSetoutTaskDo equPartsSetoutTaskDo = new EquPartsSetoutTaskDo();
                    BeanUtils.copyProperties(item, equPartsSetoutTaskDo);
                    // 更换主表ID
                    equPartsSetoutTaskDo.setMasterid(info.getId())
                            .setId(SecurityUtil.getUUID())
                            .setCreateuserid(currentUser.getId())
                            .setCreateusername(currentUser.getName())
                            .setCreatedate(newDate)
                            .setModifyuserid(currentUser.getId())
                            .setModifyusername(currentUser.getName())
                            .setModifydate(newDate)
                            .setTenantid(currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1]);
                    return equPartsSetoutTaskDo;
                }).collect(Collectors.toList())).flatMap(Collection::stream).distinct().collect(Collectors.toList());
    }

    /**
     * 去重复
     *
     * @param maintenancePartList 部位表
     * @param maintenanceTaskList 任务表
     * @return {@link List<EquMaintenancePartDo>}
     * @date 2023/11/27 18:14
     * @author shangmi
     */
    public List<EquMaintenancePartDo> removeDuplicates(
            List<EquMaintenancePartDo> maintenancePartList,
            List<EquMaintenanceTaskDo> maintenanceTaskList) {
        // 获取任务表中存在的保养部位
        List<String> maintenanceSite = maintenanceTaskList.stream()
                .map(EquMaintenanceTaskDo::getMaintenancesite)
                .collect(Collectors.toList());
        // 对部位表进行去重
        return maintenancePartList.stream().filter(info ->
                !maintenanceSite.contains(info.getMaintenancesite())
        ).collect(Collectors.toList());
    }

    /**
     * 数据转换（设备——计划）
     *
     * @param aspCheckItem 设备信息
     * @return {@link EquMaintenanceStandardDo}
     * @date 2023/11/29 15:24
     * @author shangmi
     */

    public EquMaintenanceScheduleDo dataShiftFacilityToPlan(AspCheckItems aspCheckItem, Integer year) {
        EquMaintenanceScheduleDo maintenanceSchedule = new EquMaintenanceScheduleDo();
        Date newDate = new Date();
        // SysUserVo currentUser = CommonUtils.getCurrentUser();
        maintenanceSchedule.setEquipmenttype(aspCheckItem.getCheckitemtype())
                .setPlanyear(year)
                .setEquipmentname(aspCheckItem.getCheckitemname())
                .setEquipmentid(aspCheckItem.getId())
                .setEquipmentnumber(aspCheckItem.getCheckitemcode())
                .setPlantype("BY")
                .setSpecialequipment(aspCheckItem.getSource())
                .setObjecttype("1")
                .setSpecification(aspCheckItem.getDevicemodel())
                .setWorkshop(aspCheckItem.getUsedeptname())
                .setWorkshopid(aspCheckItem.getUsedeptid())
                .setPlannedstatus("unlocked")
                .setId(SecurityUtil.getUUID())
                .setCreatedate(newDate)
                // .setCreateuserid(currentUser.getId())
                // .setCreateusername(currentUser.getName())
                .setModifydate(newDate)
                // .setModifyuserid(currentUser.getId())
                // .setModifyusername(currentUser.getName())
                .setTenantid(aspCheckItem.getTenantid());
        return maintenanceSchedule;
    }


}
