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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rongwei.bscommon.sys.dao.ApsBlankOrderDao;
import com.rongwei.bscommon.sys.fegin.RwApsServer;
import com.rongwei.bscommon.sys.service.*;
import com.rongwei.bsentity.domain.*;
import com.rongwei.bsentity.vo.*;
import com.rongwei.rwadmincommon.system.vo.SysUserVo;
import com.rongwei.rwcommon.base.exception.CustomException;
import com.rongwei.rwcommon.utils.DateUtils;
import com.rongwei.rwcommon.utils.SecurityUtil;
import com.rongwei.rwcommon.utils.StringUtils;
import com.rongwei.safecommon.utils.CXCommonUtils;
import com.rongwei.safecommon.utils.SaveConstans;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.rongwei.safecommon.utils.SaveConstans.LockmarkType.LOCKMARK_Y;

@Service
public class ApsServiceImpl implements ApsService {

    private static final Logger logger = LoggerFactory.getLogger(ApsServiceImpl.class);
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private ApsBlankOrderService apsBlankOrderService;
    @Autowired
    private ApsBlankOrderDao apsBlankOrderDao;
    @Autowired
    private RwApsServer rwApsServer;
    @Autowired
    private ApsScheduleConfigService apsScheduleConfigService;
    @Autowired
    private AspCheckItemsService aspCheckItemsService;
    @Autowired
    private ApsProcessOperationService apsProcessOperationService;
    @Autowired
    private ApsProcessOperationProcessEquServiceImpl processOperationProcessEquService;
    @Autowired
    private ApsEquipmentCalendarService apsEquipmentCalendarService;
    @Autowired
    private ApsProcessOperationOutMaterService apsProcessOperationOutMaterService;

    @Override
    public void apsSchedule(List<ApsBlankOrderVo> apsBlankOrders) {
        // 当前等路人所属工厂
        SysUserVo currentUser = CXCommonUtils.getCurrentUser();
        String tenantId = currentUser.getOrganizationDoList().get(0).getFullpid().split(",")[1];
        if (StringUtils.isBlank(tenantId)) {
            throw new CustomException("所属工厂不能为空");
        }
        assert apsBlankOrders != null : "排程订单不能为空";
        // 按照所属工厂加锁
        RLock rLock = redissonClient.getLock(tenantId);
        boolean isLocked = rLock.isLocked();
        // 锁是否被占用
        if(isLocked){
            throw new CustomException("正在排程、请稍等一会！");
        }else{
            try {
                // 加锁最大1小时
                rLock.lock(1, TimeUnit.HOURS);
                // 合并待发布未锁定的订单一起排程
                String idStrs = null;
                if(apsBlankOrders != null && apsBlankOrders.size()>0){
                    List<String> hasIds = apsBlankOrders.stream().map(v -> v.getId()).collect(Collectors.toList());
                    idStrs = CollUtil.join(hasIds, "','");
                    idStrs = "'" + idStrs + "'";
                }

                // 查询存在未锁定的作业坯料计划
//            List<ApsBlankOrderVo> fbNotLock = apsBlankOrderDao.getFbNotLock(idStrs,tenantId);
                List<ApsBlankOrderVo> fbNotLock = apsBlankOrderDao.getOrdersHasNotLockProcess(idStrs,tenantId);
                if (fbNotLock != null && fbNotLock.size() > 0) {
                    apsBlankOrders.addAll(fbNotLock);
                }

                // 模型转换
//                ProductionScheduleVo productionScheduleVo = apsBlankOrderService.apsPlanModelSet(apsBlankOrders);
                ProductionScheduleVo productionScheduleVo = apsProductionScheduleInit(apsBlankOrders);
                JSONConfig jsonConfig = JSONConfig.create();
                jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("排程数据：" + JSONUtil.toJsonStr(productionScheduleVo, jsonConfig));
                logger.info("排程数据：" + JSONUtil.toJsonStr(productionScheduleVo, jsonConfig));
                // APS平台排程接口调用
                ProductionScheduleRetVo productionScheduleRetVo = rwApsServer.productionSchedule(productionScheduleVo);
                if (!"200".equals(productionScheduleRetVo.getCode())) {
                    throw new CustomException(productionScheduleRetVo.getMsg());
                }
                apsBlankOrderService.apsAfter(productionScheduleRetVo,apsBlankOrders);
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            } finally {
                rLock.forceUnlock();
                System.out.println("解锁....");
                logger.info("解锁....");
            }
        }
    }

