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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rongwei.bscommon.sys.dao.*;
import com.rongwei.bscommon.sys.service.*;
import com.rongwei.bscommon.sys.utils.ApsUtils;
import com.rongwei.bsentity.domain.*;
import com.rongwei.bsentity.vo.*;
import com.rongwei.rwadmincommon.system.domain.SysDictDo;
import com.rongwei.rwadmincommon.system.service.SysGeneralCRUDService;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.BaseDo;
import com.rongwei.rwcommon.base.R;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.rwcommon.vo.MailDo;
import com.rongwei.rwcommon.vo.generalsql.MasterSlaveInsertVo;
import com.rongwei.rwcommon.vo.generalsql.MasterSlaveUpdateVo;
import com.rongwei.safecommon.fegin.CXAdminFeginClient;
import com.rongwei.safecommon.fegin.CXCommonFeginClient;
import com.rongwei.safecommon.utils.CXCommonUtils;
import com.rongwei.safecommon.utils.SaveConstans;
import com.rongwei.wfentity.sys.ProcessInstDo;
import com.rongwei.wfentity.sys.RunTaskDo;
import com.rongwei.wfentity.sys.vo.CreateProcessVo;
import com.rongwei.wfentity.sys.vo.FlowBackVo;
import com.rongwei.wfentity.sys.vo.RunTaskVo;
import com.rongwei.wfserver.wfcommon.core.service.impl.WorkFlowServiceImpl;
import com.rongwei.wfserver.wfcommon.sys.service.ProcessInstService;
import com.rongwei.wfserver.wfcommon.sys.service.RunTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.DatePattern.DATE_PATTERN_YMD;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyContent.*;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyTitle.*;
import static com.rongwei.safecommon.utils.SaveConstans.NotifyType.*;

/**
 *
 */
