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

import cn.estsh.i3plus.ext.mes.pcn.api.job.jx.IJxRestoreProductDataService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.SxWorkCellLineOffRecord;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.SxWorkCellLineOffRecordRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesProductData;
import cn.estsh.i3plus.pojo.mes.repository.MesProductDataRepository;
import lombok.extern.slf4j.Slf4j;
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.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: wangjie
 * @CreateDate: 2019/8/23 1:16 PM
 * @Description: 嘉兴补录检测数据定时任务
 **/
@Slf4j
@Service
public class JxRestoreProductDataService implements IJxRestoreProductDataService {

    @Autowired
    private SxWorkCellLineOffRecordRepository workCellLineOffRecordRepository;

    @Autowired
    private MesProductDataRepository productDataRepository;

    @Override
    public void doRestoreProductData(Map<String, Object> paramMap) {

        String organizeCode = (String) paramMap.get(MesPcnExtConstWords.ORGANIZE_CODE);

        Integer limit = paramMap.containsKey(MesPcnExtConstWords.LIMIT) ? (Integer) paramMap.get(MesPcnExtConstWords.LIMIT) : 100;

        List<MesProductData> productDataList = findProductDataList(organizeCode, limit);

        log.info("工厂{} RESTORE PRODUCT DATA JOB --- EXEC --- PRODUCT DATA SIZE:[{}]", organizeCode, CollectionUtils.isEmpty(productDataList) ? 0 : productDataList.size());

        if (CollectionUtils.isEmpty(productDataList)) return;

        doRestoreProductData(organizeCode, getProductDataMapByPs(productDataList), true);

        doRestoreProductData(organizeCode, getProductDataMapBySn(productDataList), false);

    }

    private Map<String, List<MesProductData>> getProductDataMapByPs(List<MesProductData> productDataList) {
        return CollectionUtils.isEmpty(productDataList) ? null :
                productDataList.stream().filter(o -> (null != o && !StringUtils.isEmpty(o.getProductSn()))).collect(Collectors.groupingBy(MesProductData::getProductSn));
    }

    private Map<String, List<MesProductData>> getProductDataMapBySn(List<MesProductData> productDataList) {
        return CollectionUtils.isEmpty(productDataList) ? null :
                productDataList.stream().filter(o -> (null != o && StringUtils.isEmpty(o.getProductSn()) && !StringUtils.isEmpty(o.getSerialNumber()))).collect(Collectors.groupingBy(MesProductData::getSerialNumber));
    }

    private List<MesProductData> findProductDataList(String organizeCode, Integer limit) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getNumberSmallerEqualPackContainsZero(0, MesPcnExtConstWords.SYSTEM_SYNC_STATUS, packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.SYSTEM_SYNC_STATUS}, packBean);
        return productDataRepository.findByHqlTopWhere(packBean, limit);
    }

    private SxWorkCellLineOffRecord getWorkCellLineOffRecord(String organizeCode, String sn, Boolean flag) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        if (flag) DdlPreparedPack.getStringEqualPack(sn, MesPcnExtConstWords.PRODUCT_SN, packBean);
        else DdlPreparedPack.getStringEqualPack(sn, MesPcnExtConstWords.SERIAL_NUMBER, packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.CREATE_DATE_TIME}, packBean);
        return workCellLineOffRecordRepository.getByProperty(packBean);
    }

    private void doRestoreProductData(String organizeCode, Map<String, List<MesProductData>> productDataMap, Boolean flag) {

        for (Map.Entry<String, List<MesProductData>> entry : productDataMap.entrySet()) {

            if (null == entry) continue;

            SxWorkCellLineOffRecord workCellLineOffRecord = getWorkCellLineOffRecord(organizeCode, entry.getKey(), flag);

            Integer count = doRestoreProductData(entry.getValue(), workCellLineOffRecord);

            log.info("工厂{} RESTORE PRODUCT DATA JOB --- EXEC --- SN:{} --- {} --- QTY:[{}] --- COMPLETED:[{}]", organizeCode, entry.getKey(), flag ? "产品条码" : "过程条码", entry.getValue().size(), count);

        }
    }

    private Integer doRestoreProductData(List<MesProductData> productDataList, SxWorkCellLineOffRecord workCellLineOffRecord) {
        Integer count = 0;
        if (null != workCellLineOffRecord) count = productDataList.size();
        for (MesProductData productData : productDataList) {
            if (null == productData) continue;
            if (count == 0) productData.setSystemSyncStatus(productData.getSystemSyncStatus() - 1);
            else {
                productData.setProductSn(workCellLineOffRecord.getProductSn());
                productData.setOrderNo(workCellLineOffRecord.getWorkOrderNo());
                productData.setPartNo(workCellLineOffRecord.getPartNo());
                productData.setPartDesc(workCellLineOffRecord.getPartNameRdd());
                productData.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                ConvertBean.serviceModelUpdate(productData, MesPcnExtConstWords.JOB);
            }
            productDataRepository.save(productData);
        }
        return count;
    }

}
