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

import cn.estsh.i3plus.ext.mes.pcn.pojo.model.yf.YfManyCellMonitorModel;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.base.BaseModuleService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.busi.dispatch.cachedispatch.WorkCellDataCacheDispatch;
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.pojo.base.enumutil.MesPcnEnumUtil;
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 com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description : 展示组件：多工位监控加工
 * @Reference :
 * @Author :wangjie
 * @CreateDate : 2020-06-26 11:18 上午
 * @Modify:
 **/
@Slf4j
@Service("yfManyCellMonitorModuleService")
public class YfManyCellMonitorModuleService extends BaseModuleService {

    private static final String YF_MANY_CELL_MONITOR_MODULE = "YF_MANY_CELL_MONITOR_MODULE";
    private static final String CELL_LOCATION = "CELL_LOCATION";

    @Override
    public void init(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(YF_MANY_CELL_MONITOR_MODULE);
        resultBean.setDataAttrList(packDataAttrList(reqBean));
        resultBean.setSpecialDisplayData(getStepColIndent(reqBean));
        resultBean.setResultList(getResultList(reqBean));
        resultBean.setResultMap(getResultMap(reqBean, resultBean));
        this.sendMessage(reqBean, resultBean);
    }

    private Map<String, Object> getResultMap(StationRequestBean reqBean, StationResultBean resultBean) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("location", reqBean.getWcpcMap().get(CELL_LOCATION));
        resultMap.put("qty", CollectionUtils.isEmpty(resultBean.getResultList()) ? 0 : resultBean.getResultList().size());
        return resultMap;
    }

    private List<YfManyCellMonitorModel> getResultList(StationRequestBean reqBean) {
        List<YfManyCellMonitorModel> resultList = getSerialNumberList(reqBean);
        if (CollectionUtils.isEmpty(resultList)) return null;
        resultList = resultList.stream().filter(o -> null != o).sorted(Comparator.comparing(YfManyCellMonitorModel::getCreateDatetime).reversed()).collect(Collectors.toList());
        String time = TimeTool.getNowTime(true);
        for (YfManyCellMonitorModel result : resultList) {
            if (null == result) continue;
            try {
                if (TimeTool.getSecoundsBetweenTime(2, result.getCreateDatetime(), time) >= 1) result.status("加工完成");
                else result.status("正在加工");
            } catch (ParseException e) {
                result.status("加工完成");
            }
        }
        return resultList;
    }

    private List<YfManyCellMonitorModel> getSerialNumberList(StationRequestBean reqBean) {
        String data = (String) doHandleSn(reqBean, 1, null);
        return StringUtils.isEmpty(data) ? null : JSONObject.parseArray(data, YfManyCellMonitorModel.class);
    }

    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.STATUS, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "状态"));
        PojoAttrUtil.loadPojoAttrs(attrBeanList, MesPcnExtConstWords.CREATE_DATE_TIME, LocaleUtil.transferLanguage(reqBean.getUserInfo(), "操作时间"));
        return attrBeanList;
    }

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

    private String getDataKey(StationRequestBean reqBean) {
        return new StringJoiner(MesPcnExtConstWords.COLON).add(reqBean.getOrganizeCode())
                .add(YF_MANY_CELL_MONITOR_MODULE).add(reqBean.getWorkCenterCode()).add(reqBean.getWorkCellCode()).toString();
    }

    private String getMonitorKey(StationRequestBean reqBean, String suffix) {
        return new StringJoiner(MesPcnExtConstWords.COLON).add(reqBean.getOrganizeCode())
                .add(YF_MANY_CELL_MONITOR_MODULE).add(MesPcnExtConstWords.PLC_CODE_UC).add(suffix).toString();
    }

    public void addSerialNumber(StationRequestBean reqBean, String serialNumber) {
        List<YfManyCellMonitorModel> resultList = getSerialNumberList(reqBean);
        if (CollectionUtils.isEmpty(resultList)) resultList = new ArrayList<>();
        resultList.add(new YfManyCellMonitorModel(serialNumber, TimeTool.getNowTime(true), reqBean.getUserInfo()));
        doHandleSn(reqBean, 2, JSONObject.toJSONString(resultList));
    }

    public Object doHandleSn(StationRequestBean reqBean, Integer flag, String data) {
        switch (flag) {
            case 1:
                return new WorkCellDataCacheDispatch.builder().key(getDataKey(reqBean)).org(reqBean.getOrganizeCode()).build().get().getValue();
            case 2:
                return new WorkCellDataCacheDispatch.builder().key(getDataKey(reqBean)).value(data).timeSecond(MesPcnEnumUtil.EXPIRE_TIME.ONE_HOUR.getValue()).org(reqBean.getOrganizeCode()).build().save().getSuccess();
            default:
                return null;
        }
    }

    public Object doHandlePlcData(StationRequestBean reqBean, Integer flag, String plcCode, String data) {
        switch (flag) {
            case 1:
                return new WorkCellDataCacheDispatch.builder().key(getMonitorKey(reqBean, plcCode)).org(reqBean.getOrganizeCode()).build().get().getValue();
            case 2:
                return new WorkCellDataCacheDispatch.builder().key(getMonitorKey(reqBean, plcCode)).value(data).timeSecond(MesPcnEnumUtil.EXPIRE_TIME.ONE_HOUR.getValue()).org(reqBean.getOrganizeCode()).build().save().getSuccess();
            default:
                return null;
        }
    }

}