@Service
public class ApsProductionOrderServiceImpl extends ServiceImpl<ApsProductionOrderDao, ApsProductionOrderDo>
        implements ApsProductionOrderService {
    private final Logger log = LoggerFactory.getLogger(this.getClass().getName());

    //订单锁
    private final ConcurrentHashMap<String, String> productOrderLock = new ConcurrentHashMap<>();

    @Autowired
    private ApsProcessOperationDao apsProcessOperationDao;
    @Autowired
    private ApsBlankOrderDao apsBlankOrderDao;
    @Autowired
    private ApsProductDetailDao apsProductDetailDao;
    @Autowired
    private ApsProcessOperationProcessEquDao apsProcessOperationProcessEquDao;
    @Autowired
    private ApsProcessOperationBackupDao apsProcessOperationBackupDao;
    @Autowired
    private ApsProcessOperationProcessEquBackupDao apsProcessOperationProcessEquBackupDao;
    @Autowired
    private ApsBlankOrderService apsBlankOrderService;
    @Autowired
    private ApsProcessOutputProductService apsProcessOutputProductService;
    @Autowired
    private CXCommonFeginClient autoCommonFeginClient;
    @Autowired
    private ApsProductDetailService apsProductDetailService;
    @Autowired
    private ApsProductionMergeOrderService apsProductionMergeOrderService;
    @Autowired
    private ApsOrderAlloyCompositionService apsOrderAlloyCompositionService;
    @Autowired
    private ApsProductionMergeOrderDao apsProductionMergeOrderDao;
    @Autowired
    private ApsProductionTechnicalRequirementDao apsProductionTechnicalRequirementDao;
    @Autowired
    private ApsOrderAlloyCompositionDao apsOrderAlloyCompositionDao;
    @Autowired
    private ApsProductionMergeOrderHistoryService apsProductionMergeOrderHistoryService;
    @Autowired
    private ApsProductDetailHistoryService apsProductDetailHistoryService;
    @Autowired
    private ApsOrderAlloyCompositionHistoryService apsOrderAlloyCompositionHistoryService;
    @Autowired
    private ApsProductionTechnicalRequirementHistoryService apsProductionTechnicalRequirementHistoryService;
    @Autowired
    private ApsBlankOrderHistoryService apsBlankOrderHistoryService;
    @Autowired
    private ApsProcessOutputProductDao apsProcessOutputProductDao;
    @Autowired
    private ApsProcessOutputProductHistoryService apsProcessOutputProductHistoryService;
    @Autowired
    private ApsProcessOperationHistoryService apsProcessOperationHistoryService;
    @Autowired
    private ApsProcessOperationOutMaterHistoryService apsProcessOperationOutMaterHistoryService;
    @Autowired
    private ApsProcessOperationEquHistoryService apsProcessOperationEquHistoryService;
    @Autowired
    private ApsProcessOperationOutMaterDao apsProcessOperationOutMaterDao;
    @Autowired
    private ApsProcessOperationEquDao apsProcessOperationEquDao;
    @Autowired
    private ApsProductionOrderHistoryService apsProductionOrderHistoryService;
    @Autowired
    private NewSysMindMappingService newSysMindMappingService;
    @Autowired
    private NewSysMindMappingDao newSysMindMappingDao;
    @Autowired
    private ApsProcessOperationProcessEquService apsProcessOperationProcessEquService;
    @Autowired
    private RunTaskService runTaskService;
    @Autowired
    private ProcessInstService processInstService;
    @Resource
    private CXAdminFeginClient cxAdminFeginClient;
    @Autowired
    private ApsProductionTechnicalRequirementService apsProductionTechnicalRequirementService;
    @Autowired
    private ApsWorkInProgressInventoryService apsWorkInProgressInventoryService;
    @Autowired
    private ApsReportYearAndMonthService apsReportYearAndMonthService;
    @Autowired
    private ApsReportOrderFinishTableService apsReportOrderFinishTableService;
    @Autowired
    private ApsReportOrderFinishPhotoService apsReportOrderFinishPhotoService;
    @Autowired
    private ApsReportCastRollTableService apsReportCastRollTableService;
    @Autowired
    private ApsReportCastRollPhotoService apsReportCastRollPhotoService;
    @Autowired
    private ApsReportJzProcessTableService apsReportJzProcessTableService;
    @Autowired
    private ApsReportJzProcessPhotoService apsReportJzProcessPhotoService;
    @Autowired
    private ApsReportZjProcessTableService apsReportZjProcessTableService;
    @Autowired
    private ApsReportZjProcessPhotoService apsReportZjProcessPhotoService;
    @Autowired
    private ApsReportThProcessTableService apsReportThProcessTableService;
    @Autowired
    private ApsReportThProcessPhotoService apsReportThProcessPhotoService;
    @Autowired
    private ApsReportOutputServiceImpl apsReportOutputService;
    @Autowired
    private WorkFlowServiceImpl workFlowService;
    @Autowired
    private SysGeneralCRUDService sysGeneralCRUDService;


    public static final String ERROR_MSG = "%s上诉订单的排程交货期大于承诺交货期";
    @Autowired
    private AspCheckItemsServiceImpl aspCheckItemsServiceImpl;

    /**
     * 发布订单排程
     *
     * @param productionOrderIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R publish(List<String> productionOrderIds) {
        if (productionOrderIds.isEmpty()) {
            return R.ok();
        }
        // 如果 订单排程交货期>承诺交货期 抛出异常信息
        List<ApsProductionOrderDo> list = this.list(new LambdaQueryWrapper<ApsProductionOrderDo>()
                .in(ApsProductionOrderDo::getId, productionOrderIds)
                .apply(" SCHEDULEDELIVERYDATE>PROMISEDELIVERYDATE"));
        if (!list.isEmpty()) {
            String collect = list.stream()
                    .map(info -> info.getOrderno() + "-" + info.getCustomname())
                    .collect(Collectors.joining(";"));
            log.error("存在排程交货期大于承诺交货期 的订单：{}", collect);
            return R.error(String.format(ERROR_MSG, collect));
        }

        // 更新工序作业的生产状态和是否锁定=是
        apsProcessOperationDao.publish(productionOrderIds);

        apsProcessOperationProcessEquDao.publish(productionOrderIds);
        // 更新坯料计划的生产状态
        apsBlankOrderDao.publish(productionOrderIds);
        // 更新产品明细的生产状态
        apsProductDetailDao.publish(productionOrderIds);
        // 更新订单的生产状态
        this.baseMapper.publish(productionOrderIds);
        // 根据坯料ID 删除 备份数据
        List<ApsBlankOrderDo> apsBlankOrderDos = apsBlankOrderDao.selectList(new LambdaQueryWrapper<ApsBlankOrderDo>()
                .in(ApsBlankOrderDo::getProductionorderid, productionOrderIds));
        ApsUtils.clearBackup(null);
        return R.ok();
    }

    /**
     * 取消发布订单排程
     *
     * @param productionOrderIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public R publishCancel(List<String> productionOrderIds) {
        // 更新工序作业的生产状态和是否锁定=是
        apsProcessOperationDao.publishCancel(productionOrderIds);
        apsProcessOperationProcessEquDao.publishCancel(productionOrderIds);
        // 更新坯料计划的生产状态
        apsBlankOrderDao.publishCancel(productionOrderIds);
        // 更新产品明细的生产状态
        apsProductDetailDao.publish(productionOrderIds);
        // 更新订单的生产状态
        this.baseMapper.publishCancel(productionOrderIds);
        List<ApsBlankOrderDo> apsBlankOrderDos = apsBlankOrderDao.selectList(new LambdaQueryWrapper<ApsBlankOrderDo>()
                .in(ApsBlankOrderDo::getProductionorderid, productionOrderIds));
        List<String> blankIds = apsBlankOrderDos.stream().map(ApsBlankOrderDo::getId).collect(Collectors.toList());
        // 根据坯料ID 删除 备份数据
        ApsUtils.clearBackup(null);
        return R.ok();
    }

    @Override
    @Transactional
    public R checkAndSaveOrUpdateOrder(CheckAndSaveOrUpdateOrderReq req) {
        //订单信息
        ApsProductionOrderDo apsProductionOrderDo = req.getApsProductionOrderDo();
        String id = apsProductionOrderDo.getId();

        SysUserVo currentUser = CXCommonUtils.getCurrentUser();
        if (productOrderLock.containsKey(id)) {
            log.error("校验-该订单已被：{}提交", productOrderLock.get(id));
            return R.error("该订单已被提交，请刷新页面后重新操作");
        }
        productOrderLock.put(id, currentUser.getId());
        try {
            //数据库中的订单数据
            ApsProductionOrderDo nowApsProductionOrderDo = this.getById(id);
            //页面上的订单数据
            ApsProductionOrderDo oldOrder = req.getOldOrder();
            //如果 评审状态 不一致
            if (!oldOrder.getAuditstatus().equals(nowApsProductionOrderDo.getAuditstatus())) {
                return R.error("该订单已被提交，请刷新页面后重新操作");
            }


            //合并订单信息
            List<ApsProductionMergeOrderDo> apsProductionMergeOrderDoList = req.getApsProductionMergeOrderDoList();
            //产品明细信息
            List<ApsProductDetailVo> apsProductDetailVoList = req.getApsProductDetailVoList();
            //坯料计划信息(坯料计划是一保存的状态，校验直接通过数据库查询)
            List<ApsBlankOrderDo> apsBlankOrderDoList = apsBlankOrderDao.selectList(new QueryWrapper<ApsBlankOrderDo>().lambda().eq(ApsBlankOrderDo::getProductionorderid, apsProductionOrderDo.getId()).orderByDesc(ApsBlankOrderDo::getModifydate));
            //是否需要检验坯料计划是否已排程
            Boolean checkSchedule = req.getCheckSchedule();
            //坯料计划校验等级
            Integer checkLevel = req.getCheckLevel();

            //=========检查坯料计划的个数和状态=============
            if (ObjectUtil.isEmpty(apsBlankOrderDoList)) {
                return R.error("坯料计划至少有一个");
            }
            if (checkLevel == 3) {
                for (int i = 0; i < apsBlankOrderDoList.size(); i++) {
                    if (apsBlankOrderDoList.get(i).getIsstag().equals("是")) {
                        return R.error("坯料计划" + apsBlankOrderDoList.get(i).getBlanknumber() + "还未提交，请先提交坯料计划再提交订单");
                    }
                }
            }

            //提交时需要校验是否已排程
            if (checkSchedule) {
                //如果坯料计划生产状态=待排程；错误提示：坯料计划 {输入物料描述} 还未排程
                for (ApsBlankOrderDo apsBlankOrderDo : apsBlankOrderDoList) {
                    if (ObjectUtil.isNotEmpty(apsBlankOrderDo.getProductstatus()) && apsBlankOrderDo.getProductstatus().equals(SaveConstans.ProductionStatus.TO_BE_SCHEDULED)) {
                        return R.error("坯料计划 " + apsBlankOrderDo.getInputreportdescribe() + " 还未排程");
                    }
                }
                //检查该订单所有作业明细，如果存在冲突，则错误提示：请先解决冲突再发布
                int count = this.baseMapper.selectConflictdesCount(apsProductionOrderDo.getId());
                if (count > 0) {
                    return R.error("请先解决冲突再发布");
                }

//            //============校验承诺交期============
//            //如果承诺交货期为空，错误提示：请填写订单{订单号}{客户简称}的承诺交货期
//            if (ObjectUtil.isEmpty(apsProductionOrderDo.getPromisedeliverydate())) {
//                return R.error("请填写订单" + apsProductionOrderDo.getOrderno() + apsProductionOrderDo.getCustomname() + "的承诺交货期");
//            }
//            if (ObjectUtil.isEmpty(apsProductionOrderDo.getScheduledeliverydate())) {
//                return R.error("排程交货期不能为空");
//            }
//            //如果承诺交货期<排程交货期，错误提示：承诺交货期不能早于排程交货期{排程交货期}
//            if (apsProductionOrderDo.getPromisedeliverydate().compareTo(apsProductionOrderDo.getScheduledeliverydate()) < 0) {
//                return R.error("承诺交货期不能早于排程交货期" + DateUtil.format(apsProductionOrderDo.getScheduledeliverydate(), "yyyy-MM-dd"));
//            }
            }

            //============校验计划输出订单总重量==============
            //检查每个订单产品，如果该订单产品坯料计划输出总重量 不等于 该订单产品订单总数量；
            //错误提示：订单产品 {输入物料描述} 订单总数量与坯料计划输出总重量不一致
            if (ObjectUtil.isEmpty(apsProductDetailVoList) || apsProductDetailVoList.size() <= 0) {
                return R.error("产品明细至少有一个");
            }
//        for (ApsProductDetailVo apsProductDetailVo : apsProductDetailVoList) {
//            if (ObjectUtil.isEmpty(apsProductDetailVo.getTotalordercount()) || ObjectUtil.isEmpty(apsProductDetailVo.getPlanout()) || apsProductDetailVo.getTotalordercount().compareTo(apsProductDetailVo.getPlanout()) != 0) {
//                return R.error("订单产品 " + apsProductDetailVo.getInputmaterialdescription() + " 订单总数量与坯料计划输出总重量不一致");
//            }
//        }

            //查询此订单所有产品明细对应的输出成品的卷数和
//        List<ProductDetailIdAndPlanOutPutRollCountAllVo> planOutPutRollCountAllVos = this.baseMapper.getProductDetailIdAndPlanOutPutRollCountAll(apsProductDetailVoList.get(0).getMainid());
            //检查每个订单产品，如果该订单产品填写了卷数，
            //并且该订单产品对应坯料输出成品的计划输出订单卷数合计不等于订单产品的卷数，
            //错误提示：订单产品 {输入物料描述} 的卷数与坯料计划的计划输出订单卷数不一致
//        for (ApsProductDetailVo apsProductDetailVo : apsProductDetailVoList) {
//            if (ObjectUtil.isNotEmpty(apsProductDetailVo.getRollnum())) {
//                for (ProductDetailIdAndPlanOutPutRollCountAllVo planOutPutRollCountAllVo : planOutPutRollCountAllVos) {
//                    if (planOutPutRollCountAllVo.getProductDetailId().equals(apsProductDetailVo.getId())) {
//                        if (planOutPutRollCountAllVo.getPlanOutPutRollCountAll().equals(apsProductDetailVo.getRollnum())) {
//                            break;
//                        } else {
//                            return R.error("订单产品 " + apsProductDetailVo.getInputmaterialdescription() + " 的卷数与坯料计划的计划输出订单卷数不一致");
//                        }
//                    }
//                }
//            }
//        }

            //===============校验产品明细的长===================
            if (ObjectUtil.isEmpty(apsProductDetailVoList)) {
                return R.error("产品明细至少有一个");
            }

//        //获取产品明细的所有产品类型ID（去重）
//        Set<String> productTypeIds = apsProductDetailVoList.stream().map(ApsProductDetailVo::getProducttypeid).collect(Collectors.toSet());
//        String join = String.join("','", productTypeIds);
//
//        List<ProductTypeIdAndPidVo> productTypeIdAndPidList = this.baseMapper.selectProductTypeIdAndPid(join);
//        if (ObjectUtil.isNotEmpty(productTypeIdAndPidList)) {
//            for (ProductTypeIdAndPidVo productTypeIdAndPidVo : productTypeIdAndPidList) {
//                for (int i = 0; i < apsProductDetailVoList.size(); i++) {
//                    ApsProductDetailVo apsProductDetailVo = apsProductDetailVoList.get(i);
//                    if (apsProductDetailVo.getProducttypeid().equals(productTypeIdAndPidVo.getId())) {
//                        //如果是铝板或铝锭
//                        if (productTypeIdAndPidVo.getPid().equals(SaveConstans.ProductionType.LVBAN_ID) || productTypeIdAndPidVo.getPid().equals(SaveConstans.ProductionType.BANDING_ID)) {
//                            //判断长度是否为空
//                            if (ObjectUtil.isEmpty(apsProductDetailVo.getProlength())) {
//                                return R.error("第" + (i + 1) + "个产品明细，产品类型是铝板或板锭时长度必填");
//                            }
//                        }
//                    }
//                }
//            }
//        }

            //==========校验订单技术要求============
            /**
             * 如果技术要求的订单产品在产品明细中不存在，错误提示：技术要求的订单产品{订单产品}已删除或已变更，请重新选择该技术要求的订单产品
             * 如果有产品明细没有技术要求，错误提示：请填写{订单产品1}，{订单产品2}的技术要求
             * 如果合金成分要求为空，错误提示：请加载合金成分要求
             * 校验所有坯料输出成品合金成分
             *  如果坯料输出成品没有替代合金，并且合金没有加载合金成分要求，错误提示：{合金}合金成分要求没有加载
             *  如果坯料输出成品有替代合金，并且替代合金没有加载合金成分要求，错误提示：{合金}替代合金成分要求没有加载
             * 如果合金有多个合金成分要求，错误提示：{合金}合金成分要求不能有多个
             */
            //已有的产品明细的ID集合
            List<String> nowOrderDetailIdList = apsProductDetailVoList.stream().map(ApsProductDetailVo::getId).collect(Collectors.toList());
            //查询技术要求
            List<ApsProductionTechnicalRequirementDo> apsProductionTechnicalRequirementDoList = apsProductionTechnicalRequirementService.list(new LambdaQueryWrapper<ApsProductionTechnicalRequirementDo>().eq(ApsProductionTechnicalRequirementDo::getOrderid, id));
            //技术要求对应的产品明细ID集合
            List<String> technicalHaveDetailIdList = new LinkedList<>();
            for (ApsProductionTechnicalRequirementDo apsProductionTechnicalRequirementDo : apsProductionTechnicalRequirementDoList) {
                if (ObjectUtil.isNotEmpty(apsProductionTechnicalRequirementDo.getOrderdetailids())) {
                    String[] split1 = apsProductionTechnicalRequirementDo.getOrderdetailids().split(",");
                    technicalHaveDetailIdList.addAll(Arrays.asList(split1));
                    String[] split2 = apsProductionTechnicalRequirementDo.getOrderdetailnames().split(",");
                    for (int i = 0; i < split1.length; i++) {
                        String orderDetailId = split1[i];
                        if (!nowOrderDetailIdList.contains(orderDetailId)) {
                            return R.error("技术要求的订单产品" + split2[i] + "已删除或已变更，请重新选择该技术要求的订单产品");
                        }
                    }
                }
            }
            for (String nowOrderDetailId : nowOrderDetailIdList) {
                if (!technicalHaveDetailIdList.contains(nowOrderDetailId)) {
                    ApsProductDetailVo apsProductDetailVo = apsProductDetailVoList.stream().filter(item -> item.getId().equals(nowOrderDetailId)).findFirst().orElse(null);
                    return R.error("请填写" + apsProductDetailVo.getInputmaterialdescription() + "的技术要求");
                }
            }

            List<ApsOrderAlloyCompositionDo> apsOrderAlloyCompositionDoList = apsOrderAlloyCompositionService.list(new LambdaQueryWrapper<ApsOrderAlloyCompositionDo>().eq(ApsOrderAlloyCompositionDo::getProductionorderid, id));
            if (ObjectUtil.isEmpty(apsOrderAlloyCompositionDoList)) {
                return R.error("请加载合金成分要求");
            }
            List<String> productDetailAlloyList = apsProductDetailVoList.stream().map(ApsProductDetailVo::getAlloy).collect(Collectors.toList());
            for (String productDetailAlloy : productDetailAlloyList) {
                if (ObjectUtil.isEmpty(apsOrderAlloyCompositionDoList.stream().filter(item -> item.getAlloy().equals(productDetailAlloy)).findFirst().orElse(null))) {
                    return R.error(productDetailAlloy + "合金成分要求没有加载");
                }

            }

            List<String> changeAlloyList = this.baseMapper.selectChangeAlloyByOrderId(id);
            for (String changeAlloy : changeAlloyList) {
                if (ObjectUtil.isEmpty(apsOrderAlloyCompositionDoList.stream().filter(item -> item.getAlloy().equals(changeAlloy)).findFirst().orElse(null))) {
                    return R.error(changeAlloy + "替代合金成分要求没有加载");
                }
            }

            Map<String, Integer> alloyCountMap = new HashMap<>();
            apsOrderAlloyCompositionDoList.forEach(item -> {
                if (alloyCountMap.containsKey(item.getAlloy())) {
                    alloyCountMap.put(item.getAlloy(), alloyCountMap.get(item.getAlloy()) + 1);
                } else {
                    alloyCountMap.put(item.getAlloy(), 1);
                }
            });
            for (String key : alloyCountMap.keySet()) {
                if (alloyCountMap.get(key) > 1) {
                    return R.error(key + "合金成分要求不能有多个");
                }
            }


            /**
             * 校验每个订单产品
             * 如果订单产品暂不评审=否，并且坯料计划输出总重量 = 0，则错误提示：订单产品 {输入物料描述}坯料计划未填写
             * 如果订单产品暂不评审=是，并且坯料计划输出总重量 > 0，则错误提示：订单产品 {输入物料描述}暂不评审，不应该填写坯料计划
             */
            for (ApsProductDetailVo apsProductDetailVo : apsProductDetailVoList) {
                if (apsProductDetailVo.getDeleted().equals("0")) {
                    if (apsProductDetailVo.getNotyetreview().equals("否") && (ObjectUtil.isEmpty(apsProductDetailVo.getPlanout()) || apsProductDetailVo.getPlanout().toString().equals("0"))) {
                        return R.error("订单产品 " + apsProductDetailVo.getInputmaterialdescription() + "坯料计划未填写");
                    }
                    if (apsProductDetailVo.getNotyetreview().equals("是") && ObjectUtil.isNotEmpty(apsProductDetailVo.getPlanout()) && !apsProductDetailVo.getPlanout().toString().equals("0")) {
                        return R.error("订单产品 " + apsProductDetailVo.getInputmaterialdescription() + "暂不评审，不应该填写坯料计划");
                    }
                }
            }


            List<ApsProductDetailDo> productDetailDoList = BeanUtil.copyToList(apsProductDetailVoList, ApsProductDetailDo.class);
            //================循环校验坯料计划===============
            for (int i = 0; i < apsBlankOrderDoList.size(); i++) {
                //如果坯料计划已发布，则不再校验
                if (Integer.parseInt(apsBlankOrderDoList.get(i).getProductstatus()) > 20) {
                    continue;
                }
                CheckAndSaveOrUpdateBlankReq checkAndSaveOrUpdateBlankReq = new CheckAndSaveOrUpdateBlankReq();
                checkAndSaveOrUpdateBlankReq.setApsBlankOrderDo(apsBlankOrderDoList.get(i));
                checkAndSaveOrUpdateBlankReq.setApsProcessOutputProductDoList(apsProcessOutputProductService.list(new QueryWrapper<ApsProcessOutputProductDo>().lambda().eq(ApsProcessOutputProductDo::getBlankid, apsBlankOrderDoList.get(i).getId())));
                checkAndSaveOrUpdateBlankReq.setApsProductDetailDoList(productDetailDoList);
                checkAndSaveOrUpdateBlankReq.setCheckLevel(checkLevel);
                if (checkSchedule) {
                    checkAndSaveOrUpdateBlankReq.setCheckDevice(true);
                }

                R r = apsBlankOrderService.checkBlankOrder(checkAndSaveOrUpdateBlankReq, i + 1);
                if (!r.getCode().equals("200")) {
                    return R.error(r.getMsg());
                }
            }

            //================校验通过，保存或更新订单相关信息=====================
            if (req.getIsNeedSave()) {
                //获取当前用户的所属工厂
//            SysUserVo currentUser = CXCommonUtils.getCurrentUser();
                String tenantId = CXCommonUtils.getCurrentUserFactoryId(currentUser);

                //保存主表信息
                apsProductionOrderDo.setTenantid(tenantId);
                this.saveOrUpdate(apsProductionOrderDo);

                //保存产品明细子表
                for (ApsProductDetailVo apsProductDetailVo : apsProductDetailVoList) {
                    apsProductDetailVo.setTenantid(tenantId);
                }
                apsProductDetailService.saveOrUpdateBatch(productDetailDoList);

                //保存合并订单子表
                if (ObjectUtil.isNotEmpty(apsProductionMergeOrderDoList) && apsProductionMergeOrderDoList.size() > 0) {
                    for (ApsProductionMergeOrderDo apsProductionMergeOrderDo : apsProductionMergeOrderDoList) {
                        apsProductionMergeOrderDo.setTenantid(tenantId);
                    }
                    apsProductionMergeOrderService.saveOrUpdateBatch(apsProductionMergeOrderDoList);
                }
            }

            if (req.getIsNeedPublish()) {
                //=============发布排程================
                List<String> blankIds = apsBlankOrderDoList.stream().filter(item -> item.getProductstatus().equals(SaveConstans.ProductionStatus.TO_BE_PUBLISHED)).map(ApsBlankOrderDo::getId).collect(Collectors.toList());
                if (ObjectUtil.isNotEmpty(blankIds)) {
                    R publish = apsBlankOrderService.publish(blankIds);
                    if (!publish.getCode().equals("200")) {
                        throw new RuntimeException(publish.getMsg());
                    }
                } else {
                    if (ObjectUtil.isNotEmpty(apsBlankOrderDoList)) {
                        //更新生产状态
                        CommonUpdateProductionStatusReq request = new CommonUpdateProductionStatusReq();
                        request.setBlankId(apsBlankOrderDoList.get(0).getId());
                        apsProcessOperationProcessEquService.updateProductionStatus(request);
                    }
                }
            } else {
                if (ObjectUtil.isNotEmpty(apsBlankOrderDoList)) {
                    //更新生产状态
                    CommonUpdateProductionStatusReq request = new CommonUpdateProductionStatusReq();
                    request.setBlankId(apsBlankOrderDoList.get(0).getId());
                    apsProcessOperationProcessEquService.updateProductionStatus(request);
                }
            }

            if (req.getIsNeedRunTask()) {
                String processinstid = nowApsProductionOrderDo.getProcessinstid();
                RunTaskDo runTaskDo = runTaskService.getOne(new LambdaQueryWrapper<RunTaskDo>().eq(BaseDo::getDeleted, "0")
                        .eq(RunTaskDo::getProcessinstid, processinstid)
                        .in(RunTaskDo::getTaskstatus, "10", "20")
                        .orderByDesc(BaseDo::getCreatedate), false);
                RunTaskVo runTaskVo = new RunTaskVo();
                BeanUtils.copyProperties(runTaskDo, runTaskVo);
                runTaskVo.setProcessInstId(processinstid);
                runTaskVo.setBusinesstableid(apsProductionOrderDo.getId());
                runTaskVo.setProcesstitle("订单评审");
                runTaskVo.setProcessdefid("order_review");
                runTaskVo.setAuditoperation("10");
                runTaskVo.setTaskstatusname("待处理");
                try {
                    workFlowService.runTask(runTaskVo, true);
                } catch (Exception e) {
                    log.error("流程更新失败");
                    throw new RuntimeException("执行流程失败，请刷新页面后重试");
                }
            }
        } finally {
            log.debug("校验-订单提交完毕，从map中清空当前订单锁，订单ID:{}", id);
            productOrderLock.remove(id);
        }

        return R.ok();
    }

    /*
    订单未及时评审提醒
     */
    @Override
    public void orderOuttimeAudit() {
        List<ApsProductionOrderDo> apsProductionOrderDos = this.baseMapper.getOrderOuttimeAudit();
        for (ApsProductionOrderDo apsProductionOrderDo : apsProductionOrderDos) {
            //系统通知（移动端和PC端个人工作台）
            CXCommonUtils.sendNotify(ORDEROUTTIMEAUDIT_TITLE, String.format(ORDEROUTTIME_AUDIT_CONTENT, apsProductionOrderDo.getOrderno()), null, Arrays.asList(apsProductionOrderDo.getCreateuserid().split(",")), apsProductionOrderDo.getId(), ORDEROUTTIME_AUDIT, false);

            //邮件提醒
            if (StringUtils.isNotEmpty(apsProductionOrderDo.getModifyusername())) {
                MailDo mailDo = new MailDo();
                mailDo.setReceiveEmail(apsProductionOrderDo.getModifyusername().split(","));
                mailDo.setNeedTransReceive(false);
                mailDo.setCcEmail(new String[]{});
                mailDo.setSubject(ORDEROUTTIMEAUDIT_TITLE);
                mailDo.setContent(String.format(ORDEROUTTIME_AUDIT_CONTENT, apsProductionOrderDo.getOrderno()));
                autoCommonFeginClient.sendHtmlMail(mailDo);
            }
        }
    }

    /*
    辅料申购提醒
     */
    @Override
    public void auxiliaryMaterial() {
        List<ApsProductionOrderDo> apsProductionOrderDos = this.baseMapper.getAuxiliaryMaterial();
        for (ApsProductionOrderDo apsProductionOrderDo : apsProductionOrderDos) {
            //系统通知（移动端和PC端个人工作台）
            CXCommonUtils.sendNotify(AUXILIARYMATERIAL_TITLE, String.format(AUXILIARYMATERIAL_CONTENT, apsProductionOrderDo.getOrderno()), null, Arrays.asList(apsProductionOrderDo.getCreateuserid().split(",")), apsProductionOrderDo.getId(), AUXILIARYMATERIAL_REMIND, false);

            //邮件提醒
            if (StringUtils.isNotEmpty(apsProductionOrderDo.getModifyusername())) {
                MailDo mailDo = new MailDo();
                mailDo.setReceiveEmail(apsProductionOrderDo.getModifyusername().split(","));
                mailDo.setNeedTransReceive(false);
                mailDo.setCcEmail(new String[]{});
                mailDo.setSubject(AUXILIARYMATERIAL_TITLE);
                mailDo.setContent(String.format(AUXILIARYMATERIAL_CONTENT, apsProductionOrderDo.getOrderno()));
                autoCommonFeginClient.sendHtmlMail(mailDo);
            }
        }
    }

    @Override
    @Transactional
    @Deprecated
    public R changeOrder(ApsProductionOrderDo req) {
        if (ObjectUtil.isEmpty(req.getId())) {
            return R.error("订单Id不能为空");
        }
        //订单评审状态=待计划评审，订单调整日期=今天，
        this.baseMapper.changeOrderById(req.getId());

        //撤回发布订单所有坯料计划的排程结果，参见【订单排程/一键自动排程/撤回发布排程结果】
        List<String> orderIdList = new LinkedList<>();
        orderIdList.add(req.getId());
        R r = this.publishCancel(orderIdList);
        if (!r.getCode().equals("200")) {
            return R.error(r.getMsg());
        }

        return R.ok();
    }

    @Override
    @Transactional
    public R deleteOrder(DeleteOrderVo req) {
        if (ObjectUtil.isEmpty(req.getOrderId())) {
            return R.error("订单ID不能为空");
        }

        List<ApsBlankOrderDo> blankList = apsBlankOrderService.list(new QueryWrapper<ApsBlankOrderDo>().lambda().eq(ApsBlankOrderDo::getProductionorderid, req.getOrderId()));
        //清除排程备份
        if (req.getNeedDelBackup()) {
            //查询订单下的坯料计划

            List<String> blankIdList = blankList.stream().map(ApsBlankOrderDo::getId).collect(Collectors.toList());
            SysUserVo currentUser = CXCommonUtils.getCurrentUser();
            String factoryId = CXCommonUtils.getCurrentUserFactoryId(currentUser);
            apsProcessOperationBackupDao.deletedByBlankId(blankIdList, factoryId);
            apsProcessOperationProcessEquBackupDao.deletedByBlankId(blankIdList, factoryId);
        }

        //删除该订单，包括订单明细，合并订单及明细，坯料计划，工序作业
        //删除订单
        this.removeById(req.getOrderId());

        //删除订单明细子表
        apsProductDetailService.remove(new QueryWrapper<ApsProductDetailDo>().lambda().eq(ApsProductDetailDo::getMainid, req.getOrderId()));

        //删除合并订单子表
        apsProductionMergeOrderService.remove(new QueryWrapper<ApsProductionMergeOrderDo>().lambda().eq(ApsProductionMergeOrderDo::getMainid, req.getOrderId()));

        //删除合计成分要求子表
        apsOrderAlloyCompositionService.remove(new QueryWrapper<ApsOrderAlloyCompositionDo>().lambda().eq(ApsOrderAlloyCompositionDo::getProductionorderid, req.getOrderId()));

        //遍历删除坯料计划子表
        for (ApsBlankOrderDo apsBlankOrderDo : blankList) {
            apsBlankOrderService.removeBlankOrderAndChild(apsBlankOrderDo);
        }

        return R.ok();
    }

    /*
    作业延期提醒
     */
    @Override
    public void processDelay() {
        List<ApsProductionOrderDo> apsProductionOrderDos = this.baseMapper.getProcessDelay();
        List<ApsProductionOrderDo> scjhzrs = new ArrayList<>();//获取各工厂生产计划主任
        if (apsProductionOrderDos.size() > 0) {
            scjhzrs = this.baseMapper.getScjhzr();
        }
        for (ApsProductionOrderDo apsProductionOrderDo : apsProductionOrderDos) {
            //系统通知（移动端和PC端个人工作台）
            CXCommonUtils.sendNotify(PROCESSDELAY_TITLE, String.format(PROCESSDELAY_CONTENT, apsProductionOrderDo.getOrderno()), null, Arrays.asList(apsProductionOrderDo.getCreateuserid().split(",")), apsProductionOrderDo.getId(), PROCESSDELAY_REMIND, false);

            //邮件提醒
            if (StringUtils.isNotEmpty(apsProductionOrderDo.getModifyusername())) {
                MailDo mailDo = new MailDo();
                mailDo.setReceiveEmail(apsProductionOrderDo.getModifyusername().split(","));
                mailDo.setNeedTransReceive(false);
                mailDo.setCcEmail(new String[]{});
                mailDo.setSubject(PROCESSDELAY_TITLE);
                mailDo.setContent(String.format(PROCESSDELAY_CONTENT, apsProductionOrderDo.getOrderno()));
                autoCommonFeginClient.sendHtmlMail(mailDo);
            }
        }
    }

    /*
    报工不合格提醒
     */
    @Override
    public void reportUnqualify() {
        List<ApsProductionOrderDo> apsProductionOrderDos = this.baseMapper.getReportUnqualify();
        if (apsProductionOrderDos.isEmpty()) {
            return;
        }
        //缺陷字典
        List<SysDictDo> defectTypes = apsReportOutputService.getQualityDefectsDictsByType();
        //所有的坯料计划id
        List<String> blankIds = apsProductionOrderDos.stream().map(ApsProductionOrderDo::getCustomid).distinct().collect(Collectors.toList());
        //坯料输出成品
        List<ApsProcessOutputProductDo> apsProcessOutputProductDos = apsProcessOutputProductService.list(new LambdaQueryWrapper<ApsProcessOutputProductDo>()
                .in(ApsProcessOutputProductDo::getBlankid, blankIds)
                .eq(BaseDo::getDeleted, "0")
                .orderByDesc(ApsProcessOutputProductDo::getModifydate));

        //按照订单分组
        Map<String, List<ApsProductionOrderDo>> orderList = apsProductionOrderDos.stream().collect(Collectors.groupingBy(e -> e.getId()));
        final String[] content = {""};
        orderList.forEach((k, olist) -> {
            //系统通知（移动端和PC端个人工作台）
            CXCommonUtils.sendNotify(REPORTUNQUALIFY_TITLE, REPORTUNQUALIFY_CONTENT, null, Arrays.asList(olist.get(0).getCreateuserid().split(",")), k, REPORTUNQUALIFY_REMIND, false);

            //邮件内容
            content[0] = "<div>报工检验不合格，请及时调整计划</div>" +
                    "<div>客户【" + olist.get(0).getCustomname() + "】【" + DateUtil.format(olist.get(0).getOrderdate(), DATE_PATTERN_YMD) + "】的订单【" + olist.get(0).getOrderno() + "】</div>";
            //按照坯料计划分组
            Map<String, List<ApsProductionOrderDo>> blankList = olist.stream().collect(Collectors.groupingBy(o -> o.getCustomid()));
            blankList.forEach((b, blist) -> {
                List<ApsProcessOutputProductDo> apsProcessOutputProductDoList = apsProcessOutputProductDos.stream().filter(out -> out.getBlankid().equals(b)).collect(Collectors.toList());
                for (ApsProcessOutputProductDo apsProcessOutputProductDo : apsProcessOutputProductDoList) {
                    content[0] += "<div>产品【" + apsProcessOutputProductDo.getProductname() + "】</div>";
                }
            });

            for (ApsProductionOrderDo apsProductionOrderDo : olist) {
                content[0] += "<div>批次号【" + apsProductionOrderDo.getCustomwarehouse() + "】工序【" + apsProductionOrderDo.getCustomorderno() + "】检验等级【" + apsProductionOrderDo.getCustomordertype() + "】</div>";
                content[0] += "<div>主要缺陷【" + handleDefect(apsProductionOrderDo.getRemark(), defectTypes) + "】</div>";
                content[0] += "<div>次要缺陷【" + handleDefect(apsProductionOrderDo.getRoption(), defectTypes) + "】</div>";
            }

            //邮件提醒
            if (StringUtils.isNotEmpty(olist.get(0).getModifyusername())) {
                MailDo mailDo = new MailDo();
                mailDo.setReceiveEmail(olist.get(0).getModifyusername().split(","));
                mailDo.setNeedTransReceive(false);
                mailDo.setCcEmail(new String[]{});
                mailDo.setSubject(REPORTUNQUALIFY_TITLE);
                mailDo.setContent(content[0]);
                autoCommonFeginClient.sendHtmlMail(mailDo);
            }
        });
    }

    /**
     * 处理主要缺陷/次要缺陷字典值显示为逗号分隔的文本
     *
     * @param defect
     * @return
     */
    private String handleDefect(String defect, List<SysDictDo> dictDos) {
        String result = "";
        if (org.apache.commons.lang.StringUtils.isNotBlank(defect)) {
            List<String> dictNameList = new ArrayList<>();
            String[] valuesToLookup = defect.split(",");
            for (SysDictDo sysDictDo : dictDos) {
                for (String value : valuesToLookup) {
                    if (sysDictDo.getId().equals(value.trim())) {
                        dictNameList.add(sysDictDo.getName());
                        // 一旦找到匹配的值，就不需要再检查该字典项的其他值了
                        break;
                    }
                }
            }
            if (!dictNameList.isEmpty()) {
                result = String.join(",", dictNameList);
            }
        }
        return result;
    }

    /*
    根据保存前数据的 id 获取撤回前版本所有主子表信息
     */
    @Override
    public R saveHistoryInfo(String id) {
        //获取保存前主子表信息
        ApsProductionOrderDo apsProductionOrderDo = this.baseMapper.selectDataInfo(id);
        if (apsProductionOrderDo != null) {
            //创建一个map集合
            Map<String, String> ApsProductDetailMap = new HashMap<>();

            ApsProductionOrderHistoryDo apsProductionOrderHistoryDo = new ApsProductionOrderHistoryDo();
            BeanUtils.copyProperties(apsProductionOrderDo, apsProductionOrderHistoryDo);
            apsProductionOrderHistoryDo.setHistorytableid(apsProductionOrderDo.getId());
            apsProductionOrderHistoryDo.setId(SecurityUtil.getUUID());
            apsProductionOrderHistoryService.save(apsProductionOrderHistoryDo);

            //获取合并订单列表
            List<ApsProductionMergeOrderDo> apsProductionMergeOrderDoList = apsProductionMergeOrderDao.selectApsProductionMergeOrderDoByMainId(apsProductionOrderDo.getId());
            if (apsProductionMergeOrderDoList != null && apsProductionMergeOrderDoList.size() > 0) {
                for (ApsProductionMergeOrderDo apsProductionMergeOrderDo : apsProductionMergeOrderDoList) {
                    //将apsProductionMergeOrderDo的数据复制到apsProductionMergeOrderHistoryDo
                    ApsProductionMergeOrderHistoryDo apsProductionMergeOrderHistoryDo = new ApsProductionMergeOrderHistoryDo();
                    BeanUtils.copyProperties(apsProductionMergeOrderDo, apsProductionMergeOrderHistoryDo);
                    //订单表和历史版本表关联
                    apsProductionMergeOrderHistoryDo.setMainid(apsProductionOrderHistoryDo.getId());
                    apsProductionMergeOrderHistoryDo.setId(SecurityUtil.getUUID());
                    //保存apsProductionMergeOrderHistoryDo
                    apsProductionMergeOrderHistoryService.save(apsProductionMergeOrderHistoryDo);
                }

            }


            //获取产品明细
            List<ApsProductDetailDo> apsProductDetailDoList = apsProductDetailDao.getProductDetailByMainId(apsProductionOrderDo.getId());
            if (apsProductDetailDoList != null && apsProductDetailDoList.size() > 0) {

                for (ApsProductDetailDo apsProductDetailDo : apsProductDetailDoList) {
                    //将apsProductDetailDo的数据复制到apsProductDetailHistoryDo
                    ApsProductDetailHistoryDo apsProductDetailHistoryDo = new ApsProductDetailHistoryDo();
                    BeanUtils.copyProperties(apsProductDetailDo, apsProductDetailHistoryDo);
                    //关联历史版本主表 id
                    apsProductDetailHistoryDo.setMainid(apsProductionOrderHistoryDo.getId());
                    apsProductDetailHistoryDo.setId(SecurityUtil.getUUID());

                    //保存aps
                    apsProductDetailHistoryService.save(apsProductDetailHistoryDo);

                    //通过产品明细 id  获取 坯料输出成品 aps_process_output_product （关联id：PRODUCTID）
                    List<ApsProcessOutputProductDo> apsProcessOutputProductDoList = apsProcessOutputProductDao.getProcessOutputProductByProductid(apsProductDetailDo.getId());
                    if (apsProcessOutputProductDoList != null && apsProcessOutputProductDoList.size() > 0) {

                        for (ApsProcessOutputProductDo apsProcessOutputProductDo : apsProcessOutputProductDoList) {
                            //向ApsProductDetailMap集合中插入产品明细数据的老 id 和历史版本对应数据的新 id
                            ApsProductDetailMap.put(apsProcessOutputProductDo.getId(), apsProductDetailHistoryDo.getId());
                        }
                    }
                }
            }
            //获取技术要求
            List<ApsProductionTechnicalRequirementDo> apsProductionTechnicalRequirementDoList = apsProductionTechnicalRequirementDao.selectByOrderid(apsProductionOrderDo.getId());
            if (apsProductionTechnicalRequirementDoList != null && apsProductionTechnicalRequirementDoList.size() > 0) {
                for (ApsProductionTechnicalRequirementDo apsProductionTechnicalRequirementDo : apsProductionTechnicalRequirementDoList) {
                    ApsProductionTechnicalRequirementHistoryDo apsProductionTechnicalRequirementHistoryDo = new ApsProductionTechnicalRequirementHistoryDo();
                    BeanUtils.copyProperties(apsProductionTechnicalRequirementDo, apsProductionTechnicalRequirementHistoryDo);
                    apsProductionTechnicalRequirementHistoryDo.setOrderid(apsProductionOrderHistoryDo.getId());
                    apsProductionTechnicalRequirementHistoryDo.setId(SecurityUtil.getUUID());
                    apsProductionTechnicalRequirementHistoryService.save(apsProductionTechnicalRequirementHistoryDo);
                }
            }
            //获取合金成分要求
            List<ApsOrderAlloyCompositionDo> apsOrderAlloyCompositionDoList = apsOrderAlloyCompositionDao.getAlloyCompositionByProductionorderId(apsProductionOrderDo.getId());

            if (apsOrderAlloyCompositionDoList != null && apsOrderAlloyCompositionDoList.size() > 0) {

                for (ApsOrderAlloyCompositionDo apsOrderAlloyCompositionDo : apsOrderAlloyCompositionDoList) {
                    ApsOrderAlloyCompositionHistoryDo apsOrderAlloyCompositionHistoryDo = new ApsOrderAlloyCompositionHistoryDo();
                    BeanUtils.copyProperties(apsOrderAlloyCompositionDo, apsOrderAlloyCompositionHistoryDo);
                    apsOrderAlloyCompositionHistoryDo.setProductionorderid(apsProductionOrderHistoryDo.getId());
                    apsOrderAlloyCompositionHistoryDo.setId(SecurityUtil.getUUID());
                    apsOrderAlloyCompositionHistoryService.save(apsOrderAlloyCompositionHistoryDo);
                }
            }
            //获取坯料计划
            List<ApsBlankOrderDo> apsBlankOrderDoList = apsBlankOrderDao.selectBlankOrderByProductionorderId(apsProductionOrderDo.getId());

            if (apsBlankOrderDoList != null && apsBlankOrderDoList.size() > 0) {

                for (ApsBlankOrderDo apsBlankOrderDo : apsBlankOrderDoList) {
                    ApsBlankOrderHistoryDo apsBlankOrderHistoryDo = new ApsBlankOrderHistoryDo();
                    BeanUtils.copyProperties(apsBlankOrderDo, apsBlankOrderHistoryDo);
                    apsBlankOrderHistoryDo.setProductionorderid(apsProductionOrderHistoryDo.getId());
                    apsBlankOrderHistoryDo.setId(SecurityUtil.getUUID());
                    apsBlankOrderHistoryService.save(apsBlankOrderHistoryDo);


                    //根据坯料计划id获取 坯料输出成品  aps_process_output_product子表数据
                    List<ApsProcessOutputProductDo> apsProcessOutputProductDoList = apsProcessOutputProductDao.getProcessOutputProductByBlankId(apsBlankOrderDo.getId());
                    if (apsProcessOutputProductDoList != null && apsProcessOutputProductDoList.size() > 0) {
                        for (ApsProcessOutputProductDo apsProcessOutputProductDo : apsProcessOutputProductDoList) {
                            ApsProcessOutputProductHistoryDo apsProcessOutputProductHistoryDo = new ApsProcessOutputProductHistoryDo();
                            BeanUtils.copyProperties(apsProcessOutputProductDo, apsProcessOutputProductHistoryDo);
                            //ApsProductDetailMap不为 null 则 如果键为apsProcessOutputProductDo.getId() 数据存在 map 中 则获取到其值 并且赋值到productid 字段
                            if (ApsProductDetailMap != null && ApsProductDetailMap.containsKey(apsProcessOutputProductDo.getId())) {
                                apsProcessOutputProductHistoryDo.setProductid(ApsProductDetailMap.get(apsProcessOutputProductDo.getId()));
                            }
                            apsProcessOutputProductHistoryDo.setBlankid(apsBlankOrderHistoryDo.getId());
                            apsProcessOutputProductHistoryDo.setId(SecurityUtil.getUUID());
                            apsProcessOutputProductHistoryService.save(apsProcessOutputProductHistoryDo);

                        }
                    }

                    //根据工序作业 id 获取工艺路线图数据 赋值历史表的坯料计划 id
                    List<NewSysMindMappingDo> sysMindMappingDoList = newSysMindMappingDao.getSysMindMappingByMainId(apsBlankOrderDo.getId());

                    if (sysMindMappingDoList != null && sysMindMappingDoList.size() > 0) {
                        for (NewSysMindMappingDo sysMindMappingDo : sysMindMappingDoList) {
                            NewSysMindMappingDo newSysMindMappingDo = new NewSysMindMappingDo();
                            BeanUtils.copyProperties(sysMindMappingDo, newSysMindMappingDo);
                            newSysMindMappingDo.setBsid(apsBlankOrderHistoryDo.getId());
                            newSysMindMappingDo.setId(SecurityUtil.getUUID());
                            newSysMindMappingService.save(newSysMindMappingDo);
                        }
                    }

                    //根据坯料计划id获取 工序作业  aps_process_operation 子表数据
                    List<ApsProcessOperationDo> apsProcessOperationDoList = apsProcessOperationDao.getProcessOperationByBlankId(apsBlankOrderDo.getId());

                    if (apsProcessOperationDoList != null && apsProcessOperationDoList.size() > 0) {
                        for (ApsProcessOperationDo apsProcessOperationDo : apsProcessOperationDoList) {
                            ApsProcessOperationHistoryDo apsProcessOperationHistoryDo = new ApsProcessOperationHistoryDo();
                            BeanUtils.copyProperties(apsProcessOperationDo, apsProcessOperationHistoryDo);
                            apsProcessOperationHistoryDo.setBlankid(apsBlankOrderHistoryDo.getId());
                            apsProcessOperationHistoryDo.setId(SecurityUtil.getUUID());
                            apsProcessOperationHistoryService.save(apsProcessOperationHistoryDo);

                            NewSysMindMappingDo newSysMindMappingDo = newSysMindMappingDao.getDataInfo(apsBlankOrderHistoryDo.getId(), apsProcessOperationHistoryDo.getCraftstepid(), apsProcessOperationHistoryDo.getLevel());
                            if (newSysMindMappingDo != null) {
                                //更改newSysMindMappingDo 中的 id 为apsProcessOperationHistoryDo.getId()
                                newSysMindMappingDao.updateDataInfo(newSysMindMappingDo.getId(), apsProcessOperationHistoryDo.getId());
                            }
                            //根据工序作业 id 获取 输出物料 aps_process_operation_out_mater
                            List<ApsProcessOperationOutMaterDo> apsProcessOperationOutMaterDoList = apsProcessOperationOutMaterDao.getProcessOperationOutMaterByMainId(apsProcessOperationDo.getId());
                            if (apsProcessOperationOutMaterDoList != null && apsProcessOperationOutMaterDoList.size() > 0) {
                                for (ApsProcessOperationOutMaterDo apsProcessOperationOutMaterDo : apsProcessOperationOutMaterDoList) {
                                    ApsProcessOperationOutMaterHistoryDo apsProcessOperationOutMaterHistoryDo = new ApsProcessOperationOutMaterHistoryDo();
                                    BeanUtils.copyProperties(apsProcessOperationOutMaterDo, apsProcessOperationOutMaterHistoryDo);
                                    apsProcessOperationOutMaterHistoryDo.setMainid(apsProcessOperationHistoryDo.getId());
                                    apsProcessOperationOutMaterHistoryDo.setId(SecurityUtil.getUUID());
                                    apsProcessOperationOutMaterHistoryService.save(apsProcessOperationOutMaterHistoryDo);
                                }
                            }
                            //根据工序作业 id 获取 可选设备 aps_process_operation_equ
                            List<ApsProcessOperationEquDo> apsProcessOperationEquDoList = apsProcessOperationEquDao.getProcessOperationEquByMainId(apsProcessOperationDo.getId());

                            if (apsProcessOperationEquDoList != null && apsProcessOperationEquDoList.size() > 0) {
                                for (ApsProcessOperationEquDo apsProcessOperationEquDo : apsProcessOperationEquDoList) {
                                    ApsProcessOperationEquHistoryDo apsProcessOperationEquHistoryDo = new ApsProcessOperationEquHistoryDo();
                                    BeanUtils.copyProperties(apsProcessOperationEquDo, apsProcessOperationEquHistoryDo);
                                    apsProcessOperationEquHistoryDo.setMainid(apsProcessOperationHistoryDo.getId());
                                    apsProcessOperationEquHistoryDo.setId(SecurityUtil.getUUID());
                                    apsProcessOperationEquHistoryService.save(apsProcessOperationEquHistoryDo);
                                }
                            }


                        }
                    }

                    //获取 以上新增的工艺路线图数据
                    List<NewSysMindMappingDo> newSysMindMappingDoList = newSysMindMappingDao.getSysMindMappingByMainId(apsBlankOrderHistoryDo.getId());
                    if (newSysMindMappingDoList != null && newSysMindMappingDoList.size() > 0) {
                        // 获取列表中level的最大值
                        int maxLevel = 0;
                        for (NewSysMindMappingDo mapping : newSysMindMappingDoList) {
                            if (mapping.getLevel() > maxLevel) {
                                maxLevel = mapping.getLevel();
                            }
                        }
                        // 遍历列表，根据不同的level设置parentid
                        for (NewSysMindMappingDo mapping : newSysMindMappingDoList) {
                            int currentLevel = mapping.getLevel();
                            if (currentLevel == 2) {
                                String parentId = getIdByLevel(newSysMindMappingDoList, 0);
                                mapping.setParentid(parentId);
                                newSysMindMappingService.updateById(mapping);
                            } else if (currentLevel == 3) {
                                String parentId = getIdByLevel(newSysMindMappingDoList, 2);
                                mapping.setParentid(parentId);
                                newSysMindMappingService.updateById(mapping);
                            } else if (currentLevel == 4) {
                                String parentId = getIdByLevel(newSysMindMappingDoList, 3);
                                mapping.setParentid(parentId);
                                newSysMindMappingService.updateById(mapping);
                            } else if (currentLevel > 4 && currentLevel <= maxLevel) {
                                String parentId = getIdByLevel(newSysMindMappingDoList, currentLevel - 1);
                                mapping.setParentid(parentId);
                                newSysMindMappingService.updateById(mapping);
                            }
                        }
                    }
                }
            }
        }
        return R.ok();
    }

    // 根据level获取对应的id
    private String getIdByLevel(List<NewSysMindMappingDo> mappingList, int level) {
        for (NewSysMindMappingDo mapping : mappingList) {
            if (mapping.getLevel() == level) {
                return mapping.getId();
            }
        }
        return null;
    }

    @Override
    public R haveBeChanged(OrderHaveBeChangedReq req) {
        //当前页面的订单数据
        ApsProductionOrderDo oldApsProductionOrderDo = req.getApsProductionOrderDo();

        //数据库中的订单数据
        ApsProductionOrderDo nowApsProductionOrderDo = this.getById(req.getOrderId());

        //如果 评审状态 不一致
        if (!oldApsProductionOrderDo.getAuditstatus().equals(nowApsProductionOrderDo.getAuditstatus())) {
            return R.error("该订单已被其他人提交，不能保存或提交");
        }

        return R.ok();
    }

    @Override
    @Transactional
    public R closeOrder() {
        //查询所有 订单评审状态=已发布计划，生产状态=已完工 的订单
        List<ApsProductionOrderDo> productionOrderDoList = this.list(new QueryWrapper<ApsProductionOrderDo>().lambda()
                .eq(ApsProductionOrderDo::getAuditstatus, "已发布计划")
                .eq(ApsProductionOrderDo::getProductionstatus, "50"));
        if (ObjectUtil.isEmpty(productionOrderDoList)) {
            return R.ok();
        }

        //需要更新的流程实例ID集合
        List<String> processInstIdList = productionOrderDoList.stream().map(ApsProductionOrderDo::getProcessinstid).collect(Collectors.toList());

        if (ObjectUtil.isEmpty(processInstIdList)) {
            return R.ok();
        }

        List<RunTaskDo> needUpdateList = new LinkedList<>();
        //更新所有 流程节点(wf_run_task)的审批状态为30，结束流程，形成闭环
        for (String processInstId : processInstIdList) {
            //获取最新的一个节点
            RunTaskDo one = runTaskService.getOne(new QueryWrapper<RunTaskDo>().lambda()
                    .eq(RunTaskDo::getProcessinstid, processInstId)
                    .eq(RunTaskDo::getTaskname, "生产计划员5")
                    .in(RunTaskDo::getTaskstatus, Arrays.asList("10", "20"))
                    .orderByDesc(RunTaskDo::getModifydate).last("limit 1"));

            RunTaskDo needUpdate = new RunTaskDo();
            needUpdate.setId(one.getId());
            needUpdate.setAssignee("8672bf72ab274bec83052868ae336b38");//系统管理员
            needUpdate.setTaskstatus("30");
            DateTime nowDate = DateUtil.date();
            needUpdate.setCreatedate(nowDate);
            needUpdate.setModifydate(nowDate);
            needUpdate.setModifyuserid("8672bf72ab274bec83052868ae336b38");
            needUpdate.setModifyusername("管理员");
            needUpdateList.add(needUpdate);
        }

        runTaskService.updateBatchById(needUpdateList);
        //更新所有流程实例为已完成(20)
        processInstService.update(new UpdateWrapper<ProcessInstDo>().lambda()
                .set(ProcessInstDo::getFlowinststatus, "20")
                .in(ProcessInstDo::getId, processInstIdList));

        //更新所有订单的审批状态为 已完工关闭
        List<String> orderIdList = productionOrderDoList.stream().map(ApsProductionOrderDo::getId).collect(Collectors.toList());
        this.update(new UpdateWrapper<ApsProductionOrderDo>().lambda()
                .set(ApsProductionOrderDo::getAuditstatus, "已完工关闭")
                .in(ApsProductionOrderDo::getId, orderIdList));

        return R.ok();
    }

    @Override
    @Transactional
    public R generalMsInsert(OrderSaveOrUpdateVo req) {
        MasterSlaveInsertVo masterSlaveInsert = req.getMasterSlaveInsert();
        try {
            sysGeneralCRUDService.generalMsInsert(masterSlaveInsert);
        } catch (Exception e) {
            throw new RuntimeException("新增订单信息错误，请刷新页面后重试");
        }
        //发起流程
        if (req.getIsStartWf()) {
            SysUserVo currentUser = CXCommonUtils.getCurrentUser();
            ApsProductionOrderDo oldOrder = req.getOldOrder();
            CreateProcessVo createProcessVo = new CreateProcessVo();
            createProcessVo.setProcessdefid("order_review");
            createProcessVo.setBusinesstablename("aps_production_order");
            createProcessVo.setBusinesstableid(oldOrder.getId());
            createProcessVo.setProcessname("订单评审");
            createProcessVo.setProcesstitle(oldOrder.getOrderno() + "-订单评审-" + DateUtil.now());
            createProcessVo.setUserId(currentUser.getId());
            createProcessVo.setNotifycontent("订单评审");
            //查询订单信息，map格式返回
            Map<String, Object> map = this.baseMapper.getMapById(oldOrder.getId());
            createProcessVo.setBusinesstableValue(map);
            try {
                workFlowService.createProcessInstance(createProcessVo);
            } catch (Exception e) {
                log.error("流程创建失败");
                throw new RuntimeException("执行创建流程失败，请刷新页面后重试");
            }
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R generalMsUpdate(OrderSaveOrUpdateVo req) {
        MasterSlaveUpdateVo masterSlaveUpdate = req.getMasterSlaveUpdate();
        String id = masterSlaveUpdate.getMasterUpdate().getColumnQueryTypes().get(0).getColumns().get(0).getValue();
        SysUserVo currentUser = CXCommonUtils.getCurrentUser();
        if (productOrderLock.containsKey(id)) {
            log.error("修改-该订单已被：{}提交", productOrderLock.get(id));
            return R.error("该订单已被提交");
        }
        productOrderLock.put(id, currentUser.getId());
        try {
            //数据库中的订单数据
            ApsProductionOrderDo nowApsProductionOrderDo = this.getById(id);
            //页面上的订单数据
            ApsProductionOrderDo oldOrder = req.getOldOrder();
            //如果 评审状态 不一致
            if (!oldOrder.getAuditstatus().equals(nowApsProductionOrderDo.getAuditstatus())) {
                return R.error("该订单已被提交，请刷新页面后重新操作");
            }
            try {
                sysGeneralCRUDService.generalMsUpdate(masterSlaveUpdate);
            } catch (Exception e) {
                throw new RuntimeException("更新订单信息错误，请刷新页面后重试");
            }
            //提交流程
            if (req.getIsSubmitWf()) {
                String processinstid = nowApsProductionOrderDo.getProcessinstid();
                RunTaskDo runTaskDo = runTaskService.getOne(new LambdaQueryWrapper<RunTaskDo>().eq(BaseDo::getDeleted, "0")
                        .eq(RunTaskDo::getProcessinstid, processinstid)
                        .in(RunTaskDo::getTaskstatus, "10", "20")
                        .orderByDesc(BaseDo::getCreatedate), false);
                RunTaskVo runTaskVo = new RunTaskVo();
                BeanUtils.copyProperties(runTaskDo, runTaskVo);
                runTaskVo.setProcessInstId(processinstid);
                runTaskVo.setBusinesstableid(nowApsProductionOrderDo.getId());
                runTaskVo.setProcesstitle("订单评审");
                runTaskVo.setProcessdefid("order_review");
                runTaskVo.setAuditoperation("10");
                runTaskVo.setTaskstatusname("待处理");
                runTaskVo.setComment(req.getComment());
                try {
                    workFlowService.runTask(runTaskVo, true);
                } catch (Exception e) {
                    log.error("流程更新失败");
                    throw new RuntimeException("执行提交流程失败，请刷新页面后重试");
                }
            }
            //退回流程
            if (req.getIsBackWf()) {
                try {
                    workFlowService.flowBackByType(req.getFlowBackVo());
                    return R.ok();
                } catch (Exception e) {
                    log.error("流程退回失败");
                    throw new RuntimeException("执行退回流程失败，请刷新页面后重试");
                }
            }
            //发起流程
            if (req.getIsStartWf()) {
                CreateProcessVo createProcessVo = new CreateProcessVo();
                createProcessVo.setProcessdefid("order_review");
                createProcessVo.setBusinesstablename("aps_production_order");
                createProcessVo.setBusinesstableid(nowApsProductionOrderDo.getId());
                createProcessVo.setProcessname("订单评审");
                createProcessVo.setProcesstitle(nowApsProductionOrderDo.getOrderno() + "-订单评审-" + DateUtil.now());
                createProcessVo.setUserId(currentUser.getId());
                createProcessVo.setNotifycontent("订单评审");
                //查询订单信息，map格式返回
                Map<String, Object> map = this.baseMapper.getMapById(nowApsProductionOrderDo.getId());
                createProcessVo.setBusinesstableValue(map);
                try {
                    workFlowService.createProcessInstance(createProcessVo);
                } catch (Exception e) {
                    log.error("流程创建失败");
                    throw new RuntimeException("执行创建流程失败，请刷新页面后重试");
                }
            }
        } finally {
            log.debug("修改-订单提交完毕，从map中清空当前订单锁，订单ID:{}", id);
            productOrderLock.remove(id);
        }
        return R.ok();
    }

    @Override
    public R removeBatchNumberByOrderId(String orderId) {
        //查询所有的坯料计划
        List<ApsBlankOrderDo> apsBlankOrderDoList = apsBlankOrderService.list(new QueryWrapper<ApsBlankOrderDo>().lambda().eq(ApsBlankOrderDo::getProductionorderid, orderId));
        for (ApsBlankOrderDo apsBlankOrderDo : apsBlankOrderDoList) {
            //如果是否备料=是，备料对应在制品的备料计划ID=(空)，在制品状态=备料中
            if (ObjectUtil.isNotEmpty(apsBlankOrderDo.getPreparematerialbatchno())) {
                List<String> batchNumberList = Arrays.asList(apsBlankOrderDo.getPreparematerialbatchno().split(","));
                apsWorkInProgressInventoryService.update(new UpdateWrapper<ApsWorkInProgressInventoryDo>().lambda()
                        .set(ApsWorkInProgressInventoryDo::getPlanmaterialid, null)
                        .setSql("WORKINPROCESSSTATUS = IF(PREVIOUSWORKINPROCESSSTATUS = '待加工','备料中',PREVIOUSWORKINPROCESSSTATUS)")
                        .eq(ApsWorkInProgressInventoryDo::getDeleted, "0")
                        .in(ApsWorkInProgressInventoryDo::getBatchnumber, batchNumberList));

                //更新坯料计划该字段为空
                apsBlankOrderService.update(new UpdateWrapper<ApsBlankOrderDo>().lambda()
                        .set(ApsBlankOrderDo::getPreparematerialbatchno, null)
                        .eq(ApsBlankOrderDo::getId, apsBlankOrderDo.getId()));
            }
        }
        return R.ok();
    }

    @Override
    public void dataEyeReport() {


        //生成大屏中间部分数据
        try {
            log.info("开始生成大屏中间的数据");
            setMiddleData();
        } catch (Exception e) {
            log.error("生成大屏中间数据失败");
            e.printStackTrace();
        }
        //订单完成情况表格
        try {
            log.info("开始生成大屏订单完成情况表格");
            setOrderFinishTable();
        } catch (Exception e) {
            log.error("生成大屏订单完成情况表格失败");
            e.printStackTrace();
        }
        //订单完成情况趋势图
        try {
            log.info("开始生成大屏订单完成情况趋势图");
            setOrderFinishTrend();
        } catch (Exception e) {
            log.error("生成大屏订单完成情况趋势图失败");
            e.printStackTrace();
        }
        //铸轧生产情况表格
        try {
            log.info("开始生成大屏铸轧生产情况表格");
            setCastRollData();
        } catch (Exception e) {
            log.error("生成大屏铸轧生产情况表格失败");
            e.printStackTrace();
        }
        //铸轧生产情况趋势图
        try {
            log.info("开始生成大屏铸轧生产情况趋势图");
            setCastRollTrend();
        } catch (Exception e) {
            log.error("生成大屏铸轧生产情况趋势图失败");
            e.printStackTrace();
        }
        //精整生产情况表格
        try {
            log.info("开始生成大屏精整生产情况表格");
            setProcessTable();
        } catch (Exception e) {
            log.error("生成大屏精整生产情况表格失败");
            e.printStackTrace();
        }
        //精整生产情况趋势图
        try {
            log.info("开始生成大屏精整生产情况趋势图");
            setProcessTrend();
        } catch (Exception e) {
            log.error("生成大屏精整生产情况趋势图失败");
            e.printStackTrace();
        }
        //轧机生产情况表格
        try {
            log.info("开始生成大屏轧机生产情况表格");
            setZjProcessTable();
        } catch (Exception e) {
            log.error("生成大屏轧机生产情况表格失败");
            e.printStackTrace();
        }
        //轧机生产情况趋势图
        try {
            log.info("开始生成大屏轧机生产情况趋势图");
            setZjProcessTrend();
        } catch (Exception e) {
            log.error("生成大屏轧机生产情况趋势图失败");
            e.printStackTrace();
        }
        //退火生产情况表格
        try {
            log.info("开始生成大屏退火生产情况表格");
            setThProcessTable();
        } catch (Exception e) {
            log.error("生成大屏退火生产情况表格失败");
            e.printStackTrace();
        }
        //退火生产情况趋势图
        try {
            log.info("开始生成大屏退火生产情况趋势图");
            setThProcessTrend();
        } catch (Exception e) {
            log.error("生成大屏退火生产情况趋势图失败");
            e.printStackTrace();
        }

    }

    private void setThProcessTrend() {
        List<ApsReportThProcessPhoto> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            //平均值
            ApsReportThProcessPhoto avgApsReportThProcessPhoto = this.baseMapper.selectAvgThProcessPhoto(key);
            //近12月数据
            List<ApsReportThProcessPhoto> list = this.baseMapper.selectThProcessPhoto(key);
            if (ObjectUtil.isNotEmpty(list)) {
                //按日期升序
                list.sort(Comparator.comparing(a -> DateUtil.parse(a.getYearmonth(), "yyyy-MM")));
                String nowYear = DateUtil.year(new Date()) + "";
                //如果第一个月是今年的数据，全年只取月份
                if (list.get(0).getYearmonth().split("-")[0].equals(nowYear)) {
                    list.forEach(item -> {
                        item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                    });
                }
                //如果第一个月不是今年的，第一个月取年月，第二年第一个月取年月，其余只取月份
                else {
                    //判断是否触发今年数据
                    boolean isNowYear = false;
                    for (int i = 0; i < list.size(); i++) {
                        ApsReportThProcessPhoto item = list.get(i);
                        if (i == 0) {
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                            continue;
                        }
                        if (!isNowYear && item.getYearmonth().split("-")[0].equals(nowYear)) {
                            isNowYear = true;
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                        } else {
                            item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                        }
                    }
                }
                int index = 1;
                for (ApsReportThProcessPhoto item : list) {
                    item.setId(key + String.format("%02d", index));
                    index++;
                    item.setTenantid(key);
                    item.setTenantname(value);
                    item.setAvgplanproducevolume(avgApsReportThProcessPhoto.getAvgplanproducevolume());
                    item.setAvgactualproducevolume(avgApsReportThProcessPhoto.getAvgactualproducevolume());
                }
                resInsertList.addAll(list);
            }
        });
        if (ObjectUtil.isNotEmpty(resInsertList)) {
            this.baseMapper.truncateByTableName("aps_report_th_process_photo");
//            apsReportThProcessPhotoService.remove(new LambdaQueryWrapper<ApsReportThProcessPhoto>().eq(ApsReportThProcessPhoto::getDeleted, "0"));
            apsReportThProcessPhotoService.saveBatch(resInsertList);
        }
    }

    private void setThProcessTable() {
        List<ApsReportThProcessTable> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            List<ApsReportThProcessTable> list = this.baseMapper.selectThProcessTable(key);
            list = list.stream().filter(item -> ObjectUtil.isNotEmpty(item.getProcessworkshop())).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    item.setId(SecurityUtil.getUUID());
                    item.setTenantid(key);
                    item.setTenantname(value);
                });
                resInsertList.addAll(list);
            }
        });
        if (ObjectUtil.isNotEmpty(resInsertList)) {
            apsReportThProcessTableService.remove(new LambdaQueryWrapper<ApsReportThProcessTable>().eq(ApsReportThProcessTable::getDeleted, "0"));
            apsReportThProcessTableService.saveBatch(resInsertList);
        }
    }

    private void setZjProcessTrend() {
        List<ApsReportZjProcessPhoto> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            //平均值
            ApsReportZjProcessPhoto avgApsReportZjProcessPhoto = this.baseMapper.selectAvgZjProcessPhoto(key);
            //近12月数据
            List<ApsReportZjProcessPhoto> list = this.baseMapper.selectZjProcessPhoto(key);
            if (ObjectUtil.isNotEmpty(list)) {
                //按日期升序
                list.sort(Comparator.comparing(a -> DateUtil.parse(a.getYearmonth(), "yyyy-MM")));
                String nowYear = DateUtil.year(new Date()) + "";
                //如果第一个月是今年的数据，全年只取月份
                if (list.get(0).getYearmonth().split("-")[0].equals(nowYear)) {
                    list.forEach(item -> {
                        item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                    });
                }
                //如果第一个月不是今年的，第一个月取年月，第二年第一个月取年月，其余只取月份
                else {
                    //判断是否触发今年数据
                    boolean isNowYear = false;
                    for (int i = 0; i < list.size(); i++) {
                        ApsReportZjProcessPhoto item = list.get(i);
                        if (i == 0) {
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                            continue;
                        }
                        if (!isNowYear && item.getYearmonth().split("-")[0].equals(nowYear)) {
                            isNowYear = true;
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                        } else {
                            item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                        }
                    }
                }
                int index = 1;
                for (ApsReportZjProcessPhoto item : list) {
                    item.setId(key + String.format("%02d", index));
                    index++;
                    item.setTenantid(key);
                    item.setTenantname(value);
                    item.setAvgplanproducevolume(avgApsReportZjProcessPhoto.getAvgplanproducevolume());
                    item.setAvgactualproducevolume(avgApsReportZjProcessPhoto.getAvgactualproducevolume());
                }
                resInsertList.addAll(list);
            }
        });
        if (ObjectUtil.isNotEmpty(resInsertList)) {
//            apsReportZjProcessPhotoService.remove(new LambdaQueryWrapper<ApsReportZjProcessPhoto>().eq(ApsReportZjProcessPhoto::getDeleted, "0"));
            this.baseMapper.truncateByTableName("aps_report_zj_process_photo");
            apsReportZjProcessPhotoService.saveBatch(resInsertList);
        }

    }

    private void setZjProcessTable() {
        List<ApsReportZjProcessTable> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            List<ApsReportZjProcessTable> list = this.baseMapper.selectZjProcessTable(key);
            list = list.stream().filter(item -> ObjectUtil.isNotEmpty(item.getProcessworkshop())).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    item.setId(SecurityUtil.getUUID());
                    item.setTenantid(key);
                    item.setTenantname(value);
                });
                resInsertList.addAll(list);
            }
        });
        if (ObjectUtil.isNotEmpty(resInsertList)) {
            apsReportZjProcessTableService.remove(new LambdaQueryWrapper<ApsReportZjProcessTable>().eq(ApsReportZjProcessTable::getDeleted, "0"));
            apsReportZjProcessTableService.saveBatch(resInsertList);
        }
    }

    private void setProcessTrend() {
        List<ApsReportJzProcessPhoto> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            //平均值
            ApsReportJzProcessPhoto avgApsReportJzProcessPhoto = this.baseMapper.selectProcessAvg(key);
            //近12月数据
            List<ApsReportJzProcessPhoto> list = this.baseMapper.selectProcessTrend(key);
            if (ObjectUtil.isNotEmpty(list)) {
                //按日期升序
                list.sort(Comparator.comparing(a -> DateUtil.parse(a.getYearmonth(), "yyyy-MM")));
                String nowYear = DateUtil.year(new Date()) + "";
                //如果第一个月是今年的数据，全年只取月份
                if (list.get(0).getYearmonth().split("-")[0].equals(nowYear)) {
                    list.forEach(item -> {
                        item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                    });
                }
                //如果第一个月不是今年的，第一个月取年月，第二年第一个月取年月，其余只取月份
                else {
                    //判断是否触发今年数据
                    boolean isNowYear = false;
                    for (int i = 0; i < list.size(); i++) {
                        ApsReportJzProcessPhoto item = list.get(i);
                        if (i == 0) {
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                            continue;
                        }
                        if (!isNowYear && item.getYearmonth().split("-")[0].equals(nowYear)) {
                            isNowYear = true;
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                        } else {
                            item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                        }
                    }
                }
                int index = 1;
                for (ApsReportJzProcessPhoto item : list) {
                    item.setId(key + String.format("%02d", index));
                    index++;
                    item.setTenantid(key);
                    item.setTenantname(value);
                    item.setAvgplanproducevolume(avgApsReportJzProcessPhoto.getAvgplanproducevolume());
                    item.setAvgactualproducevolume(avgApsReportJzProcessPhoto.getAvgactualproducevolume());
                }
                resInsertList.addAll(list);
            }
        });
        if (ObjectUtil.isNotEmpty(resInsertList)) {
//            apsReportJzProcessPhotoService.remove(new QueryWrapper<ApsReportJzProcessPhoto>().lambda().eq(ApsReportJzProcessPhoto::getDeleted, "0"));
            this.baseMapper.truncateByTableName("aps_report_jz_process_photo");
            apsReportJzProcessPhotoService.saveBatch(resInsertList);
        }
    }

    private void setProcessTable() {
        List<ApsReportJzProcessTable> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            List<ApsReportJzProcessTable> list = this.baseMapper.selectProcessTable(key);
            list = list.stream().filter(item -> ObjectUtil.isNotEmpty(item.getProcessworkshop())).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    item.setId(SecurityUtil.getUUID());
                    item.setTenantid(key);
                    item.setTenantname(value);
                });
                resInsertList.addAll(list);
            }
        });
        if (ObjectUtil.isNotEmpty(resInsertList)) {
            apsReportJzProcessTableService.remove(new QueryWrapper<ApsReportJzProcessTable>().lambda().eq(ApsReportJzProcessTable::getDeleted, "0"));
            apsReportJzProcessTableService.saveBatch(resInsertList);
        }

    }

    private void setCastRollTrend() {
        List<ApsReportCastRollPhoto> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            //平均值
            ApsReportCastRollPhoto apsReportCastRollPhotoAvg = this.baseMapper.selectCastRollPhotoAvg(key);
            //近12月份值
            List<ApsReportCastRollPhoto> list = this.baseMapper.selectCastRollPhoto(key);
            if (ObjectUtil.isNotEmpty(list)) {
                //按日期升序
                list.sort(Comparator.comparing(a -> DateUtil.parse(a.getYearmonth(), "yyyy-MM")));
                String nowYear = DateUtil.year(new Date()) + "";
                //如果第一个月是今年的数据，全年只取月份
                if (list.get(0).getYearmonth().split("-")[0].equals(nowYear)) {
                    list.forEach(item -> {
                        item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                    });
                }
                //如果第一个月不是今年的，第一个月取年月，第二年第一个月取年月，其余只取月份
                else {
                    //判断是否触发今年数据
                    boolean isNowYear = false;
                    for (int i = 0; i < list.size(); i++) {
                        ApsReportCastRollPhoto item = list.get(i);
                        if (i == 0) {
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                            continue;
                        }
                        if (!isNowYear && item.getYearmonth().split("-")[0].equals(nowYear)) {
                            isNowYear = true;
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1] + " ");
                        } else {
                            item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                        }
                    }
                }

                int index = 1;
                for (ApsReportCastRollPhoto item : list) {
                    item.setId(key + String.format("%02d", index));
                    index++;
                    item.setTenantid(key);
                    item.setTenantname(value);
                    item.setAvgplanproducevolume(apsReportCastRollPhotoAvg.getAvgplanproducevolume());
                    item.setAvgactualproducevolume(apsReportCastRollPhotoAvg.getAvgactualproducevolume());
                }
                resInsertList.addAll(list);
            }
        });
        //更新
        if (ObjectUtil.isNotEmpty(resInsertList)) {
//            apsReportCastRollPhotoService.remove(new LambdaQueryWrapper<ApsReportCastRollPhoto>().eq(ApsReportCastRollPhoto::getDeleted, "0"));
            this.baseMapper.truncateByTableName("aps_report_cast_roll_photo");
            apsReportCastRollPhotoService.saveBatch(resInsertList);
        }
    }

    private void setCastRollData() {
        List<ApsReportCastRollTable> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            List<ApsReportCastRollTable> list = this.baseMapper.selectCastRollData(key);
            list = list.stream().filter(item -> ObjectUtil.isNotEmpty(item.getProcessworkshop())).collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    item.setId(SecurityUtil.getUUID());
                    item.setTenantid(key);
                    item.setTenantname(value);
                });
                resInsertList.addAll(list);
            }
        });
        //更新
        if (ObjectUtil.isNotEmpty(resInsertList)) {
            apsReportCastRollTableService.remove(new LambdaQueryWrapper<ApsReportCastRollTable>().eq(ApsReportCastRollTable::getDeleted, "0"));
            apsReportCastRollTableService.saveBatch(resInsertList);
        }
    }

    private void setOrderFinishTrend() {
        List<ApsReportOrderFinishPhoto> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            //平均值
            ApsReportOrderFinishPhoto apsReportOrderFinishPhotoAvg = this.baseMapper.selectOrderFinishPhotoAvg(key);
            //近12月值
            List<ApsReportOrderFinishPhoto> list = this.baseMapper.selectOrderFinishPhotoByMonth(key);
            if (ObjectUtil.isNotEmpty(list)) {
                //按日期升序
                list.sort(Comparator.comparing(a -> DateUtil.parse(a.getYearmonth(), "yyyy-MM")));
                String nowYear = DateUtil.year(new Date()) + "";
                //如果第一个月是今年的数据，全年只取月份
                if (list.get(0).getYearmonth().split("-")[0].equals(nowYear)) {
                    list.forEach(item -> {
                        item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                    });
                }
                //如果第一个月不是今年的，第一个月取年月，第二年第一个月取年月，其余只取月份
                else {
                    //判断是否触发今年数据
                    boolean isNowYear = false;
                    for (int i = 0; i < list.size(); i++) {
                        ApsReportOrderFinishPhoto item = list.get(i);
                        if (i == 0) {
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1]);
                            continue;
                        }
                        if (!isNowYear && item.getYearmonth().split("-")[0].equals(nowYear)) {
                            isNowYear = true;
                            item.setYearmonth(item.getYearmonth().split("-")[0] + "." + item.getYearmonth().split("-")[1]);
                        } else {
                            item.setYearmonth(item.getYearmonth().split("-")[1] + " ");
                        }
                    }
                }

                int index = 1;
                for (ApsReportOrderFinishPhoto item : list) {
                    item.setId(key + String.format("%02d", index));
                    index++;
                    item.setTenantid(key);
                    item.setTenantname(value);
                    item.setAvgplanproducevolume(apsReportOrderFinishPhotoAvg.getAvgplanproducevolume());
                    item.setAvgactualproducevolume(apsReportOrderFinishPhotoAvg.getAvgactualproducevolume());
                }
                resInsertList.addAll(list);
            }
        });
        //更新
        if (!resInsertList.isEmpty()) {
//            apsReportOrderFinishPhotoService.remove(new LambdaQueryWrapper<ApsReportOrderFinishPhoto>().eq(ApsReportOrderFinishPhoto::getDeleted, "0"));
            this.baseMapper.truncateByTableName("aps_report_order_finish_photo");
            apsReportOrderFinishPhotoService.saveBatch(resInsertList);
        }
    }

    /**
     * 生成订单完成情况表格
     */
    private void setOrderFinishTable() {
        List<ApsReportOrderFinishTable> resInsertList = new LinkedList<>();
        //根据工厂分别生成指定数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            List<ApsReportOrderFinishTable> list = this.baseMapper.selectOrderTable(key);
            if (ObjectUtil.isNotEmpty(list)) {
                list.forEach(item -> {
                    item.setId(SecurityUtil.getUUID());
                    item.setTenantid(key);
                    item.setTenantname(value);
                });
                resInsertList.addAll(list);
            }
        });
        //更新
        if (!resInsertList.isEmpty()) {
            apsReportOrderFinishTableService.remove(new LambdaQueryWrapper<ApsReportOrderFinishTable>().eq(ApsReportOrderFinishTable::getDeleted, "0"));
            apsReportOrderFinishTableService.saveBatch(resInsertList);
        }
    }

    /**
     * 生成大屏中间部分数据
     */
    private void setMiddleData() {
        //存储最终数据
        List<ApsReportYearAndMonth> resInsertList = new LinkedList<>();
        //初始化数据
        SaveConstans.COMPANY_MAP.forEach((key, value) -> {
            ApsReportYearAndMonth apsReportYearAndMonth = new ApsReportYearAndMonth();
            apsReportYearAndMonth.setId(SecurityUtil.getUUID());
            apsReportYearAndMonth.setTenantid(key);
            apsReportYearAndMonth.setTenantname(value);
            resInsertList.add(apsReportYearAndMonth);
        });


        //===================今年计划接单量==================
        List<ApsReportYearAndMonth> apsReportYearAndMonthList = this.baseMapper.selectNowYearPlanGetOrderNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndMonthList) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setPlanordernumyear(apsReportYearAndMonth.getPlanordernumyear());
                });
            }
        }
        //==================今年实际已接单===================
        List<ApsReportYearAndMonth> apsReportYearAndMonthList1 = this.baseMapper.selectNowYearActualGetOrderNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndMonthList1) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setActualordernumyear(apsReportYearAndMonth.getActualordernumyear());
                });
            }
        }
        //==================今年实际已完成===================
        List<ApsReportYearAndMonth> apsReportYearAndMonthList2 = this.baseMapper.selectNowYearActualProduceNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndMonthList2) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setActualfinishnumyear(apsReportYearAndMonth.getActualfinishnumyear());
                });
            }
        }
        //==================今年接单量完成比例 = 今年实际已接单/今年计划接单量===================
        resInsertList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getPlanordernumyear())
                    && ObjectUtil.isNotEmpty(item.getActualordernumyear())
                    && new BigDecimal(item.getPlanordernumyear()).compareTo(BigDecimal.ZERO) != 0
                    && new BigDecimal(item.getActualordernumyear()).compareTo(BigDecimal.ZERO) != 0) {
                //计算比例，保留4位小数，以便百分比保留两位小数
                item.setPlanordernumyearpercent(
                        new BigDecimal(item.getActualordernumyear()).multiply(new BigDecimal(100)).divide(new BigDecimal(item.getPlanordernumyear()), 2, RoundingMode.HALF_UP).toString());
            } else if (new BigDecimal(item.getActualordernumyear()).compareTo(BigDecimal.ZERO) == 0) {
                item.setPlanordernumyearpercent("0");
            } else {
                item.setPlanordernumyearpercent("100");
            }
