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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionDispatchContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionProcessContextStepService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProductionProcessContext;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseStepService;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
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.MesContainerPackage;
import cn.estsh.i3plus.pojo.mes.bean.MesContainerPackageDetail;
import cn.estsh.i3plus.pojo.mes.bean.MesContainerSnStation;
import cn.estsh.i3plus.pojo.mes.bean.MesStation;
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.MesContainerPackageDetailRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesContainerPackageRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesContainerSnRepository;
import cn.estsh.i3plus.pojo.mes.repository.MesContainerSnStationRepository;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
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.Objects;

/**
 * @Description : 容器上料绑定装配件站点工步
 * @Author : jason.niu
 **/
@Slf4j
@Service("mesStationFeedContainerSnStepService")
public class MesStationFeedContainerSnStepService extends BaseStepService {
    @Autowired
    private MesContainerSnStationRepository mesContainerSnStationRepository;
    @Autowired
    private MesContainerPackageRepository containerPackageRDao;
    @Autowired
    private MesContainerPackageDetailRepository packageDetailRDao;
    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;
    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;
    @Autowired
    private MesContainerSnRepository containerSnRDao;

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        StationResultBean resultBean = new StationResultBean();

        StepResult stepResult = StepResult.getSuccessComplete();
        final String organizeCode = reqBean.getOrganizeCode();

        //扫描信息置空
        String containerSn = reqBean.resetScanInfo(reqBean.getScanInfo());
        if (StringUtils.isEmpty(containerSn)) stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), "请扫描上料容器条码!");

        if (!containerSnRDao.isExitByProperty(new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID, "containerSn"},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), containerSn})) {
            stepSendGuideAndThrowEx(reqBean, resultBean.writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PROCESS.getValue()), String.format("请扫描容器条码【%s】!", containerSn));
        }

        //获取工位当前设备信息
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.dispatchCurCellEquipment(reqBean);

        //配置错误 抛出异常
        if (!productionProcessContext.getSuccess()) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), productionProcessContext.getMessage());
        }

        //获取站点用于缺料时进行上料绑定
        List<MesStation> stationList = productionDispatchContextStepService.getMatchStationContext(reqBean);
        if (CollectionUtils.isEmpty(stationList)) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), "容器条码扣减装配件时验证设备未关联支持上料的站点");
        }
        MesStation station = null;
        MesStation mixStation = null;
        for (MesStation st : stationList) {
            if (Objects.equals(st.getStationType(), MesExtEnumUtil.STATION_TYPE.STATION_TYPE_10.getValue()) ||
                    Objects.equals(st.getStationType(), MesExtEnumUtil.STATION_TYPE.STATION_TYPE_20.getValue())) {
                station = st;
                break;
            }
            if (mixStation == null && Objects.equals(st.getStationType(), MesExtEnumUtil.STATION_TYPE.STATION_TYPE_40.getValue())) {
                mixStation = st;
            }
        }
        if (station == null) {
            station = mixStation;
        }
        if (station == null) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), "不存在站点类型为【原料站点】、【装配件站点】、【混料站点】的站点信息！");
        }
        String topContainerSn = getTopContainerSn(organizeCode, containerSn);
        if (!topContainerSn.equals(containerSn)) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), String.format("此容器已绑定容器条码【%s】，请扫描容器条码【%s】!", containerSn, topContainerSn));
        }
        //校验容器条码的唯一性
        DdlPackBean containerSnStationDdlPackBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(containerSn, "topContainerSn", containerSnStationDdlPackBean);
        MesContainerSnStation containerSnStation = mesContainerSnStationRepository.getByProperty(containerSnStationDdlPackBean);
        if (containerSnStation != null) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), String.format("容器条码【%s】已绑定站点【%s】!", containerSn, containerSnStation.getStation()));
        }
        checkContainerPackage(reqBean, resultBean, organizeCode, containerSn);
        return stepSuccessCompleteAndSendMsgReturn(reqBean, resultBean.writeDbLog(), stepResult, "容器条码扣减装配件验证成功!");
    }

    private void checkContainerPackage(StationRequestBean reqBean, StationResultBean resultBean, String organizeCode, String containerSn) {
        MesContainerPackage containerPackage = containerPackageRDao.getByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_VALID, MesConstWords.IS_DELETED, "containerSn"},
                new Object[]{organizeCode, CommonEnumUtil.IS_VAILD.VAILD.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), containerSn});
        if (containerPackage == null) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), String.format("容器条码【%s】未绑定零件!", containerSn));
        }
        assert containerPackage != null;
        if (!Objects.equals(containerPackage.getPackageStatus(), MesExtEnumUtil.CONTAINER_PACKAGE_STATUS.STATUS_20.getValue())) {
            stepExpSendMsgAndThrowEx(reqBean, resultBean.writeDbLog(), String.format("容器条码【%s】未关箱!", containerSn));
        }
    }

    private String getTopContainerSn(String organizeCode, String containerSn) {
        MesContainerPackageDetail packageDetail = packageDetailRDao.getByProperty(new String[]{MesConstWords.ORGANIZE_CODE, MesConstWords.IS_VALID, MesConstWords.IS_DELETED, "barCode"},
                new Object[]{organizeCode, CommonEnumUtil.IS_VAILD.VAILD.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), containerSn});
        if (packageDetail != null) {
            return getTopContainerSn(organizeCode, packageDetail.getContainerSn());
        }
        return containerSn;
    }
}
