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

import cn.estsh.i3plus.ext.mes.pcn.api.base.bu.IMesBusiConfigService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IWorkCenterContainerLocationService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.station.SxPutPalletModuleService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPutPalletModuleModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.SxPutPalletPlcDataModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.*;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.ConvertBeanExt;
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.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesContainer;
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.MesContainerRepository;
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.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description : 工步业务-本体装托完成工步
 * @Reference :
 * @Author : wangjie
 * @CreateDate : 2019-07-11
 * @Modify:
 **/
@Slf4j
@Service("sxPutPalletCompleteStepService")
public class SxPutPalletCompleteStepService extends BaseStepService {

    @Autowired
    private SxPutPalletModuleService putPalletModuleService;

    @Autowired
    private MesPackageExtRepository packageExtRepository;

    @Autowired
    private MesOuterPackageRepository outerPackageRepository;

    @Autowired
    private MesProduceSnRepairRepository produceSnRepairRepository;

    @Autowired
    private SxProductOffLineExtRepository productOffLineExtRepository;

    @Autowired
    private IWorkCenterContainerLocationService workCenterContainerLocationService;

    @Autowired
    private MesContainerRepository containerRepository;

    @Autowired
    private IMesBusiConfigService busiConfigService;

    @Autowired
    private SxWorkLineGenerationAgvTasksConfigRepository workLineGenerationAgvTasksConfigRepository;

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

        StationResultBean resultBean = new StationResultBean();
        String err;

        if (StringUtils.isEmpty(reqBean.getOrganizeCode())) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "入参缺少工厂代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }

        String curLockLocationNo = (String) putPalletModuleService.doHandleCurLockLocationNo(reqBean, 1, null);
        if (StringUtils.isEmpty(curLockLocationNo)) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前未锁定位置编号");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }

