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

import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExt;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesWorkOrderExtBindSnRecord;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ep.EpSnBindOrderModuleModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.model.ep.EpSnBindOrderWorkOrderModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkOrderExtBindSnRecordRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesWorkOrderExtRepository;
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.BaseModuleService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.busi.dispatch.ShippingDispatchService;
import cn.estsh.i3plus.mes.pcn.util.LocaleUtil;
import cn.estsh.i3plus.mes.pcn.util.PojoAttrUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.platform.common.util.MesPcnConstWords;
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.MesStateMachineStatus;
import cn.estsh.i3plus.pojo.mes.model.AttrBean;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.impp.framework.boot.util.ImppRedis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
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.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-dev
 * @DESCRIPTION:
 * @USER: xinwang.yi
 * @DATE: 2021-12-27 15:53
 */
@Slf4j
@Service("epSnBindOrderModuleService")
public class EpSnBindOrderModuleService extends BaseModuleService {

    @Autowired
    private MesWorkOrderExtBindSnRecordRepository workOrderExtBindSnRecordRepository;

    @Autowired
    private MesWorkOrderExtRepository workOrderExtRepository;

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

    @Autowired
    private ShippingDispatchService shippingDispatchService;

    @Override
    public void init(StationRequestBean reqBean) {
        this.sendMessage(reqBean, null, "", MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
        doInit(reqBean);
    }

    private void doInit(StationRequestBean reqBean){
        StationResultBean resultBean = new StationResultBean();

        resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MODULE_CONTENT.getValue());
        resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.CUSTOM.getValue());
        resultBean.setCustomPageName(MesPcnExtConstWords.EP_SN_BIND_ORDER_MODULE);
        resultBean.setDataAttrList(packDataAttrList(reqBean));
        resultBean.setSpecialDisplayData(getStepColIndent(reqBean));
        Map<String, Object> dataMap = reqBean.getDataMap();
        String prodType = (String) getLastSelectOrder(reqBean,MesPcnExtConstWords.CUR_PROD_TYPE);
        String prodTypeName = "";
        if(!StringUtils.isEmpty(prodType)){
            prodTypeName = MesPcnExtEnumUtil.EP_SN_BIND_ORDER_PROD_TYPE.valueOfDescription(Integer.valueOf(prodType));
        }

        //当前工单号
        EpSnBindOrderWorkOrderModel curWorkOrderNo = (EpSnBindOrderWorkOrderModel) doHandleCurWorkOrder(reqBean, 1, null);

