package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.step.ep;

import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ep.EpPartDivulgeCheckRecordModel;
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.serviceimpl.base.BaseStepService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.mes.bean.MesPackageDetail;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.model.StepResult;
import cn.estsh.i3plus.pojo.mes.repository.MesPackageDetailRepository;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION: 24小时泄露检测校验判定结果与条码有效性工步
 * @USER: xinwang.yi
 * @DATE: 2021-12-21 16:55
 */
@Slf4j
@Service("epPartDivulgeCheckSnStepService")
public class EpPartDivulgeCheckSnStepService extends BaseStepService {

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private MesPackageDetailRepository packageDetailRepository;

    @Autowired
    private MesProduceSnExtRepository produceSnExtRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private MesSubassemblyRemadeRecordRepository subassemblyRemadeRecordRepository;

    @Autowired
    private MesPartDivulgeCheckCfgRepository partDivulgeCheckCfgRepository;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("epPartDivulgeCheckSnStepService[execute] 参数：{}", reqBean);

        StationResultBean resultBean = new StationResultBean();
        String err;

        //检测结果
        Integer checkResult = Integer.valueOf(reqBean.getDataMap().get(MesPcnExtConstWords.RADIO).toString());
        String divulgeValue = (String) reqBean.getDataMap().get(MesPcnExtConstWords.DIVULGE_VALUE_CAPITAL);