        SxPutPalletPlcDataModel ctNoModel = (SxPutPalletPlcDataModel) putPalletModuleService.doHandleCurCtNo(reqBean, 1, null);
        if (null == ctNoModel || !ctNoModel.getBoo()) {
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "当前未锁定容器代码");
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }
        List<SxPutPalletModuleModel> putPalletModuleModelList = (List<SxPutPalletModuleModel>) putPalletModuleService.doHandlePackageDataByCtNo(reqBean, ctNoModel.getCtNo(), 1, null);
        if (CollectionUtils.isEmpty(putPalletModuleModelList)) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]未绑定包装条码"), ctNoModel.getCtNo());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return StepResult.getSuccessComplete();
        }

        try {
            MesContainer container = workCenterContainerLocationService.getContainerByCtNo(reqBean.getOrganizeCode(), ctNoModel.getCtNo());
            if (null == container) {
                err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]无效"), ctNoModel.getCtNo());
                this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
            container.setUseStatus(String.valueOf(MesPcnEnumUtil.MES_CONTAINER_STATUS.OCCUPY.getValue()));
            ConvertBean.serviceModelUpdate(container, reqBean.getUserInfo());
            containerRepository.save(container);

            for (SxPutPalletModuleModel model : putPalletModuleModelList) {
                if (null == model) {
                    continue;
                }
                //判断是否是净水器产线
                MesBusiConfig mesBusiConfig = busiConfigService.queryBusiConfigeByCfgCode(MesPcnExtConstWords.WATER_PURIFIER_CODE, reqBean.getOrganizeCode());
                boolean iswaterPurifierWorkCenter = false;
                if (mesBusiConfig != null && !StringUtils.isEmpty(mesBusiConfig.getCfgValue())) {
                    List<String> workCenterCodeList = Arrays.stream(mesBusiConfig.getCfgValue().split(MesPcnExtConstWords.COMMA)).collect(Collectors.toList());
                    if (workCenterCodeList.contains(reqBean.getWorkCenterCode())) {
                        iswaterPurifierWorkCenter = true;
                    }
                }
                if (MesPcnExtEnumUtil.WORK_ORDER_TYPE.REWORK_ORDER.getValue() != model.getWorkOrderType()) {
                    if (iswaterPurifierWorkCenter) {
                        updateOuterPackage(reqBean, resultBean, ctNoModel, model);
                    } else {
                        MesPackageExt pack = packageExtRepository.getById(Long.parseLong(model.getIdStrList().get(0)));
                        if (null == pack) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "包装条码ID[%s]数据不存在"), model.getIdStrList().get(0));
                            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            foundExThrowNoShowMsg();
                        }
                        pack.setCtNo(ctNoModel.getCtNo());
                        ConvertBean.serviceModelUpdate(pack, reqBean.getUserInfo());
                        pack.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                        new ConvertBeanExt(pack).convertBean(pack);
                        packageExtRepository.save(pack);
                    }
                } else {
                    List<MesProduceSnRepair> produceSnRepairList = new ArrayList<>();
                    if (iswaterPurifierWorkCenter) {
                        updateOuterPackage(reqBean, resultBean, ctNoModel, model);
                    }
                    for (String id : model.getIdStrList()) {
                        MesProduceSnRepair produceSnRepair = produceSnRepairRepository.getById(Long.parseLong(id));
                        if (null == produceSnRepair) {
                            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "返工条码ID[%s]数据不存在"), id);
                            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                            foundExThrowNoShowMsg();
                        }
                        produceSnRepair.setCtNo(ctNoModel.getCtNo());
                        ConvertBean.serviceModelUpdate(produceSnRepair, reqBean.getUserInfo());
                        produceSnRepairList.add(produceSnRepair);
                    }
                    produceSnRepairRepository.saveAll(produceSnRepairList);
                }
                // 新增 下线报工关联数据 用于 WMS 生成 AGV搬运任务
                insertSxProductOffLineExt(reqBean, curLockLocationNo, ctNoModel, model);
            }
        } catch (Exception e) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]执行满托发生异常,请执行强制完成!异常原因[%s]"),
                    ctNoModel.getCtNo(), e.getMessage());
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }

        putPalletModuleService.doHandleCurCtNo(reqBean, 3, null);
        putPalletModuleService.doHandleCurCtQty(reqBean, 3, null);
        putPalletModuleService.doHandleCurLockLocationNo(reqBean, 3, null);
        putPalletModuleService.doHandleDisUnlockLocation(reqBean, 3, null);
        putPalletModuleService.doHandlePackageDataByCtNo(reqBean, ctNoModel.getCtNo(), 3, null);

        err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "容器代码[%s]已完成装托"), ctNoModel.getCtNo());
        this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        return StepResult.getSuccessComplete();
    }

    private void insertSxProductOffLineExt(StationRequestBean reqBean, String curLockLocationNo, SxPutPalletPlcDataModel ctNoModel, SxPutPalletModuleModel model) {
        SxProductOffLineExt productOffLineExt = new SxProductOffLineExt();
        productOffLineExt.setWorkOrderNo(model.getWorkOrderNo());
        productOffLineExt.setPackageNo(model.getPackageNo());
        productOffLineExt.setCtNo(ctNoModel.getCtNo());
        productOffLineExt.setStrarPoint(curLockLocationNo);
        int isAgvCarry = MesPcnExtEnumUtil.IS_AGV_CARRY.NO.getValue();
        if(checkIsAgvCraay(reqBean.getWorkCenterCode(), reqBean.getOrganizeCode())){
            isAgvCarry = MesPcnExtEnumUtil.IS_AGV_CARRY.YES.getValue();
        }
        productOffLineExt.setIsAGVCarry(isAgvCarry);

        productOffLineExt.setSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        productOffLineExt.setOrganizeCode(reqBean.getOrganizeCode());
        ConvertBean.serviceModelInitialize(productOffLineExt, reqBean.getUserInfo());
        productOffLineExtRepository.insert(productOffLineExt);
    }

    private boolean checkIsAgvCraay(String workCenterCode, String organizeCode){
        SxWorkLineGenerationAgvTasksConfig workLineGenerAgvTasksConfig = workLineGenerationAgvTasksConfigRepository.getByProperty(
                new String[]{"workCenterCode", "organizeCode", "isValid", "isDeleted"},
                new Object[]{workCenterCode, organizeCode,
                        CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                        CommonEnumUtil.IS_DEAL.NO.getValue()});

        if(workLineGenerAgvTasksConfig == null || workLineGenerAgvTasksConfig.getIsAGVCarry() == MesPcnExtEnumUtil.IS_AGV_CARRY.YES.getValue()){
            return true;
        }

        return false;
    }

    private void updateOuterPackage(StationRequestBean reqBean, StationResultBean resultBean, SxPutPalletPlcDataModel ctNoModel, SxPutPalletModuleModel model) {
        String err;
        MesOuterPackage pack = outerPackageRepository.getById(Long.parseLong(model.getIdStr()));
        if (null == pack) {
            err = String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "大包装条码ID[%s]数据不存在"), model.getIdStrList().get(0));
            this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }
        pack.setCtNo(ctNoModel.getCtNo());
        ConvertBean.serviceModelUpdate(pack, reqBean.getUserInfo());
        pack.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        new ConvertBeanExt(pack).convertBean(pack);
        outerPackageRepository.save(pack);
    }

}