//            //拼接展示字段
//            String pre = item.getPlanordernumyearpercent();
//            item.setActualordernumyearshow(
//                    item.getActualordernumyear() + "(" + pre + "%)");
        });
        //==================今年完成比例=今年实际已完成/今年实际已接单===================
        resInsertList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getActualordernumyear())
                    && ObjectUtil.isNotEmpty(item.getActualfinishnumyear())
                    && new BigDecimal(item.getActualordernumyear()).compareTo(BigDecimal.ZERO) != 0
                    && new BigDecimal(item.getActualfinishnumyear()).compareTo(BigDecimal.ZERO) != 0) {
                //计算比例，保留4位小数，以便百分比保留两位小数
                item.setActualfinishnumyearpercent(
                        new BigDecimal(item.getActualfinishnumyear()).multiply(BigDecimal.valueOf(100)).divide(new BigDecimal(item.getActualordernumyear()), 2, RoundingMode.HALF_UP).toString());
            } else if (new BigDecimal(item.getActualfinishnumyear()).compareTo(BigDecimal.ZERO) == 0) {
                item.setActualfinishnumyearpercent("0");
            } else {
                item.setActualfinishnumyearpercent("100");
            }
//            //拼接展示字段
//            String pre = item.getActualfinishnumyearpercent();
//            item.setActualfinishnumyearshow(
//                    item.getActualfinishnumyear() + "(" + pre + "%)");
        });
        //==================本月计划接单量==================
        List<ApsReportYearAndMonth> apsReportYearAndMonthList3 = this.baseMapper.selectNowMonthPlanGetOrderNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndMonthList3) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setPlanordernummonth(apsReportYearAndMonth.getPlanordernummonth());
                });
            }
        }
        //==================本月实际已接单===================
        List<ApsReportYearAndMonth> apsReportYearAndMonthList4 = this.baseMapper.selectNowMonthActualGetOrderNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndMonthList4) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setActualordernummonth(apsReportYearAndMonth.getActualordernummonth());
                });
            }
        }
        //==================本月实际已完成===================
        List<ApsReportYearAndMonth> apsReportYearAndMonthList5 = this.baseMapper.selectNowMonthActualProduceNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndMonthList5) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setActualfinishnummonth(apsReportYearAndMonth.getActualfinishnummonth());
                });
            }
        }
        //==================本月接单量完成比例 = 本月实际已接单/本月计划接单量===================
        resInsertList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getPlanordernummonth())
                    && ObjectUtil.isNotEmpty(item.getActualordernummonth())
                    && new BigDecimal(item.getPlanordernummonth()).compareTo(BigDecimal.ZERO) != 0
                    && new BigDecimal(item.getActualordernummonth()).compareTo(BigDecimal.ZERO) != 0) {
                //计算比例，保留4位小数，以便百分比保留两位小数
                item.setPlanordernummonthpercent(
                        new BigDecimal(item.getActualordernummonth()).multiply(BigDecimal.valueOf(100)).divide(new BigDecimal(item.getPlanordernummonth()), 2, RoundingMode.HALF_UP).toString());
            } else if (new BigDecimal(item.getActualordernummonth()).compareTo(BigDecimal.ZERO) == 0) {
                item.setPlanordernummonthpercent("0");
            } else {
                item.setPlanordernummonthpercent("100");
            }
