package cn.estsh.i3plus.ext.mes.pcn.apiservice.schedulejob;


import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionRecordService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesWorkOrderService;
import cn.estsh.i3plus.platform.common.tool.JsonUtilTool;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesProductionRecord;
import cn.estsh.i3plus.pojo.mes.repository.MesProductionRecordRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.i3plus.pojo.model.wms.WmsJobParamModel;
import cn.estsh.impp.framework.boot.exception.ImppBusiException;
import cn.estsh.impp.framework.boot.init.ApplicationProperties;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author castle,暂时没有客供品移库
 * @version 1.0
 * @date 2021/2/2 16:44
 **/
@Slf4j
@DisallowConcurrentExecution
@Component
@ApiOperation("非排序报工job")
public class MesReportNoSortJob extends BaseMesScheduleJob {

    @Autowired
    private IMesWorkOrderService workOrderService;

    @Autowired
    private MesProductionRecordRepository productionRecordRao;
    @Autowired
    private IMesProductionRecordService productionRecordService;

    public MesReportNoSortJob() {
        super(MesReportNoSortJob.class, "非排序报工JOB");
    }
    @Override
    @Transactional
    public void executeMesJob(JobExecutionContext context, ApplicationProperties applicationProperties) {
        List<WmsJobParamModel> wmsJobParamModelList = JsonUtilTool.toList(this.getJobParam(), WmsJobParamModel.class);
        if (!CollectionUtils.isEmpty(wmsJobParamModelList)) {
            for (WmsJobParamModel wmsJobParamModel : wmsJobParamModelList) {
                try {
                    long startTime = System.currentTimeMillis();
                    // 处理无工单
                    handlerNoOrder(wmsJobParamModel.getOrganizeCode(), "JOB");
                    // 处理有工单
                    handlerHasOrder(wmsJobParamModel.getOrganizeCode(), "JOB");
                    long endTime = System.currentTimeMillis();
                    log.info("工厂{}非排序报工JOB --- END --- 耗时: {} ms", wmsJobParamModel.getOrganizeCode(), endTime - startTime);
                } catch (Exception e) {
                    log.info("工厂{}非排序报工JOB 执行失败{}", wmsJobParamModel.getOrganizeCode(), e);
                }
            }
        }else{
            log.info("非排序报工JOB 参数不能为空");
        }
    }

    private void handlerNoOrder(String organizeCode, String userName) {
        List<MesProductionRecord> unReportMesProduceSn = workOrderService.getUnReportMesProduceSn(organizeCode);
        if (CollectionUtils.isEmpty(unReportMesProduceSn)) {
            LOGGER.error("无加工单加工记录中没有数据，无需处理");
            return;
        }
        for (MesProductionRecord mesProductionRecord : unReportMesProduceSn) {
            LOGGER.info("----------报工开始-------{}", mesProductionRecord.getProductSn());
            workOrderService.doProductReportByRecord(mesProductionRecord, organizeCode, userName);
            LOGGER.info("----------报工结束-------{}", mesProductionRecord.getProductSn());

        }

    }

    private void handlerHasOrder(String organizeCode, String userName) {
        List<MesProductionRecord> unReportMesProduceSn = workOrderService.getUnReportHasOrderMesProduceSn(organizeCode);
        if (CollectionUtils.isEmpty(unReportMesProduceSn)) {
            LOGGER.error("有加工单加工记录中没有数据，无需处理");
            return;
        }
        try {
            Map<String, Integer> map = new HashMap<>();
            for (MesProductionRecord mesProductionRecord : unReportMesProduceSn) {
                workOrderService.doProductHasOrderReportByRecord(mesProductionRecord, organizeCode, userName);
            }

        } catch (ImppBusiException e) {
            //LOGGER.error("条码:{}报工失败", unReportMesProduceSn.get(0).getProductSn(), e.getErrorDetail());
            //productionRecordService.updateProductionRecord(organizeCode, userName, unReportMesProduceSn.get(0).getProductSn(), e.getErrorDetail());
        }
    }


    private void updateProductionRecord(String organizeCode, String userName, String sn) {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);

        DdlPreparedPack.getStringEqualPack(sn, "productSn", ddlPackBean);
        productionRecordRao.updateByProperties(new String[]{"modifyUser", "modifyDatetime","reportStatus"},
                new Object[]{userName, TimeTool.getNowTime(true), MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_20.getValue() },ddlPackBean);
    }
    private void updateProductionRecord(String organizeCode, String userName, String sn, String errorMsg) {
        DdlPackBean ddlPackBean = DdlPackBean.getDdlPackBean(organizeCode);

        DdlPreparedPack.getStringEqualPack(sn, "productSn", ddlPackBean);
        productionRecordRao.updateByProperties(new String[]{"modifyUser", "modifyDatetime","reportStatus", "remark"},
                new Object[]{userName, TimeTool.getNowTime(true), MesExtEnumUtil.REPORT_STATUS.REPORT_STATUS_40.getValue(), errorMsg },ddlPackBean);
    }
}