    /**
     * 原始订单表数据转换APS平台模型数据
     *
     * @param apsBlankOrders
     * @return
     */
    @Override
    public ProductionScheduleVo apsProductionScheduleInit(List<ApsBlankOrderVo> apsBlankOrders) {
        // 待排程坯料计划ID集合
        List<String> blankids = apsBlankOrders.stream().map(v -> v.getId()).collect(Collectors.toList());
        ProductionScheduleVo productionScheduleVo = new ProductionScheduleVo();
        productionScheduleVo.setProductionScheduleId("批量排程");
        List<ApsScheduleConfigDo> apsConfigs = apsScheduleConfigService.list();
        ApsScheduleConfigDo apsScheduleConfig = null;
        // 松散度
        if (apsConfigs != null && apsConfigs.size() > 0) {
            apsScheduleConfig = apsConfigs.get(0);
            productionScheduleVo.setLooseness(apsScheduleConfig.getLooseness());
            productionScheduleVo.setPlanSeconds(apsScheduleConfig.getScheduleruntime());
            Map<String, Integer> roamTime = new HashMap<>();
            Integer workshopin = apsScheduleConfig.getWorkshopin();
            Integer workshopcross = apsScheduleConfig.getWorkshopcross();
            roamTime.put("WORKSHOP_IN", workshopin);
            roamTime.put("WORKSHOP_CROSS", workshopcross);
            productionScheduleVo.setRoamTime(roamTime);
            // 排程计划开始时间
            int a = 8;
            if (apsScheduleConfig.getStartschedulerun() != null) {
                a = apsScheduleConfig.getStartschedulerun();
            }
            if (apsScheduleConfig.getApsplanstartdate() != null) {
                productionScheduleVo.setApsPlanStartDate(apsScheduleConfig.getApsplanstartdate());
            } else {
                productionScheduleVo.setApsPlanStartDate(DateUtil.parseDate(DateUtils.format(DateUtil.date(),"yyyy-MM-dd HH:mm")).offset(DateField.HOUR, a));
            }
            productionScheduleVo.setWashingtime(apsScheduleConfig.getWashingtime());
            productionScheduleVo.setStandingtime(apsScheduleConfig.getStandingtime());
        } else {
            throw new CustomException("排程参数缺失");
        }
        // 洗炉合金配置数据设置
        List<WashingMetal> washingMetalConfig = apsBlankOrderDao.getWashingMetalConfig();
        productionScheduleVo.setClosealloynames(washingMetalConfig);

        // 所有设备
        List<AspCheckItemsDo> eqs = aspCheckItemsService.list(new LambdaQueryWrapper<>());
        Map<String, AspCheckItemsDo> eqMaps = new HashMap<>();
        for (AspCheckItemsDo eq : eqs) {
            eqMaps.put(eq.getId(), eq);
        }
        // 排程计划设备集合
        List<Equipment> equipmentList = new ArrayList<>();
        // 排程计划工序任务集合
        List<ProductionProcesses> processesList = new ArrayList<>();
        // 坯料计划ID和所属工序作业ID对应关系
        Map<String, List<String>> blankProcessIds = new HashMap<>();
        // 待合并生产的订单工序
        List<ApsProcessOperationVo> processOperationMs = new ArrayList<>();
        if (apsBlankOrders != null && apsBlankOrders.size() > 0) {
            for (ApsBlankOrderVo apsBlankOrderVo : apsBlankOrders) {
                // 当前坯料计划作业集合
                List<ProductionProcesses> blankProcessesList = new ArrayList<>();
                // 父子ID对应关系处理
                List<String> processIdss = new ArrayList<>();
                // 坯料计划订单
                ProduceOrder produceOrder = new ProduceOrder(apsBlankOrderVo.getId(), apsBlankOrderVo.getMaterialname(), DateUtil.offsetHour(apsBlankOrderVo.getDeliverydate(), -apsBlankOrderVo.getDeliverytime()));
                // 获取所有订单工序
                List<ApsProcessOperationDo> operationDos = apsProcessOperationService.list(new LambdaQueryWrapper<ApsProcessOperationDo>()
                        .eq(ApsProcessOperationDo::getBlankid, apsBlankOrderVo.getId()));
                // 起始节点
                ApsProcessOperationDo rootOperationDo = null;
                // 作业维度缓存
                Map<String,List<ProductionProcesses>> operationProductionProcesses = new HashMap<>();
                Map<String,ApsProcessOperationDo> operationMaps = new HashMap<>();
                // 锁定的合并工序缓存
                Map<String, ProductionProcesses> lockHbPp = new HashMap<>();
                // 转换工序模型数据
                for (ApsProcessOperationDo operationDo : operationDos) {
                    processIdss.add(operationDo.getId());
                    ProductionProcesses processes = new ProductionProcesses();
                    // 工序所属订单
                    processes.setProduceOrder(Arrays.asList(new ProduceOrder[]{produceOrder}));
                    // 判断是否合并生产工序,加工方式是“合并加工”
                    String productprocess = operationDo.getProcessway();
                    // 根节点判断
                    if(StringUtils.isBlank(operationDo.getPreviousprocessid())){
                        rootOperationDo = operationDo;
                    }
                    operationMaps.put(operationDo.getId(),operationDo);
                    // 设备列表初始化
                    List<String> optionalEquipments = equipmentListInit(operationDo,equipmentList,eqMaps,blankids,productionScheduleVo,apsScheduleConfig);
                    // 工序作业相关数据初始化
                    productionProcessesInit(operationDo,produceOrder,optionalEquipments,processesList,operationProductionProcesses);
                }
                // 前后关联关系初始化
                processesRelationInit(rootOperationDo,operationProductionProcesses,operationMaps,apsBlankOrderVo);

                blankProcessIds.put(apsBlankOrderVo.getId(), processIdss);
            }
        }
        // 合并生产工序
        productionScheduleVo.setProcesses(processesList);
        productionScheduleVo.setEquipmentList(equipmentList);
        productionScheduleVo.setBlankProcessIds(blankProcessIds);
        return productionScheduleVo;
    }