        if(checkResult == null){
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "检测结果无效"));
            this.sendMessage(reqBean, resultBean, "检测结果为空", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            return StepResult.getNonComplete();
        }else{
            if(StringUtils.isEmpty(MesPcnExtEnumUtil.DIVULGE_CHECK_RESULT.valueOfDescription(checkResult))){
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "检测结果无效"));
                this.sendMessage(reqBean, resultBean, "检测结果无效", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete();
            }

            if(checkResult == MesPcnExtEnumUtil.DIVULGE_CHECK_RESULT.OK.getValue()){
                try {
                    if(!StringUtils.isEmpty(divulgeValue)){
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参泄露值[%s]无效"), divulgeValue);
                        this.sendMessage(reqBean, resultBean, "入参存在无效的泄露值", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                } catch (Exception e) {
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参泄露值[%s]无效"), divulgeValue);
                    this.sendMessage(reqBean, resultBean, "入参存在无效的泄露值", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
            }else if(checkResult == MesPcnExtEnumUtil.DIVULGE_CHECK_RESULT.NG.getValue()){

                if(StringUtils.isEmpty(divulgeValue) || divulgeValue.equals("null")){
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参泄露值[%s]无效"), divulgeValue);
                    this.sendMessage(reqBean, resultBean, "请输入泄露值", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }

                String[] standar = divulgeValue.split(MesPcnExtConstWords.DECIMAL_POINT);
                if(standar != null && standar.length == 2 && standar[1].length()>=2){
                    err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参泄露值[%s]无效"), divulgeValue);
                    this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return StepResult.getNonComplete(err);
                }
            }
            String packageNo = reqBean.getScanInfo();
            if(StringUtils.isEmpty(packageNo)){
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少包装条码"));
                this.sendMessage(reqBean, resultBean, "入参缺少包装条码" , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(packageNo,MesPcnExtConstWords.PACKAGENO, packBean);
            MesPackageExt packageExt = packageExtRepository.getByProperty(packBean);

            if(packageExt == null) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]不存在"), packageNo);
                this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(packageExt.getPartNo(), MesPcnExtConstWords.PART_NO, packBean);
            MesPartDivulgeCheckCfg partDivulgeCheckCfg = partDivulgeCheckCfgRepository.getByProperty(packBean);

            if(partDivulgeCheckCfg == null){
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]未关联24小时泄露检测物料配置"), packageNo);
                this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                return StepResult.getNonComplete(err);
            }

            packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(packageNo, MesPcnExtConstWords.PACKAGENO, packBean);
            List<MesPackageDetail> packageDetail = packageDetailRepository.findByHqlWhere(packBean);
            SimpleDateFormat format = new SimpleDateFormat(MesPcnExtConstWords.DATETIME_FORMAT);
            EpPartDivulgeCheckRecordModel partDivulgeCheckRecordModel = new EpPartDivulgeCheckRecordModel();
            if(!CollectionUtils.isEmpty(packageDetail)){
                Iterator<MesPackageDetail> detailIterator = packageDetail.stream().iterator();

                while (detailIterator.hasNext()){
                    MesPackageDetail mesPackageDetail = detailIterator.next();
                    String serialNumber = mesPackageDetail.getSerialNumber();

                    packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
                    DdlPreparedPack.getStringEqualPack(serialNumber, MesPcnExtConstWords.SERIAL_NUMBER, packBean);
                    MesProduceSnExt produceSn = produceSnExtRepository.getByProperty(packBean);

                    if(produceSn == null){
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s] 无效"), packageNo, serialNumber);
                        this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }

                    if(produceSn.getQcStatus()!= null && produceSn.getQcStatus() == MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.DEFECTED.getValue() ){
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]质量状态[%s]"),packageNo, serialNumber,MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.DEFECTED.getDescription());
                        this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }

                    if(produceSn.getSnStatus()!= null && produceSn.getSnStatus() == MesPcnExtEnumUtil.PRODUCE_SN_STATUS.ERR_OFFLINE.getValue() ){
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]状态为[%s]"), packageNo, serialNumber,MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.DEFECTED.getDescription());
                        this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                    //下线时间
                    String outWcTime;
                    String workOrderNo;
                    String shiftCode;
                    String workTime;
                    String lotNo;
                    //判断条码的最终工单号与生产工单号是否一致
                    if(produceSn.getWorkOrderNo().equals(produceSn.getLastWorkOrderNo())){
                        try {
                            Date outWorkCenterTime = format.parse(produceSn.getOutWorkCenterTime());
                            Date nowTime = new Date();
                            Long resultTemp = nowTime.getTime() - outWorkCenterTime.getTime();
                            Double result = resultTemp * 1.0 / (1000 * 60 * 60);
                            outWcTime = produceSn.getOutWorkCenterTime();
                            if(result < 24) {
                                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]下线时间[%s],未满24小时,不能检测"), packageNo, produceSn.getProductSn(),produceSn.getOutWorkCenterTime());
                                this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                                return StepResult.getNonComplete(err);
                            }
                            workOrderNo = produceSn.getWorkOrderNo();
                            shiftCode = produceSn.getShiftCode();
                            workTime = produceSn.getWorkTime();
                            lotNo = produceSn.getLotNo();
                        } catch (ParseException e) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]下线时间[%s]格式不符合或为空"), packageNo, serialNumber,produceSn.getOutWorkCenterTime());
                            this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            return StepResult.getNonComplete(err);
                        }

                    }else{
                        packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
                        DdlPreparedPack.getStringEqualPack(produceSn.getSerialNumber(),MesPcnExtConstWords.SERIAL_NUMBER,packBean);
                        DdlPreparedPack.getStringEqualPack(produceSn.getLastWorkOrderNo(),MesPcnExtConstWords.WORK_ORDER_NO,packBean);
                        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.OUT_WC_TIME}, packBean);
                        MesProduceSnRepair produceSnRepair = produceSnRepairRepository.getByProperty(packBean);

                        if(produceSnRepair == null){
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]状态为[%s]"), packageNo, serialNumber,MesPcnExtEnumUtil.PRODUCE_SN_QC_STATUS.DEFECTED.getDescription());
                            this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            return StepResult.getNonComplete();
                        }
                        outWcTime = produceSnRepair.getOutWorkCenterTime();
                        try {
                            Date outWorkCenterTime = format.parse(produceSnRepair.getOutWorkCenterTime());
                            Date nowTime = new Date();
                            Long resultTemp = nowTime.getTime() - outWorkCenterTime.getTime();
                            Double result = resultTemp * 1.0 / (1000 * 60 * 60);

                            if(result < 24) {
                                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]下线时间[%s],未满24小时,不能检测"), packageNo, produceSn.getProductSn(),produceSnRepair.getOutWorkCenterTime());
                                this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                                return StepResult.getNonComplete();
                            }
                            workOrderNo = produceSnRepair.getWorkOrderNo();
                            shiftCode = produceSnRepair.getShiftCode();
                            workTime = produceSnRepair.getWorkTime();
                            lotNo = produceSnRepair.getLotNo();
                        } catch (ParseException e) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]关联的产品条码[%s]下线时间[%s]格式不符合或为空"), packageNo, serialNumber,produceSnRepair.getOutWorkCenterTime());
                            this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            return StepResult.getNonComplete();
                        }
                    }
                    partDivulgeCheckRecordModel.setPartNo(produceSn.getPartNo());
                    partDivulgeCheckRecordModel.setCheckResult(checkResult);
                    partDivulgeCheckRecordModel.setPackageNo(packageNo);
                    partDivulgeCheckRecordModel.setCheckResultName(MesPcnExtEnumUtil.DIVULGE_CHECK_RESULT.valueOfDescription(checkResult));
                    if(!StringUtils.isEmpty(divulgeValue)){
                        partDivulgeCheckRecordModel.setDivulgeValue(Double.valueOf(divulgeValue));
                    }
                    partDivulgeCheckRecordModel.setPartName(produceSn.getPartNameRdd());
                    partDivulgeCheckRecordModel.setWorkOrderNo(workOrderNo);
                    partDivulgeCheckRecordModel.setCheckTime(TimeTool.getNowTime(true));
                    partDivulgeCheckRecordModel.setOutWorkCenterTime(outWcTime);
                    partDivulgeCheckRecordModel.setSerialNumber(serialNumber);
                    partDivulgeCheckRecordModel.setShiftCode(shiftCode);
                    partDivulgeCheckRecordModel.setWorkTime(workTime);
                    partDivulgeCheckRecordModel.setLotNo(lotNo);
                }
            } else{
                //下线时间
                String outWcTime;
                String workOrderNo;
                String shiftCode;
                String workTime;
                String lotNo;
                if(packageExt.getWorkOrderNo().equals(packageExt.getLastWorkOrderNo())){
                    try{
                        Date outWorkCenterTime = format.parse(packageExt.getModifyDatetime());
                        Date nowTime = new Date();
                        Long resultTemp = nowTime.getTime() - outWorkCenterTime.getTime();
                        Double result = resultTemp * 1.0 / (1000 * 60 * 60);
                        if(result < 24) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]下线时间:[%s],未满24小时,不能检测"), packageNo, packageExt.getModifyDatetime());
                            this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            return StepResult.getNonComplete(err);
                        }
                        outWcTime = packageExt.getModifyDatetime();
                        workOrderNo = packageExt.getWorkOrderNo();
                        workTime = packageExt.getWorkTime();
                        shiftCode = packageExt.getShiftCode();
                        lotNo = packageExt.getLotNo();
                    } catch (ParseException e) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]下线时间[%s]格式不符合或为空"), packageNo, packageExt.getModifyDatetime());
                        this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                }else{
                    packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
                    DdlPreparedPack.getStringEqualPack(packageExt.getSerialNumber(),MesPcnExtConstWords.SERIAL_NUMBER,packBean);
                    DdlPreparedPack.getStringEqualPack(packageExt.getLastWorkOrderNo(),MesPcnExtConstWords.WORK_ORDER_NO,packBean);
                    DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.OUT_WC_TIME}, packBean);
                    MesSubassemblyRemadeRecord packageExtRemade = subassemblyRemadeRecordRepository.getByProperty(packBean);

                    if(packageExtRemade == null){
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]未进行返工作业,不能进行24小时泄露检测"), packageNo);
                        this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete();
                    }
                    outWcTime = packageExtRemade.getModifyDatetime();

                    try{
                        Date outWorkCenterTime = format.parse(packageExtRemade.getModifyDatetime());
                        Date nowTime = new Date();
                        Long resultTemp = nowTime.getTime() - outWorkCenterTime.getTime();
                        Double result = resultTemp * 1.0 / (1000 * 60 * 60);
                        if(result < 24) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]下线时间:[%s],未满24小时,不能检测"), packageNo, packageExt.getModifyDatetime());
                            this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            return StepResult.getNonComplete(err);
                        }
                        shiftCode = packageExtRemade.getShiftCode();
                        workOrderNo = packageExtRemade.getWorkOrderNo();
                        workTime = packageExtRemade.getWorkTime();
                        lotNo = packageExtRemade.getLotNo();
                    } catch (ParseException e) {
                        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码[%s]下线时间[%s]格式不符合或为空"), packageNo, packageExt.getModifyDatetime());
                        this.sendMessage(reqBean, resultBean, err , MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                        return StepResult.getNonComplete(err);
                    }
                }
                partDivulgeCheckRecordModel.setPartNo(packageExt.getPartNo());
                partDivulgeCheckRecordModel.setCheckResult(checkResult);
                partDivulgeCheckRecordModel.setPackageNo(packageNo);
                partDivulgeCheckRecordModel.setCheckResultName(MesPcnExtEnumUtil.DIVULGE_CHECK_RESULT.valueOfDescription(checkResult));
                if(!StringUtils.isEmpty(divulgeValue)){
                    partDivulgeCheckRecordModel.setDivulgeValue(Double.valueOf(divulgeValue));
                }
                partDivulgeCheckRecordModel.setPartName(packageExt.getPartNameRdd());
                partDivulgeCheckRecordModel.setWorkOrderNo(workOrderNo);
                partDivulgeCheckRecordModel.setCheckTime(TimeTool.getNowTime(true));
                partDivulgeCheckRecordModel.setOutWorkCenterTime(outWcTime);
                partDivulgeCheckRecordModel.setShiftCode(shiftCode);
                partDivulgeCheckRecordModel.setWorkTime(workTime);
                partDivulgeCheckRecordModel.setLotNo(lotNo);
            }

            reqBean.getDataMap().put(MesPcnExtConstWords.CHECK_RECORD, partDivulgeCheckRecordModel);
        }
        return StepResult.getSuccessComplete();
    }

    @Override
    public StepResult guide(StationRequestBean reqBean) {
        StationResultBean resultBean = new StationResultBean();
        String guide = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请输入检测结果");
        this.sendMessage(reqBean, resultBean, guide, MesPcnEnumUtil.STATION_BUSI_TYPE.GUIDE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        return super.guide(reqBean);
    }

}
