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

import cn.estsh.i3plus.ext.mes.pcn.api.busi.bu.ISxMesBusiErrorMessageService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesBusiErrorMessage;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesProdBindRecordExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.bu.BuErrorMessageModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesProdBindRecordExtRepository;
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.actor.shipping.dispatch.IFsmCommonService;
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.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
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.impp.framework.boot.util.ImppRedis;
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 javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-bu
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2022-10-12 14:20
 */
@Slf4j
@Service("sxBuClearProdBindRecordInfoStepService")
public class SxBuClearProdBindRecordInfoStepService extends BaseStepService {

    @Resource(name = MesPcnExtConstWords.REDIS_RES_PCN)
    private ImppRedis redisMesPcn;

    @Autowired
    private IFsmCommonService fsmCommonService;

    @Autowired
    private MesProdBindRecordExtRepository prodBindRecordExtRepository;

    @Autowired
    private ISxMesBusiErrorMessageService busiErrorMessageService;

    //回退密码
    private static final String ROLLBACK_PWD = "ROLLBACK_PWD";
    //清空工步占用标志（当前工位不允许切换工单）
    //private static final String CLEAR_PROD_BIND_FLAG = "CLEAR_PROD_BIND_FLAG";

    @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);
    }

    @Override
    public StepResult execute(StationRequestBean reqBean) {
        log.info("sxBuClearProdBindRecordInfoStepService -execute- ws请求参数 {}", reqBean);
        StationResultBean resultBean = new StationResultBean();
        log.info(" sxBuClearProdBindRecordInfoStepService -execute- START work-order-no:{} --- work-cell-code:{} --- START", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
        Map<String, String> wcpcMap = fsmCommonService.getCachedWorkCellParam(reqBean);
        String reloadPwds = wcpcMap.get(ROLLBACK_PWD);
        String cacheKey = getCacheKey(reqBean, MesPcnExtConstWords.ERROR_MESSAGE);

        //redisMesPcn.putHash(getCacheKey(reqBean, CLEAR_PROD_BIND_FLAG), CLEAR_PROD_BIND_FLAG, "TRUE", MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
        if(!StringUtils.isEmpty(reloadPwds)){
            List<String> reloadPwdList = Arrays.stream(reloadPwds.split(MesPcnExtConstWords.COMMA)).collect(Collectors.toList());
            if(reloadPwdList.contains(reqBean.getScanInfo())){
                BuErrorMessageModel errorMessage = (BuErrorMessageModel) redisMesPcn.getHash(cacheKey, MesPcnExtConstWords.ERROR_MESSAGE);
                log.info(" sxBuClearProdBindRecordInfoStepService -execute- work-order-no:{} --- work-cell-code:{} --- REDIS错误信息:{}", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode(), errorMessage);
                insertErrorMessage(reqBean, errorMessage);
                log.info(" sxBuClearProdBindRecordInfoStepService -execute- work-order-no:{} --- work-cell-code:{} --- REDIS错误信息入库成功", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
                redisMesPcn.deleteBatchKey(cacheKey, getCacheKey(reqBean, MesPcnExtConstWords.BIND_KEY_PART), getCacheKey(reqBean, MesPcnExtConstWords.REPAIR_BIND_KEY_PART));
//                redisMesPcn.deleteKey(cacheKey);
////                //清空关键件信息
//                redisMesPcn.deleteKey(getCacheKey(reqBean, MesPcnExtConstWords.BIND_KEY_PART));
//                redisMesPcn.deleteKey(getCacheKey(reqBean, MesPcnExtConstWords.REPAIR_BIND_KEY_PART));
//                redisMesPcn.deleteKey(getCacheKey(reqBean, CLEAR_PROD_BIND_FLAG));
                log.info("sxBuClearProdBindRecordInfoStepService[execute] 密码{}:重载成功!",reqBean.getScanInfo());
                //清除工步内容
                resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.STEP_CONTENT.getValue());
                sendMessage(reqBean, resultBean);
                sendMessage(reqBean, resultBean,
                        "",
                        MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
                log.info(" sxBuClearProdBindRecordInfoStepService -execute- work-order-no:{} --- work-cell-code:{} --- 即将删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
                //删除关键件绑定记录
                deleteProdBindRecordList(reqBean);
                log.info(" sxBuClearProdBindRecordInfoStepService -execute- work-order-no:{} --- work-cell-code:{} --- 删除关键件绑定记录成功", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
                return StepResult.getSuccessComplete();
            }else{
                log.info(" sxBuClearProdBindRecordInfoStepService -execute- work-order-no:{} --- work-cell-code:{} ---  重载码验证失败,请重新确认再输入", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
                sendMessage(reqBean, resultBean,
                        String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "重载码验证失败,请重新确认再输入!"), reqBean.getScanInfo()),
                        MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                foundExThrowNoShowMsg();
            }
        } else{
            log.info(" sxBuClearProdBindRecordInfoStepService -execute- work-order-no:{} --- work-cell-code:{} --- 请在工位参数配置中维护重载码", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
            sendMessage(reqBean, resultBean,
                    String.format(LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请在工位参数配置中维护重载码"), reqBean.getScanInfo()),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            foundExThrowNoShowMsg();
        }
        log.info(" sxBuClearProdBindRecordInfoStepService -execute- END work-order-no:{} --- work-cell-code:{} --- START", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode() );
        return StepResult.getSuccessComplete();
    }

    private void insertErrorMessage(StationRequestBean reqBean, BuErrorMessageModel errorMessage) {
        MesBusiErrorMessage busiErrorMessage = new MesBusiErrorMessage();
        busiErrorMessage.setPartNo(errorMessage.getPartNo());
        busiErrorMessage.setPartNameRdd(errorMessage.getPartNameRdd());
        busiErrorMessage.setItemPartNo(errorMessage.getItemPartNo());
        busiErrorMessage.setItemPartName(errorMessage.getItemPartName());
        busiErrorMessage.setProcessCode(reqBean.getProcessCode());
        busiErrorMessage.setWorkCellCode(reqBean.getWorkCellCode());
        busiErrorMessage.setWorkOrderNo(errorMessage.getWorkOrderNo());
        busiErrorMessage.setSerialNumber(errorMessage.getSerialNumber());
        busiErrorMessage.setWorkCenterCode(reqBean.getWorkCenterCode());
        busiErrorMessage.setPassword(reqBean.getScanInfo());
        busiErrorMessage.setErrorMessage(errorMessage.getErrorMessage());
        busiErrorMessage.setScanInfo(errorMessage.getScanInfo());
        busiErrorMessage.setErrorStepCode(errorMessage.getErrorStepCode());
        busiErrorMessage.setErrorStepName(errorMessage.getErrorStepName());
        busiErrorMessage.setOrganizeCode(reqBean.getOrganizeCode());
        ConvertBean.serviceModelInitialize(busiErrorMessage, reqBean.getUserInfo());
        busiErrorMessageService.insertMesBusiErrorMessage(busiErrorMessage);
    }

    private void deleteProdBindRecordList(StationRequestBean reqBean){
        log.info(" sxBuClearProdBindRecordInfoStepService - deleteProdBindRecordList queryProdBindRecordExt -execute- START work-order-no:{} --- work-cell-code:{} --- 删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(reqBean.getSerialNumber(), MesPcnExtConstWords.SERIAL_NUMBER, packBean);
        List<MesProdBindRecordExt> prodBindRecordExts = prodBindRecordExtRepository.findByHqlWhere(packBean);

        log.info("sxBuClearProdBindRecordInfoStepService - deleteProdBindRecordList queryProdBindRecordExt -execute- END work-order-no:{} --- work-cell-code:{} --- 删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());

        if(!CollectionUtils.isEmpty(prodBindRecordExts)){
            List<MesProdBindRecordExt> prodBindRecordExtFilterList = prodBindRecordExts.stream().filter(prodBindRecordExt ->
                    prodBindRecordExt.getProcessCode().equals(reqBean.getProcessCode()) && prodBindRecordExt.getWorkCellCode().equals(reqBean.getWorkCellCode())).collect(Collectors.toList());
            prodBindRecordExtFilterList.stream().forEach(mesProdBindRecordExt -> {
                mesProdBindRecordExt.setIsValid(MesPcnExtEnumUtil.IS_VAILD.INVAILD.getValue());
                mesProdBindRecordExt.setIsDeleted(MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue());
                ConvertBean.serviceModelUpdate(mesProdBindRecordExt, reqBean.getUserInfo());
                new ConvertBeanExt(mesProdBindRecordExt).convertBean(mesProdBindRecordExt);
                prodBindRecordExtRepository.save(mesProdBindRecordExt);
                log.info("sxBuClearProdBindRecordInfoStepService - deleteProdBindRecordList setValue -execute- END work-order-no:{} --- work-cell-code:{} --- 删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode());
            });
            //if(!CollectionUtils.isEmpty(prodBindRecordExtFilterList)) {
            //    log.info("sxBuClearProdBindRecordInfoStepService - deleteProdBindRecordList saveValue -execute- TOTAL --- work-order-no:{} --- work-cell-code:{} --- totalDataId:{} --- 删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode(), prodBindRecordExts.stream().map(MesProdBindRecordExt::getId).collect(Collectors.toList()));
            //    for (MesProdBindRecordExt prodBindRecordExt : prodBindRecordExtFilterList) {
            //        log.info("sxBuClearProdBindRecordInfoStepService - deleteProdBindRecordList saveValue -execute- START --- work-order-no:{} --- work-cell-code:{} --- dataId:{} --- 删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode(), prodBindRecordExt.getId());
            //
            //        log.info("sxBuClearProdBindRecordInfoStepService - deleteProdBindRecordList saveValue -execute- END --- work-order-no:{} --- work-cell-code:{} --- dataId:{} --- 删除关键件绑定记录", reqBean.getWorkOrderNo(), reqBean.getWorkCellCode(), prodBindRecordExt.getId());
            //    }
            //}
        }

//        prodBindRecordExtRepository.updateByProperties(
//                new String[]{MesPcnExtConstWords.SERIAL_NUMBER, MesPcnExtConstWords.WORK_CELL_CODE, MesPcnExtConstWords.PROCESS_CODE},
//                new Object[]{reqBean.getSerialNumber(), reqBean.getWorkCellCode(), reqBean.getProcessCode()},
//                new String[]{MesConstWords.IS_DELETED, MesConstWords.IS_VALID, MesPcnExtConstWords.MODIFY_USER, MesPcnExtConstWords.MODIFY_DATE_TIME},
//                new Object[]{MesPcnExtEnumUtil.IS_VAILD.VAILD.getValue(), MesPcnExtEnumUtil.IS_VAILD.INVAILD.getValue(), reqBean.getUserInfo(), TimeTool.getNowTime(true)});
//        prodBindRecordExtRepository.deleteWeaklyByProperties(
//                new String[]{MesPcnExtConstWords.SERIAL_NUMBER, MesPcnExtConstWords.WORK_CELL_CODE, MesPcnExtConstWords.PROCESS_CODE},
//                new Object[]{reqBean.getSerialNumber(), reqBean.getWorkCellCode(), reqBean.getProcessCode()},
//                reqBean.getUserInfo());
    }
}
