package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.job.bu3;

import cn.estsh.i3plus.ext.mes.pcn.api.base.ISxPcnHttpService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.bu.IMesBusiConfigService;
import cn.estsh.i3plus.ext.mes.pcn.api.job.bu3.ISxReworkBindSnService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu3.SxReworkRangeModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.mes.pcn.util.PcnHttpUtil;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.BaseResultBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrder;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2023-06-20 11:05
 */
@Slf4j
@Service
public class SxReworkBindSnService implements ISxReworkBindSnService {

    @Autowired
    private MesWorkOrderExtRepository workOrderRepository;

    @Autowired
    private MesReworkOrderRepository reworkOrderRepository;

    @Autowired
    private MesReworkSnRepository reworkSnRepository;

    @Autowired
    private IMesBusiConfigService busiConfigService;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private MesPartExtRepository partExtRepository;

    @Autowired
    private MesOuterPackageRepository outerPackageRepository;

    @Autowired
    private MesOuterPackageDetailRepository outerPackageDetailRepository;

    @Autowired
    private ISxPcnHttpService pcnHttpService;

    @Override
    public void doReworkBindSn(String organizeCode) {

        List<MesWorkOrderExt> workOrderDbList = queryLandedReworkOrder(organizeCode);

        if(CollectionUtils.isEmpty(workOrderDbList)) return;

        MesBusiConfig mesBusiConfig = busiConfigService.queryBusiConfigeByCfgCode(MesPcnExtConstWords.WATER_PURIFIER_CODE, organizeCode);

        //净水器线
        List<String> workCenterCodeList;
        if(mesBusiConfig != null && !StringUtils.isEmpty(mesBusiConfig.getCfgValue())){
            workCenterCodeList = Arrays.stream(mesBusiConfig.getCfgValue().split(MesPcnExtConstWords.COMMA)).collect(Collectors.toList());
        }else{
            workCenterCodeList = new ArrayList<>();
        }

        List<String> orderNoList = workOrderDbList.stream().map(MesWorkOrder::getOrderNo).distinct().collect(Collectors.toList());
        List<String> partNoList = workOrderDbList.stream().map(MesWorkOrder::getPartNo).distinct().collect(Collectors.toList());
        Map<String, MesPartExt> partByPartNoMap = getPartByPartNoMap(organizeCode, partNoList);
        Map<String, MesReworkOrder> reworkOrderByOrderNoMap = getMesReworkOrderByOrderNoMap(organizeCode, orderNoList);

        //待更改关联状态返工范围
        List<SxReworkRangeModel> reworkRangeList = new ArrayList<>();
        //新增返工工单记录（提供给WMS）
        List<MesReworkOrder> reworkOrderList = new ArrayList<>();
        //新增返工条码记录（提供给WMS）
        List<MesReworkSn> reworkSnList = new ArrayList<>();
        //新增返工条码
        List<MesProduceSnRepair> produceSnRepairList = new ArrayList<>();
        Map<String, List<SxReworkRangeModel>> mesReworkRangeByPackageNoMap = getMesReworkRangeByPackageNoMap(organizeCode, partNoList);
        log.info("返工工单绑定条码定时处理任务 --- 返工范围MAP-key：{}", mesReworkRangeByPackageNoMap.keySet());
        String nowTime = TimeTool.getNowTime(true);
        List<MesOuterPackageDetail> outerPackageDetailDbList = new ArrayList<>();
        List<MesOuterPackage> outerPackageDbList = new ArrayList<>();
        for (MesWorkOrderExt workOrder : workOrderDbList) {
            if(workOrder == null || reworkOrderByOrderNoMap.containsKey(workOrder.getOrderNo())) continue;

            if(!mesReworkRangeByPackageNoMap.containsKey(workOrder.getPartNo()) || CollectionUtils.isEmpty(mesReworkRangeByPackageNoMap.get(workOrder.getPartNo()))){
                log.info("返工工单绑定条码定时处理任务 --- 工单{}没有可绑定条码", workOrder.getOrderNo());
                continue;
            }

            List<SxReworkRangeModel> reworkRangeTempList = mesReworkRangeByPackageNoMap.get(workOrder.getPartNo());

            if(workOrder.getQty() > reworkRangeTempList.size()){
                log.info("返工工单绑定条码定时处理任务 --- 工单{}计划数量{}大于可绑定范围数量{},不进行绑定", workOrder.getOrderNo(), workOrder.getQty(), reworkRangeTempList.size());
                continue;
            }

            // 绑定条码
            List<SxReworkRangeModel> updateReworkRangeList = new ArrayList<>();

            // 净水器线
            boolean isWaterPurifierLine = false;
            if(workCenterCodeList.contains(workOrder.getWorkCenterCode())){
                isWaterPurifierLine = true;
                MesPartExt part = partByPartNoMap.get(workOrder.getPartNo());
                if(part == null) {
                    log.info("返工工单绑定条码定时处理任务 --- 工单{}物料{}主数据已被删除或禁用,不进行绑定", workOrder.getOrderNo(), workOrder.getPartNo());
                    continue;
                }

                reworkRangeTempList.sort(Comparator.comparing(SxReworkRangeModel::getOuterPackageNo).thenComparing(SxReworkRangeModel::getWorkTime).thenComparing(SxReworkRangeModel::getOutWcTime));

                Map<String, List<SxReworkRangeModel>> reworkRangeTempMap = reworkRangeTempList.stream().collect(Collectors.groupingBy(SxReworkRangeModel::getOuterPackageNo, LinkedHashMap::new, Collectors.toCollection(LinkedList::new)));

                Iterator<Map.Entry<String, List<SxReworkRangeModel>>> iterator = reworkRangeTempMap.entrySet().iterator();

                while (iterator.hasNext()) {
                    Map.Entry<String, List<SxReworkRangeModel>> entry = iterator.next();

                    List<SxReworkRangeModel> sxReworkRangeModels = reworkRangeTempMap.get(entry.getKey());
                    if ( updateReworkRangeList.size() == workOrder.getQty().intValue() ) {
                        break;
                    }
                    if (part.getQty2() != null && part.getQty2() == sxReworkRangeModels.size()) {
                        updateReworkRangeList.addAll(entry.getValue());
                        iterator.remove();
                    } else {
                        log.info("返工工单绑定条码定时处理任务 --- 工单{}物料{}大包装数量【{}】与大包装条码关联小包装条码个数【{}】不一致，不进行绑定", workOrder.getOrderNo(), workOrder.getPartNo(), part.getQty2() == null ? 0.0 : part.getQty2().intValue(), sxReworkRangeModels.size());
                    }
                }

                //for (String outerPackageNo : reworkRangeTempMap.keySet()) {
                //    List<SxReworkRangeModel> sxReworkRangeModels = reworkRangeTempMap.get(outerPackageNo);
                //    if (part.getQty2() != null && part.getQty2() == sxReworkRangeModels.size()) {
                //        updateReworkRangeList.addAll(reworkRangeTempMap.remove(outerPackageNo));
                //    } else {
                //        log.info("返工工单绑定条码定时处理任务 --- 工单{}物料{}大包装数量【{}】与大包装条码关联小包装条码个数【{}】不一致，不进行绑定", workOrder.getOrderNo(), workOrder.getPartNo(), part.getQty2() == null ? 0.0 : part.getQty2().intValue(), sxReworkRangeModels.size());
                //    }
                //}

                if (updateReworkRangeList.size() != workOrder.getQty().intValue()) {
                    log.info("返工工单绑定条码定时处理任务 --- 工单{}物料{}大包装数量为{}，不进行绑定", workOrder.getOrderNo(), workOrder.getPartNo(), part.getQty2() == null ? 0.0 : part.getQty2().intValue());
                    continue;
                }

                reworkRangeTempList = reworkRangeTempMap.values().stream()
                        .flatMap(List::stream)
                        .collect(Collectors.toList());

            } else {
                updateReworkRangeList = reworkRangeTempList.subList(0, workOrder.getQty().intValue());
                reworkRangeTempList = reworkRangeTempList.subList(workOrder.getQty().intValue(), reworkRangeTempList.size());
            }

            // 绑定条码
            //updateReworkRangeList = reworkRangeTempList.subList(0, workOrder.getQty().intValue());
            updateReworkRangeList.forEach(o -> {
                o.setReworkOrderNo(workOrder.getOrderNo());
                o.setBindStatus(MesPcnExtEnumUtil.REWORK_RANGE_IS_BAND.YES.getValue());
                o.setModifyDatetime(nowTime);
                o.setModifyUser(workOrder.getModifyUser());
            });
            //reworkRangeTempList = reworkRangeTempList.subList(workOrder.getQty().intValue(), reworkRangeTempList.size());
            mesReworkRangeByPackageNoMap.put(workOrder.getPartNo(), reworkRangeTempList);

            if (isWaterPurifierLine) {
                Map<String, List<SxReworkRangeModel>> reworkRangeByOuterPackNoMap = updateReworkRangeList.stream().collect(Collectors.groupingBy(SxReworkRangeModel::getOuterPackageNo));
                for (String outerPackageNo : reworkRangeByOuterPackNoMap.keySet()) {
                    SxReworkRangeModel mesReworkRange = reworkRangeByOuterPackNoMap.get(outerPackageNo).stream().findFirst().get();
                    addReworkSnList(reworkSnList, nowTime, workOrder, mesReworkRange, mesReworkRange.getOuterPackageNo());
                }
                for (SxReworkRangeModel mesReworkRange : updateReworkRangeList) {
                    addProduceSnRepairList(organizeCode, produceSnRepairList, nowTime, workOrder, mesReworkRange);
                }

            } else {
                for (SxReworkRangeModel mesReworkRange : updateReworkRangeList) {
                    addReworkSnList(reworkSnList, nowTime, workOrder, mesReworkRange, mesReworkRange.getPackageNo());
                    addProduceSnRepairList(organizeCode, produceSnRepairList, nowTime, workOrder, mesReworkRange);
                }
            }

            //Map<String, SxReworkRangeModel> reworkRangeByOuterPackageNoMap = updateReworkRangeList.stream().collect(Collectors.toMap(SxReworkRangeModel::getOuterPackageNo, Function.identity(), (x, y) -> y));
            List<MesOuterPackage> outerPackageDbByOuterPackNoList = queryOuterPackageList(organizeCode, updateReworkRangeList);
            for (MesOuterPackage outerPackage : outerPackageDbByOuterPackNoList) {
                //if(!reworkRangeByOuterPackageNoMap.containsKey(outerPackage.getOuterPackageNo())) {
                //    log.info("返工工单绑定条码定时处理任务 --- 大包装条码{}未关联返工单,暂不解绑", outerPackage.getOuterPackageNo());
                //    continue;
                //}
                //SxReworkRangeModel mesReworkRange = reworkRangeByOuterPackageNoMap.get(outerPackage.getOuterPackageNo());
                outerPackage.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                outerPackage.setModifyUser(workOrder.getModifyUser());
                outerPackage.setModifyDatetime(nowTime);
                outerPackage.setQty(0.0);
                outerPackage.setShiftCode("");
                outerPackage.setLotNo("");
                outerPackage.setWorkTime("");
                outerPackage.setWorkCellName("");
                outerPackage.setWorkCenterCode("");
                outerPackage.setWorkCenterName("");
                outerPackage.setWorkOrderType(0);
                outerPackage.setWorkOrderNo(workOrder.getOrderNo());
                outerPackage.setIsSealed(MesPcnExtEnumUtil.PACKAGE_IS_SEALED.UNSEALED.getValue());
            }

            List<MesOuterPackageDetail> outerPackageDetailDbByWorkOrderList = queryOuterPackageDetailList(organizeCode, updateReworkRangeList);

            for (MesOuterPackageDetail outerPackageDetail : outerPackageDetailDbByWorkOrderList) {
                outerPackageDetail.setBindStatus(MesPcnExtEnumUtil.PACKAGE_BIND_STATUS.UNBIND.getValue());
                outerPackageDetail.setWorkOrderNo(workOrder.getOrderNo());
                outerPackageDetail.setWorkCellCode("");
                outerPackageDetail.setWorkCenterCode("");
                outerPackageDetail.setWorkCellName("");
                outerPackageDetail.setWorkCenterName("");
                outerPackageDetail.setModifyUser(workOrder.getModifyUser());
                outerPackageDetail.setModifyDatetime(nowTime);
            }

            outerPackageDetailDbList.addAll(outerPackageDetailDbByWorkOrderList);
            outerPackageDbList.addAll(outerPackageDbByOuterPackNoList);
            reworkRangeList.addAll(updateReworkRangeList);
            addReworkOrderList(reworkOrderList, nowTime, workOrder);
        }

        //保存入库
        if(!CollectionUtils.isEmpty(reworkOrderList)){

            Map<String, String> params = new HashMap<>();
            params.put(MesPcnExtConstWords.MODEL, JSONObject.toJSONString(reworkRangeList));
            params.put(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
            params.put(MesPcnExtConstWords.USER_NAME, "JOB");
            String requestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.SAVE_REWORK_RANGE_URL);
            String data = PcnHttpUtil.doPost(requestUrl, params);
            BaseResultBean baseResultBean = null;
            if (!StringUtils.isEmpty(data)) {
                baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
            } else {
                log.error("HTTP[{}]调用主接口失败", requestUrl);
            }
            if (null == baseResultBean || !baseResultBean.success) {
                log.error("HTTP[{}]调用主接口失败", requestUrl);
                return;
            }

            reworkOrderRepository.saveAll(reworkOrderList);
            produceSnRepairRepository.saveAll(produceSnRepairList);
            reworkSnRepository.saveAll(reworkSnList);
            Map<String, SxReworkRangeModel> reworkRangeByPackageNoMap = reworkRangeList.stream().collect(Collectors.toMap(SxReworkRangeModel::getPackageNo, Function.identity(), (x, y) -> y));

            Map<String, SxReworkRangeModel> reworkRangeBySerialNumberMap = reworkRangeList.stream().collect(Collectors.toMap(SxReworkRangeModel::getSerialNumber, Function.identity(), (x, y) -> y));
            List<MesPackageExt> packageExtList = queryPackageByNoList(organizeCode, reworkRangeList);

            List<MesProduceSnExt> produceSnExtList = queryProduceSnList(organizeCode, reworkRangeList);
            for (MesPackageExt packageExt : packageExtList) {
                SxReworkRangeModel mesReworkRange = reworkRangeByPackageNoMap.get(packageExt.getPackageNo());
                packageExt.setLastWorkOrderNo(mesReworkRange.getReworkOrderNo());
                packageExt.setModifyDatetimeExt(mesReworkRange.getModifyDatetime());
                packageExt.setModifyUserExt(mesReworkRange.getModifyUser());
                packageExt.setModifyDatetime(mesReworkRange.getModifyDatetime());
                packageExt.setModifyUser(mesReworkRange.getModifyUser());
                packageExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                packageExt.setSystemSyncStatusExt(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            }
            for (MesProduceSnExt produceSnExt : produceSnExtList) {
                SxReworkRangeModel mesReworkRange = reworkRangeBySerialNumberMap.get(produceSnExt.getSerialNumber());
                produceSnExt.setSnStatus(MesPcnExtEnumUtil.PRODUCE_SN_STATUS.REPAIR.getValue());
                produceSnExt.setProcessCode("");
                produceSnExt.setNextProcessCode("");
                produceSnExt.setLastWorkOrderNo(mesReworkRange.getReworkOrderNo());
                produceSnExt.setModifyUser(mesReworkRange.getModifyUser());
                produceSnExt.setModifyUserExt(mesReworkRange.getModifyUser());
                produceSnExt.setModifyDatetimeExt(nowTime);
                produceSnExt.setModifyDatetime(nowTime);
                produceSnExt.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                produceSnExt.setSystemSyncStatusExt(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
            }

            packageExtRepository.saveAll(packageExtList);
            produceSnExtRepository.saveAll(produceSnExtList);
            if(!CollectionUtils.isEmpty(outerPackageDbList)) outerPackageRepository.saveAll(outerPackageDbList);
            if(!CollectionUtils.isEmpty(outerPackageDetailDbList)) outerPackageDetailRepository.saveAll(outerPackageDetailDbList);
        }
    }

    private void addReworkSnList(List<MesReworkSn> reworkSnList, String nowTime, MesWorkOrderExt workOrder, SxReworkRangeModel mesReworkRange, String packageNo) {
        MesReworkSn reworkSn = new MesReworkSn();
        BeanUtils.copyProperties(mesReworkRange, reworkSn);
        reworkSn.setCreateUser(workOrder.getModifyUser());
        reworkSn.setCreateDatetime(nowTime);
        reworkSn.setModifyUser(workOrder.getModifyUser());
        reworkSn.setModifyDatetime(nowTime);
        reworkSn.setPartName(mesReworkRange.getPartName());
        reworkSn.setPackageNo(packageNo);
        reworkSn.setErpWarehouse(workOrder.getErpWarehouse());
        reworkSn.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        reworkSnList.add(reworkSn);
    }

    private List<MesOuterPackage> queryOuterPackageList(String organizeCode, List<SxReworkRangeModel> reworkRangeList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(reworkRangeList.stream().map(SxReworkRangeModel::getOuterPackageNo).distinct().collect(Collectors.toList()), MesPcnExtConstWords.OUTER_PACKAGE_NO, packBean);
        return outerPackageRepository.findByHqlWhere(packBean);
    }

    private List<MesOuterPackageDetail> queryOuterPackageDetailList(String organizeCode, List<SxReworkRangeModel> reworkRangeList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(reworkRangeList.stream().map(SxReworkRangeModel::getOuterPackageNo).distinct().collect(Collectors.toList()), MesPcnExtConstWords.OUTER_PACKAGE_NO, packBean);
        return outerPackageDetailRepository.findByHqlWhere(packBean);
    }

    private Map<String, MesPartExt> getPartByPartNoMap(String organizeCode, List<String> partNoList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(partNoList, MesPcnExtConstWords.PART_NO, packBean);
        List<MesPartExt> partDbList = partExtRepository.findByHqlWhere(packBean);
        return partDbList.stream().collect(Collectors.toMap(MesPartExt::getPartNo, Function.identity(), (x,y)-> y));
    }

    private void addProduceSnRepairList(String organizeCode, List<MesProduceSnRepair> produceSnRepairList, String nowTime, MesWorkOrder workOrder, SxReworkRangeModel mesReworkRange) {
        MesProduceSnRepair produceSnRepair = new MesProduceSnRepair();
        produceSnRepair.setSerialNumber(mesReworkRange.getSerialNumber());
        produceSnRepair.setProductSn(mesReworkRange.getSerialNumber());
        produceSnRepair.setPartNo(mesReworkRange.getPartNo());
        produceSnRepair.setPartNameRdd(mesReworkRange.getPartName());
        produceSnRepair.setWorkCenterCode(workOrder.getWorkCenterCode());
        produceSnRepair.setWorkCellCode("");
        produceSnRepair.setWorkOrderNo(workOrder.getOrderNo());
        produceSnRepair.setInitWorkOrderNo(mesReworkRange.getWorkOrderNo());
        produceSnRepair.setSnType(MesPcnExtEnumUtil.PRODUCE_SN_TYPE.REWORK_SN.getValue());
        produceSnRepair.setOrganizeCode(organizeCode);
        produceSnRepair.setModifyUser(workOrder.getModifyUser());
        produceSnRepair.setModifyDatetime(nowTime);
        produceSnRepair.setCreateUser(workOrder.getModifyUser());
        produceSnRepair.setCreateDatetime(nowTime);
        produceSnRepair.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        produceSnRepairList.add(produceSnRepair);
    }

    private List<MesProduceSnExt> queryProduceSnList(String organizeCode, List<SxReworkRangeModel> reworkRangeList) {
        List<String> serialNumberList = reworkRangeList.stream().map(SxReworkRangeModel::getSerialNumber).collect(Collectors.toList());
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(serialNumberList, MesPcnExtConstWords.SERIAL_NUMBER, packBean);
        return produceSnExtRepository.findByHqlWhere(packBean);
    }

    private List<MesPackageExt> queryPackageByNoList(String organizeCode, List<SxReworkRangeModel> reworkRangeList) {
        List<String> packageNoList = reworkRangeList.stream().map(SxReworkRangeModel::getPackageNo).collect(Collectors.toList());
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(packageNoList, MesPcnExtConstWords.PACKAGENO, packBean);
        return packageExtRepository.findByHqlWhere(packBean);
    }

    private void addReworkOrderList(List<MesReworkOrder> reworkOrderList, String nowTime, MesWorkOrder workOrder) {
        MesReworkOrder reworkOrder = new MesReworkOrder();
        reworkOrder.setModifyDatetime(nowTime);
        reworkOrder.setCreateDatetime(nowTime);
        reworkOrder.setCreateUser(workOrder.getModifyUser());
        reworkOrder.setModifyUser(workOrder.getModifyUser());
        reworkOrder.setReworkOrderNo(workOrder.getOrderNo());
        reworkOrder.setPartNo(workOrder.getPartNo());
        reworkOrder.setPartName(workOrder.getPartNameRdd());
        reworkOrder.setOrganizeCode(workOrder.getOrganizeCode());
        reworkOrder.setWorkCenterCode(workOrder.getWorkCenterCode());
        reworkOrder.setWorkOrderStatus(MesPcnExtEnumUtil.WORK_ORDER_STATUS.CREATE.getValue());
        reworkOrder.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        reworkOrderList.add(reworkOrder);
    }

    private Map<String, MesReworkOrder> getMesReworkOrderByOrderNoMap(String organizeCode, List<String> orderNoList) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getInPackList(orderNoList, MesPcnExtConstWords.REWORK_ORDER_NO, packBean);
        List<MesReworkOrder> reworkOrderDbList = reworkOrderRepository.findByHqlWhere(packBean);
        return CollectionUtils.isEmpty(reworkOrderDbList) ? new HashMap<>() :
        reworkOrderDbList.stream().collect(Collectors.toMap(MesReworkOrder::getReworkOrderNo, Function.identity(), (x, y) -> x));
    }

    private Map<String, List<SxReworkRangeModel>> getMesReworkRangeByPackageNoMap(String organizeCode, List<String> partNoList) {
        Map<String, String> params = new HashMap<>();
        params.put(MesPcnExtConstWords.ORGANIZE_CODE, organizeCode);
        params.put(MesPcnExtConstWords.PART_NO, JSONObject.toJSONString(partNoList));
        params.put(MesPcnExtConstWords.BIND_STATUS, MesPcnExtEnumUtil.REWORK_RANGE_IS_BAND.NO.getValue() + "");
        //params.put(MesPcnExtConstWords.MODEL, JSONObject.toJSONString(new SxReworkRangeQueryModel(organizeCode, MesPcnExtEnumUtil.REWORK_RANGE_IS_BAND.NO.getValue(), partNoList)));
        String requestUrl = pcnHttpService.getRequestUrl(organizeCode, MesPcnExtConstWords.QUERY_REWORK_RANGE_LIST_URL);
        String data = null;
        data = PcnHttpUtil.doPost(requestUrl, params);
        BaseResultBean baseResultBean = null;
        List<SxReworkRangeModel> reworkRangeDbList = new ArrayList<>();
        if (!StringUtils.isEmpty(data)) {
            baseResultBean = JsonUtilTool.decode(data, BaseResultBean.class);
        } else {
            log.error("HTTP[{}]调用qms获取返工范围信息接口失败", requestUrl);
        }

        if (null != baseResultBean && baseResultBean.success
                && null != baseResultBean.getResultList() && baseResultBean.getResultList().size() > 0) {
            List<LinkedHashMap> resultObject = (List<LinkedHashMap>) baseResultBean.getResultList();
            reworkRangeDbList = JsonUtilTool.toList(JSONObject.toJSONString(resultObject), SxReworkRangeModel.class);
        }

        log.info("getMesReworkRangeByPackageNoMap 返工范围数据数量 {}", reworkRangeDbList.size());
        log.info("getMesReworkRangeByPackageNoMap 返工范围数据： {}", reworkRangeDbList);
        return CollectionUtils.isEmpty(reworkRangeDbList) ? new HashMap<>() :
                reworkRangeDbList.stream().collect(Collectors.groupingBy(SxReworkRangeModel::getPartNo, Collectors.collectingAndThen(
                        Collectors.toList(), list -> {
                            list.sort(Comparator.comparing(SxReworkRangeModel::getWorkTime).thenComparing(SxReworkRangeModel::getOutWcTime));
                            return list;
                        }
                )));
    }

    private List<MesWorkOrderExt> queryLandedReworkOrder(String organizeCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.WORK_ORDER_STATUS.LANDED.getValue(), MesPcnExtConstWords.WORK_ORDER_STATUS, packBean);
        DdlPreparedPack.getNumEqualPack(MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue(), MesPcnExtConstWords.WORK_ORDER_TYPE, packBean);
        packBean.setOrderByStr(" order by startTime ");
        return workOrderRepository.findByHqlWhere(packBean);
    }
}