        //根据工单号查询的生产工单条码绑定记录
        List<MesWorkOrderExtBindSnRecord> workOrderExtBindSnRecords = new ArrayList<>();
        //返回给resultList的数据
        List<EpSnBindOrderModuleModel> epSnBindOrderModuleModels = new ArrayList<>();
        if(curWorkOrderNo != null){
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(curWorkOrderNo.getWorkOrderNo(), MesPcnExtConstWords.ORDER_NO, packBean);
            MesWorkOrderExt workOrderExt = workOrderExtRepository.getByProperty(packBean);

            if(workOrderExt != null){
                String workOrderTypeName = MesPcnExtEnumUtil.WORK_ORDER_TYPE.valueOfDescription(workOrderExt.getWorkOrderType());
                dataMap.put(MesPcnExtConstWords.CUR_WORK_ORDER_NO, workOrderExt.getOrderNo());
                dataMap.put(MesPcnExtConstWords.PART_NO, workOrderExt.getPartNo());
                dataMap.put(MesPcnExtConstWords.PART_NAME_RDD, workOrderExt.getPartNameRdd());
                dataMap.put(MesPcnExtConstWords.WORK_ORDER_TYPE_NAME, workOrderTypeName);
                dataMap.put(MesPcnExtConstWords.QTY, workOrderExt.getQty());
                dataMap.put(MesPcnExtConstWords.BIND_QTY , curWorkOrderNo.getBindQty());
            }
            packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
            DdlPreparedPack.getStringEqualPack(curWorkOrderNo.getWorkOrderNo(), MesPcnExtConstWords.WORK_ORDER_NO, packBean);
            DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.CREATE_DATE_TIME}, packBean);
            workOrderExtBindSnRecords = workOrderExtBindSnRecordRepository.findByHqlWhere(packBean);

        }
        dataMap.put(MesPcnExtConstWords.PROD_TYPE, prodType);
        dataMap.put(MesPcnExtConstWords.PRODTYPE_NAME, prodTypeName);
        if(!CollectionUtils.isEmpty(workOrderExtBindSnRecords)){
            Iterator<MesWorkOrderExtBindSnRecord> workOrderExtBindSnRecordIterator = workOrderExtBindSnRecords.stream().iterator();

            while (workOrderExtBindSnRecordIterator.hasNext()){
                MesWorkOrderExtBindSnRecord mesWorkOrderExtBindSnRecord = workOrderExtBindSnRecordIterator.next();
                EpSnBindOrderModuleModel epSnBindOrderModuleModel = new EpSnBindOrderModuleModel();
                BeanUtils.copyProperties(mesWorkOrderExtBindSnRecord, epSnBindOrderModuleModel);
                if(!StringUtils.isEmpty(mesWorkOrderExtBindSnRecord.getSerialNumberEnd())){
                    StringBuffer buffer = new StringBuffer(epSnBindOrderModuleModel.getSerialNumber());
                    buffer.append("~");
                    buffer.append(mesWorkOrderExtBindSnRecord.getSerialNumberEnd());
                    epSnBindOrderModuleModel.setSerialNumber(buffer.toString());
                }
                epSnBindOrderModuleModel.setProdTypeName(MesPcnExtEnumUtil.EP_SN_BIND_ORDER_PROD_TYPE.valueOfDescription(mesWorkOrderExtBindSnRecord.getProdType()));
                epSnBindOrderModuleModels.add(epSnBindOrderModuleModel);
            }
        }

        resultBean.setResultMap(dataMap);
        resultBean.setResultList(epSnBindOrderModuleModels);
        this.sendMessage(reqBean, resultBean);
    }

    private List<AttrBean> packDataAttrList(StationRequestBean reqBean) {
        List<AttrBean> attrBeanList = new ArrayList<>();
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.SERIAL_NUMBER, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "产品条码"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.OPERATE_QTY, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "数量"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.PRODTYPE_NAME, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "模式"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.CREATE_DATE_TIME, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "操作时间"));
        return attrBeanList;
    }

    private String getLastSelectOrderKey(StationRequestBean reqBean) {
        return getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA);
    }

    private Object getLastSelectOrder(StationRequestBean reqBean ,String item) {
        return redisMesPcn.getHash(getLastSelectOrderKey(reqBean) , item);
    }

    @Override
    public boolean execute(StationRequestBean reqBean) {
        return true;
    }

    @Override
    public boolean execStateModule(StationRequestBean reqBean, List<MesStateMachineStatus> states, Map<String, String> wcpcMap) {
        doInit(reqBean);
        return true;
    }

    @Override
    public boolean doFunction(StationRequestBean reqBean) {
        Boolean result = false;
        String err;
        Map<String, Object> dataMap = reqBean.getDataMap();
        String common = (String) dataMap.get(MesPcnExtConstWords.COMMAND);
        Object value = dataMap.get(MesPcnExtConstWords.VALUE);
        StationResultBean resultBean = new StationResultBean();
        if(StringUtils.isEmpty(common)){
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "后端未获取到业务功能指令");
            this.sendMessage(reqBean, null, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
            return result;
        }

        switch (common){
            case MesPcnExtConstWords.CMD_WORK_ORDER :
                if (StringUtils.isEmpty(value)) {
                    err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请选择工单");
                    this.sendMessage(reqBean,  null, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return result;
                }
                if (StringUtils.isEmpty(getLastSelectOrder(reqBean, MesPcnExtConstWords.CMD_WORK_ORDER))) {
                    doHandleSelectWorkOrderNo(reqBean, 2 ,value.toString());
                    result = true;
                }
                break;

            case MesPcnExtConstWords.CMD_PROD_TYPE :
                if (StringUtils.isEmpty(value)) {
                    err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "请选择生产模式");
                    this.sendMessage(reqBean, resultBean, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
                    return result;
                }
                if (StringUtils.isEmpty(getLastSelectOrder(reqBean, MesPcnExtConstWords.CMD_PROD_TYPE))) {
                    doHandleSelectProdType(reqBean, 2, value.toString());
                    result = true;
                }
                break;

            default:
                break;
        }

        if(result == false){
            err = LocaleUtil.transferLanguage(reqBean.getUserInfo(), "操作太频繁");
            this.sendMessage(reqBean,  null, err, MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE, MesPcnEnumUtil.STATION_DATA_TYPE.EXP_TEXT);
        }else{
            result = true;
            //跳过工序
            reqBean.setClientInfo(shippingDispatchService.getActorClientInfo(reqBean));
            reqBean.setInterfaceType(MesPcnConstWords.SHIPPING);
            reqBean.setBusiType(MesPcnConstWords.WS_CMD_DO_SCAN);
            reqBean.setForceJumpProcess(true);
            shippingDispatchService.doSendScanQueueNextExec(reqBean);
        }

        return result;
    }

    public synchronized Object doHandleSelectWorkOrderNo(StationRequestBean reqBean, Integer flag, String selectWorkOrderNo) {
        switch (flag) {
            case 1:
                return redisMesPcn.getHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CMD_WORK_ORDER);
            case 2:
                return redisMesPcn.putHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CMD_WORK_ORDER, selectWorkOrderNo, MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
            case 3:
                redisMesPcn.deleteHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CMD_WORK_ORDER);
                return true;
            default:
                return null;
        }
    }

    private synchronized Object doHandleCurWorkOrder(StationRequestBean reqBean, Integer flag, EpSnBindOrderWorkOrderModel curWorkOrderNo) {
        switch (flag) {
            case 1:
                return redisMesPcn.getHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CUR_WORK_ORDER);
            case 2:
                return redisMesPcn.putHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CUR_WORK_ORDER, curWorkOrderNo, MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
            case 3:
                redisMesPcn.deleteHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CUR_WORK_ORDER);
                return true;
            default:
                return null;
        }
    }

    public synchronized Object doHandleSelectProdType(StationRequestBean reqBean, Integer flag, String prodType) {
        switch (flag) {
            case 1:
                return redisMesPcn.getHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CMD_PROD_TYPE);
            case 2:
                return redisMesPcn.putHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CMD_PROD_TYPE, prodType, MesPcnEnumUtil.EXPIRE_TIME.NEVER.getValue());
            case 3:
                redisMesPcn.deleteHash(getCacheKey(reqBean, MesPcnExtConstWords.PROD_DATA), MesPcnExtConstWords.CMD_PROD_TYPE);
                return true;
            default:
                return null;
        }
    }
}