//            //拼接展示字段
//            String pre = item.getPlanordernummonthpercent();
//            item.setActualordernummonthshow(
//                    item.getActualordernummonth() + "(" + pre + "%)");
        });
        //==================本月完成比例=本月实际已完成/本月实际已接单===================
        resInsertList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getActualordernummonth())
                    && ObjectUtil.isNotEmpty(item.getActualfinishnummonth())
                    && new BigDecimal(item.getActualordernummonth()).compareTo(BigDecimal.ZERO) != 0
                    && new BigDecimal(item.getActualfinishnummonth()).compareTo(BigDecimal.ZERO) != 0) {
                //计算比例，保留4位小数，以便百分比保留两位小数
                item.setActualfinishnummonthpercent(
                        new BigDecimal(item.getActualfinishnummonth()).multiply(BigDecimal.valueOf(100)).divide(new BigDecimal(item.getActualordernummonth()), 2, RoundingMode.HALF_UP).toString());
            } else if (new BigDecimal(item.getActualfinishnummonth()).compareTo(BigDecimal.ZERO) == 0) {
                item.setActualfinishnummonthpercent("0");
            } else {
                item.setActualfinishnummonthpercent("100");
            }
//            //拼接展示字段
//            String pre = item.getActualfinishnummonthpercent();
//            item.setActualfinishnummonthshow(
//                    item.getActualfinishnummonth() + "(" + pre + "%)");
        });


        //==================本周计划接单量==================
        //获取 每个工厂、每年、每月的平均计划量
        List<Map<String, Object>> planMapList = this.baseMapper.selectPlanMap();
        resInsertList.forEach(item -> {
            List<Map<String, Object>> mapList = planMapList.stream().filter(item2 -> ObjectUtil.isNotEmpty(item2.getOrDefault("tenantid", "").toString()) && item2.getOrDefault("tenantid", "").toString().equals(item.getTenantid()))
                    .collect(Collectors.toList());
            if (ObjectUtil.isNotEmpty(mapList)) {
                //获取当前周的7天日期
                // 获取当前日期
                LocalDate currentDate = LocalDate.now();

                // 获取当前周的第一天和最后一天
                WeekFields weekFields = WeekFields.of(Locale.getDefault());
                LocalDate firstDayOfWeek = currentDate.with(weekFields.dayOfWeek(), 1);

                //当前周的日期
                List<String> dayWeekList = new LinkedList<>();
                for (int i = 0; i < 7; i++) {
                    LocalDate day = firstDayOfWeek.plusDays(i);
                    dayWeekList.add(DateUtil.format(day.atStartOfDay(), "yyyy-MM-dd"));
                }
                //计算本周计划
                BigDecimal weekPlan = BigDecimal.ZERO;
                for (String day : dayWeekList) {
                    String[] split = day.split("-");
                    String year = split[0];
                    String month = split[1];
                    Map<String, Object> map = mapList.stream().filter(item2 -> ObjectUtil.isNotEmpty(item2.getOrDefault("year", "")) && item2.getOrDefault("year", "").equals(year))
                            .findFirst().orElse(null);
                    if (ObjectUtil.isNotEmpty(map) && ObjectUtil.isNotEmpty(map.getOrDefault(month, ""))) {
                        weekPlan = weekPlan.add(new BigDecimal(map.getOrDefault(month, "0").toString()));
                    }
                }
                //保留两位小数
                weekPlan = weekPlan.setScale(2, RoundingMode.HALF_UP);
                item.setPlanordernumweek(weekPlan.toString());
            }
        });
        //==================本周实际已接单===================
        List<ApsReportYearAndMonth> apsReportYearAndWeekList4 = this.baseMapper.selectNowWeekActualGetOrderNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndWeekList4) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setActualordernumweek(apsReportYearAndMonth.getActualordernumweek());
                });
            }
        }
        //==================本周实际已完成===================
        List<ApsReportYearAndMonth> apsReportYearAndWeekList5 = this.baseMapper.selectNowWeekActualProduceNum();
        for (ApsReportYearAndMonth apsReportYearAndMonth : apsReportYearAndWeekList5) {
            if (ObjectUtil.isEmpty(apsReportYearAndMonth)) {
                continue;
            }
            if (ObjectUtil.isNotEmpty(apsReportYearAndMonth.getTenantid()) && SaveConstans.COMPANY_MAP.containsKey(apsReportYearAndMonth.getTenantid())) {
                resInsertList.stream().filter(item -> item.getTenantid().equals(apsReportYearAndMonth.getTenantid())).findFirst().ifPresent(item -> {
                    item.setActualfinishnumweek(apsReportYearAndMonth.getActualfinishnumweek());
                });
            }
        }
        //==================本周接单量完成比例 = 本周实际已接单/本周计划接单量===================
        resInsertList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getPlanordernumweek())
                    && ObjectUtil.isNotEmpty(item.getActualordernumweek())
                    && new BigDecimal(item.getPlanordernumweek()).compareTo(BigDecimal.ZERO) != 0
                    && new BigDecimal(item.getActualordernumweek()).compareTo(BigDecimal.ZERO) != 0) {
                //计算比例，保留4位小数，以便百分比保留两位小数
                item.setPlanordernumweekhpercent(
                        new BigDecimal(item.getActualordernumweek()).multiply(BigDecimal.valueOf(100)).divide(new BigDecimal(item.getPlanordernumweek()), 2, RoundingMode.HALF_UP).toString());
            } else if (new BigDecimal(item.getActualordernumweek()).compareTo(BigDecimal.ZERO) == 0) {
                item.setPlanordernumweekhpercent("0");
            } else {
                item.setPlanordernumweekhpercent("100");
            }
        });
        //==================本周完成比例=本周实际已完成/本周实际已接单===================
        resInsertList.forEach(item -> {
            if (ObjectUtil.isNotEmpty(item.getActualordernumweek())
                    && ObjectUtil.isNotEmpty(item.getActualfinishnumweek())
                    && new BigDecimal(item.getActualordernumweek()).compareTo(BigDecimal.ZERO) != 0
                    && new BigDecimal(item.getActualfinishnumweek()).compareTo(BigDecimal.ZERO) != 0) {
                //计算比例，保留4位小数，以便百分比保留两位小数
                item.setActualfinishnumweekhpercent(
                        new BigDecimal(item.getActualfinishnumweek()).multiply(BigDecimal.valueOf(100)).divide(new BigDecimal(item.getActualordernumweek()), 2, RoundingMode.HALF_UP).toString());
            } else if (new BigDecimal(item.getActualfinishnumweek()).compareTo(BigDecimal.ZERO) == 0) {
                item.setActualfinishnumweekhpercent("0");
            } else {
                item.setActualfinishnumweekhpercent("100");
            }
        });
        //================更新数据==================
        if (!resInsertList.isEmpty()) {
            //删除所有之前的数据
            apsReportYearAndMonthService.remove(new QueryWrapper<ApsReportYearAndMonth>().lambda().eq(ApsReportYearAndMonth::getDeleted, "0"));
            //插入新的数据
            apsReportYearAndMonthService.saveBatch(resInsertList);
        }
    }

}