    private List<String> equipmentListInit(ApsProcessOperationDo operationDo,List<Equipment> equipmentList,Map<String, AspCheckItemsDo> eqMaps
            ,List<String> blankids,ProductionScheduleVo productionScheduleVo,ApsScheduleConfigDo apsScheduleConfig){
        // 设备列表
        List<String> optionalEquipments = new ArrayList<>();
        if (StringUtils.isNotBlank(operationDo.getCanchoosedeviceid())) {
            String[] sbIds = operationDo.getCanchoosedeviceid().split(",");
            for (String equIds : sbIds) {
                if(equIds.equals("0001be252874536843730b100052")){
                    System.out.println(equIds);
                }
                AspCheckItemsDo checkItemsD = eqMaps.get(equIds);
                if (checkItemsD != null) {
                    optionalEquipments.add(equIds);
                    List<Equipment> eqpts = equipmentList.stream().filter(v -> v.getId().equals(equIds)).collect(Collectors.toList());
                    // 设备集合里不存在时新增
                    if (eqpts == null || eqpts.size() == 0) {
                        Equipment equipment = new Equipment();
                        equipment.setBsEquipmentId(equIds);
                        equipment.setId(equIds);
                        equipment.setEquipmentName(checkItemsD.getCheckitemname());
                        equipment.setWorkshopid(checkItemsD.getUsedeptid());
                        equipment.setWorkshopname(checkItemsD.getUsedeptname());
                        equipment.setFactoryid(checkItemsD.getTenantid());
                        equipment.setFactory(checkItemsD.getOwnedfactory());
                        equipment.setEquassociated(checkItemsD.getEquassociated());
                        // 设备参数
                        EquipmentParameter ep = new EquipmentParameter();
                        ep.setEquipmentWidth(checkItemsD.getEquipmentlength());
                        ep.setEquipmentBearing(checkItemsD.getEquipmentbearing());
                        ep.setFurnace(apsScheduleConfig.getFurnace());
                        equipment.setEquipmentParameter(ep);
                        // 查询设备锁定的已排程的时间段
                        List<ApsProcessOperationProcessEquDo> processEqus = processOperationProcessEquService.list(new LambdaQueryWrapper<ApsProcessOperationProcessEquDo>()
                                .eq(ApsProcessOperationProcessEquDo::getProcessdeviceid, equIds)
                                .notIn(ApsProcessOperationProcessEquDo::getBlankid, blankids)
                                .ge(ApsProcessOperationProcessEquDo::getPlanenddate, productionScheduleVo.getApsPlanStartDate())
                                .orderByAsc(ApsProcessOperationProcessEquDo::getPlanstartdate)
                        );
                        // 查询当前设备最后一个生产任务、连续生产需要考虑使用
                        List<ApsProcessOperationProcessEquDo> lastpros = processOperationProcessEquService.list(new LambdaQueryWrapper<ApsProcessOperationProcessEquDo>()
                                .eq(ApsProcessOperationProcessEquDo::getProcessdeviceid, equIds)
                                .notIn(ApsProcessOperationProcessEquDo::getBlankid, blankids)
                                .lt(ApsProcessOperationProcessEquDo::getPlanstartdate, productionScheduleVo.getApsPlanStartDate())
                                .orderByDesc(ApsProcessOperationProcessEquDo::getPlanstartdate)
                        );
                        if (lastpros != null && lastpros.size() > 0) {
                            ApsProcessOperationProcessEquDo lastpro = lastpros.get(0);
                            if(processEqus != null && processEqus.size()>0){
                                List<ApsProcessOperationProcessEquDo> hasLasts = processEqus.stream().filter(v -> v.getId().equals(lastpro.getId())).collect(Collectors.toList());
                                if(hasLasts == null || hasLasts.size() == 0){
                                    ApsProcessOperationDo lastop = apsProcessOperationService.getById(lastpro.getProcessid());
                                    // 输出物料
                                    List<ApsProcessOperationOutMaterDo> outMaterDos = apsProcessOperationOutMaterService.list(new LambdaQueryWrapper<ApsProcessOperationOutMaterDo>()
                                            .eq(ApsProcessOperationOutMaterDo::getMainid, lastpro.getProcessid()));
                                    equipment.setLastProcessType(lastop.getProcess());
                                    equipment.setLastProcessEndTime(lastpro.getPlanenddate());
                                    equipment.setLastProcessCutfinishmin(lastop.getCutfinishmin() == null ? null : lastop.getCutfinishmin().intValue());
                                    // 合金+输入物料+宽度+厚度+输出物料厚度
                                    equipment.setLastSeriesProduceMark(lastop.getMetal() + "^_^" + lastop.getProducttype() + "^_^" + lastop.getProwidth() + "^_^" + lastop.getThickness() + "^_^" + outMaterDos.get(0).getThickness());
                                    equipment.setLastProcessCutfinishmin(lastop.getCutfinishmin() == null ? null : lastop.getCutfinishmin().intValue());
                                }
                            }
                        }
                        // 查询相关工序作业
                        Set<String> processIds = new HashSet<>();
                        if (processEqus != null && processEqus.size() > 0) {
                            for (ApsProcessOperationProcessEquDo equs : processEqus) {
                                processIds.add(equs.getProcessid());
                            }
                            List<ApsProcessOperationDo> processOperationDos = null;
                            if (processIds.size() > 0) {
                                processOperationDos = apsProcessOperationService.list(new LambdaQueryWrapper<ApsProcessOperationDo>()
                                        .in(ApsProcessOperationDo::getId, processIds));
                            }

                            List<EquipmentRunTime> equipmentRunTimes = new ArrayList<>();
                            for (ApsProcessOperationProcessEquDo equs : processEqus) {
                                EquipmentRunTime er = new EquipmentRunTime();
                                er.setStartRunTime(equs.getPlanstartdate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                er.setEndRunTime(equs.getPlanenddate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                er.setOccupyType("process");
                                // 设备占用时间设置连续生产标识，参与排程
                                if (processOperationDos != null) {
                                    List<ApsProcessOperationDo> pos = processOperationDos.stream().filter(v -> v.getId().equals(equs.getProcessid())).collect(Collectors.toList());
                                    if (pos != null && pos.size() > 0) {
                                        ApsProcessOperationDo processesDo = pos.get(0);
                                        // 输出物料
                                        List<ApsProcessOperationOutMaterDo> outMaterDos = apsProcessOperationOutMaterService.list(new LambdaQueryWrapper<ApsProcessOperationOutMaterDo>()
                                                .eq(ApsProcessOperationOutMaterDo::getMainid, processesDo.getId()));
                                        er.setProcessType(processesDo.getProcess());
                                        // 合金+输入物料+宽度+厚度
                                        er.setSeriesProduceMark(operationDo.getMetal() + "^_^" + operationDo.getProducttype() + "^_^" + operationDo.getProwidth() + "^_^" + operationDo.getThickness() + "^_^" + outMaterDos.get(0).getThickness());
                                        er.setVolumeMetal(operationDo.getMetal());
                                        er.setVolumeMetalstate(operationDo.getMetalstate());
                                        er.setPrepressworkmin(processesDo.getPrepressworkmin() == null ? null : processesDo.getPrepressworkmin().intValue());
                                        er.setCutfinishmin(processesDo.getCutfinishmin() == null ? null : processesDo.getCutfinishmin().intValue());
                                        // 单卷宽度、重量数据赋值
                                        er.setTotalVolumeWidth(processesDo.getProwidth());
                                        er.setTotalSinglerollweight(processesDo.getSinglerollweight());
                                        er.setTotalThickness(processesDo.getThickness());
                                    }
                                }
                                equipmentRunTimes.add(er);
                            }
                            // 设备日历不可用时间段
                            List<ApsEquipmentCalendarDo> equipmentCalendarDos = apsEquipmentCalendarService.list(
                                    new LambdaQueryWrapper<ApsEquipmentCalendarDo>().ge(ApsEquipmentCalendarDo::getSdstarttime, productionScheduleVo.getApsPlanStartDate())
                                            .eq(ApsEquipmentCalendarDo::getProcessdeviceid, equipment.getBsEquipmentId()));
                            if (equipmentCalendarDos != null && equipmentCalendarDos.size() > 0) {
                                for (ApsEquipmentCalendarDo equipmentCalendarDo : equipmentCalendarDos) {
                                    EquipmentRunTime er = new EquipmentRunTime();
                                    er.setStartRunTime(equipmentCalendarDo.getSdstarttime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                    er.setEndRunTime(equipmentCalendarDo.getSdendtime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                                    er.setOccupyType("maintenance");
                                    equipmentRunTimes.add(er);
                                }
                            }

                            equipment.setEquipmentRunTimes(equipmentRunTimes);
                        }
                        equipmentList.add(equipment);
                    }
                }
            }
        }

        return optionalEquipments;
    }


    /**
     * 前后道工序作业关联关系初始化
     * @param rootOperationDo
     * @param operationProductionProcesses
     * @param operationMaps
     * @param apsBlankOrderVo
     */
    private void processesRelationInit(ApsProcessOperationDo rootOperationDo,Map<String,List<ProductionProcesses>> operationProductionProcesses
            ,Map<String,ApsProcessOperationDo> operationMaps,ApsBlankOrderVo apsBlankOrderVo){
        if(rootOperationDo.getId().equals("b4cf9ca488bb49268a9782ed1396c4f9")){
            System.out.println(rootOperationDo);
        }
        if(StringUtils.isNotBlank(rootOperationDo.getNextprocessid())){
            String[] nextids = rootOperationDo.getNextprocessid().split(",");
            // 前后道工序关联关系处理
            if(rootOperationDo == null){
                throw new CustomException("数据异常，ID为:"+apsBlankOrderVo.getId()+"的坯料计划作业模型初始化，作业为空");
            }else{
                boolean isEnd = true;
                // 当前作业计划加工卷数
                Integer planPres = rootOperationDo.getPlanprocessrall();
                // 下道工序按物料类型分组
                Map<String, List<ProductionProcesses>> wlPros = new HashMap<>();
                if(nextids != null && nextids.length>0){
                    for (String nextid : nextids) {
                        List<ProductionProcesses> productionProcesses = operationProductionProcesses.get(nextid);
                        if(productionProcesses != null && productionProcesses.size()>0 && operationMaps.get(nextid) != null){
                            if(wlPros.containsKey(operationMaps.get(nextid).getPlaninput())){
                                wlPros.get(operationMaps.get(nextid).getPlaninput()).addAll(productionProcesses);
                            }else{
                                wlPros.put(operationMaps.get(nextid).getPlaninput(),productionProcesses);
                            }
                        }
                    }
                }
                // 当前作业和下道工序建立关联关系
                if(wlPros.size()>0){
                    wlPros.forEach((k,v)->{
                        boolean isConnect = true;
                        int vi = 0;
                        List<ProductionProcesses> productionProcesses = operationProductionProcesses.get(rootOperationDo.getId());
                        while (vi<v.size()){
                            for(int i = 0;i <planPres;i++){
                                if(vi>=v.size()){
                                    break;
                                }
                                if(productionProcesses.get(i).getNextProcessesIds() == null){
                                    List<String> ids = new ArrayList<>();
                                    ids.add(v.get(vi).getId());
                                    productionProcesses.get(i).setNextProcessesIds(ids);
                                }else{
                                    productionProcesses.get(i).getNextProcessesIds().add(v.get(vi).getId());
                                }
                                if(v.get(vi).getPreviousProcessesIds() == null){
                                    List<String> ids = new ArrayList<>();
                                    ids.add(productionProcesses.get(i).getId());
                                    v.get(vi).setPreviousProcessesIds(ids);
                                }else{
                                    v.get(vi).getPreviousProcessesIds().add(productionProcesses.get(i).getId());
                                }
                                vi++;
                            }
                        }
                    });
                }
            }
            // 递归处理下道工序数据
            if(nextids != null && nextids.length>0){
                for (String nextid : nextids) {
                    ApsProcessOperationDo apsProcessOperationDo = operationMaps.get(nextid);
                    processesRelationInit(apsProcessOperationDo,operationProductionProcesses,operationMaps,apsBlankOrderVo);
                }
            }
        }
    }

    /**
     * 工序作业模型初始化
     * @param operationDo
     * @param produceOrder
     * @param optionalEquipments
     * @param processesList
     * @param operationProductionProcesses
     */
    private void productionProcessesInit(ApsProcessOperationDo operationDo,ProduceOrder produceOrder,List<String> optionalEquipments
            ,List<ProductionProcesses> processesList,Map<String,List<ProductionProcesses>> operationProductionProcesses){
        // 输出物料
        List<ApsProcessOperationOutMaterDo> outMaterDos = apsProcessOperationOutMaterService.list(new LambdaQueryWrapper<ApsProcessOperationOutMaterDo>()
                .eq(ApsProcessOperationOutMaterDo::getMainid, operationDo.getId()));
        List<ProductionProcesses> operationProcess = new ArrayList<>();
        if(operationDo != null && operationDo.getPlanprocessrall() != null && operationDo.getPlanprocessrall()>0){
            for (Integer i = 0; i < operationDo.getPlanprocessrall(); i++) {
                ProductionProcesses processes = new ProductionProcesses();
                // 工序所属订单
                processes.setProduceOrder(Arrays.asList(new ProduceOrder[]{produceOrder}));
                // 模型ID
                processes.setId(SecurityUtil.getUUID());
                // 业务表主键ID
                List<String> bss = new ArrayList<>();
                bss.add(operationDo.getId());
                processes.setBsProcessesId(bss);
                // 工序任务可选设备
                processes.setOptionalEquipments(optionalEquipments);
                // 批次
                processes.setProducePcNum(operationDo.getPlanprocessrall());
                processes.setProcessType(operationDo.getProcess());
                // 单次加工时长
                processes.setUnitProduceTime(operationDo.getOnceprocessmin().intValue());
                processes.setProduceTime(operationDo.getOnceprocessmin().intValue());
                // 单卷宽度和重量
                processes.setVolumeWidth(operationDo.getProwidth());
                processes.setSinglerollweight(operationDo.getSinglerollweight());
                processes.setVolumeThickness(operationDo.getThickness());
                if (operationDo.getMinflowwaitmin() != null) {
                    processes.setMinWaitTime(operationDo.getMinflowwaitmin().intValue());
                }
                if (operationDo.getMaxflowwaitmin() != null) {
                    processes.setMaxWaitTime(operationDo.getMaxflowwaitmin().intValue());
                }
                // 合金
                processes.setVolumeMetal(operationDo.getMetal());
                if("成退".equals(operationDo.getProcess()) || "中退".equals(operationDo.getProcess())){
                    processes.setVolumeMetalstate(outMaterDos.get(0).getMetalstate());
                }else{
                    processes.setVolumeMetalstate(operationDo.getMetalstate());
                }
                // 连续生产标识设置
                // 合金+输入物料+宽度+输入物料厚度+输出物料厚度（取第一个冷轧工序使用）
                processes.setSeriesProduceMark(operationDo.getMetal() + "^_^" + operationDo.getProducttype() + "^_^" + operationDo.getProwidth() + "^_^" + operationDo.getThickness() + "^_^" + outMaterDos.get(0).getThickness());
                processes.setPrepressworkmin(operationDo.getPrepressworkmin() == null ? null : operationDo.getPrepressworkmin().intValue());
                processes.setCutfinishmin(operationDo.getCutfinishmin() == null ? null : operationDo.getCutfinishmin().intValue());
                // 锁定的作业加上锁定标识
                if (LOCKMARK_Y.equals(operationDo.getLockmark())) {
                    ApsProcessOperationProcessEquDo processEquServiceOne = processOperationProcessEquService.getOne(new LambdaQueryWrapper<ApsProcessOperationProcessEquDo>()
                            .eq(ApsProcessOperationProcessEquDo::getProcessid, operationDo.getId()));
                    if (processEquServiceOne != null) {
                        processes.setIfLock(true);
                        processes.setEquipmentId(processEquServiceOne.getProcessdeviceid());
                        List<String> opeqs = new ArrayList<>();
                        opeqs.add(processEquServiceOne.getProcessdeviceid());
                        processes.setOptionalEquipments(opeqs);
                        processes.setStartTime(processEquServiceOne.getPlanstartdate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                        processes.setEndTime(processEquServiceOne.getPlanenddate().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
                    }
                }
                operationProcess.add(processes);
            }
            processesList.addAll(operationProcess);
            operationProductionProcesses.put(operationDo.getId(),operationProcess);
        }
    }

}
