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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesMediaFileCfgService;
import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesProdShiftRecordService;
import cn.estsh.i3plus.ext.mes.pcn.api.busi.IMesProductionCustomContextStepService;
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.api.busi.IMesWorkOrderExtService;
import cn.estsh.i3plus.ext.mes.pcn.apiservice.util.MesPcnException;
import cn.estsh.i3plus.ext.mes.pcn.pojo.context.MesProdShiftContext;
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.BaseModuleService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.IStepService;
import cn.estsh.i3plus.mes.pcn.util.StationKvBeanUtil;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.enumutil.MesPcnEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesStateMachineStatus;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkCell;
import cn.estsh.i3plus.pojo.mes.bean.MesWorkOrder;
import cn.estsh.i3plus.pojo.mes.model.StationKvBean;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.util.MesExtEnumUtil;
import cn.estsh.impp.framework.boot.util.SpringContextsUtil;
import com.alibaba.fastjson.JSONObject;
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.List;
import java.util.Map;

/**
 * @Description : 展示组件：非排序生产
 * @Author :wangjie
 **/
@Slf4j
@Service("mesProductionNoSortModuleService")
public class MesProductionNoSortModuleService extends BaseModuleService {

    @Autowired
    private IMesProductionProcessContextStepService productionProcessContextStepService;

    @Autowired
    private IMesProductionDispatchContextStepService productionDispatchContextStepService;

    @Autowired
    private IMesProductionCustomContextStepService productionCustomContextStepService;

    @Autowired
    private IMesProdShiftRecordService prodShiftRecordService;

    @Autowired
    private IMesWorkOrderExtService workOrderExtService;

    @Autowired
    private IMesMediaFileCfgService mediaFileCfgService;

    @Override
    public void init(StationRequestBean reqBean) {

        //获取上下文信息
        MesProductionProcessContext productionProcessContext = productionProcessContextStepService.getProductionProcessContext(reqBean, false);
        //配置错误 抛出异常
        if (!productionProcessContext.getSuccess()) {
            this.sendMessage(reqBean, new StationResultBean()
                    .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.BUSI_LIST.getValue())
                    .addStationResultBeans(new StationResultBean().resultObj(MesPcnExtConstWords.STEP_DISABLE_SCAN)
                            .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.STEP_TITLE.getValue()).dataType(MesPcnEnumUtil.STATION_DATA_TYPE.TITLE.getValue()).message(String.format("信息: %s!", productionProcessContext.getMessage())))
                    .addStationResultBeans(new StationResultBean().writeDbLog()
                            .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE.getValue()).dataType(MesPcnEnumUtil.STATION_DATA_TYPE.TEXT.getValue()).message(productionProcessContext.getMessage()))
            );

            MesPcnException.throwBusiException(productionProcessContext.getMessage());
        }

        //获取班次信息，先查询缓存，缓存没有在查询数据库
        List<StationKvBean> prodShiftDataContext = prodShiftRecordService.getShiftRecordStationKvBeans(reqBean.getOrganizeCode(), reqBean.getWorkCenterCode());
        if (CollectionUtils.isEmpty(prodShiftDataContext)) {
            this.sendMessage(reqBean, new StationResultBean()
                    .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.BUSI_LIST.getValue())
                    .addStationResultBeans(new StationResultBean().resultObj(MesPcnExtConstWords.STEP_DISABLE_SCAN)
                            .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.STEP_TITLE.getValue()).dataType(MesPcnEnumUtil.STATION_DATA_TYPE.TITLE.getValue()).message("信息: 请先开班!"))
                    .addStationResultBeans(new StationResultBean().writeDbLog()
                            .busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MESSAGE.getValue()).dataType(MesPcnEnumUtil.STATION_DATA_TYPE.TEXT.getValue()).message("请先开班!"))
            );

            MesPcnException.throwBusiException("请先开班!");
        }

        // 获取工单信息
        List<List<StationKvBean>> moduleContentContext = productionDispatchContextStepService.getModuleContentContext(reqBean);

        //封装数据: 班次班组和工单
        StationResultBean resultBean = getStationResultBean(reqBean, moduleContentContext, prodShiftDataContext);

        //封装当前班组班次信息
        MesProdShiftContext mesProdShiftKvBean = prodShiftRecordService.getMesProdShiftKvBean(prodShiftDataContext);
        //封装工位展示的客制化信息 (优先级: 工位图/视频/柱状图-->加工数)
        StationResultBean resultBeanCustom = getStationResultBean(reqBean, productionProcessContext.getWorkCell(), mesProdShiftKvBean);

        if (null == resultBeanCustom) this.sendMessage(reqBean, resultBean);
        else this.sendMessage(reqBean, new StationResultBean().busiType(MesPcnEnumUtil.STATION_BUSI_TYPE.BUSI_LIST.getValue()).addStationResultBeans(resultBean).addStationResultBeans(resultBeanCustom));

        //验证工位是否锁定
        reqBean.getDataMap().put(MesPcnEnumUtil.ACTOR_RECEIVE_STRATEGY.WS_CMD_INIT_MODULE.getCode(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValueStr());
        ((IStepService) SpringContextsUtil.getBean("mesCountDownShowStepService")).executeInState(reqBean);

        //设备BYPASS监控
        ((IStepService) SpringContextsUtil.getBean("mesEquipByPassReadStepService")).executeInState(reqBean);

    }

    private StationResultBean getStationResultBean(StationRequestBean reqBean, List<List<StationKvBean>> moduleContentContext, List<StationKvBean> prodShiftDataContext) {
        StationResultBean resultBean = new StationResultBean();
        resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MODULE_CONTENT.getValue());
        resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.CUSTOM.getValue());
        resultBean.setCustomPageName(MesPcnExtConstWords.CUSTOM_PAGE_NAME_DEFAULT);
        resultBean.setSpecialDisplayData(getStepColIndent(reqBean));

        resultBean.setResultObj(prodShiftDataContext);
        resultBean.setResultList(moduleContentContext);
        return resultBean;
    }

    //封装工位展示的客制化信息(优先级: 工位图/视频/柱状图-->加工数)
    private StationResultBean getStationResultBean(StationRequestBean reqBean, MesWorkCell workCell, MesProdShiftContext mesProdShiftKvBean) {

        StationResultBean resultBean = new StationResultBean();
        resultBean.setBusiType(MesPcnEnumUtil.STATION_BUSI_TYPE.MODULE_CUSTOM_CONTENT.getValue());
        resultBean.setCustomPageName(MesPcnExtConstWords.CUSTOM_PAGE_NAME_WORK_CELL);

        //验证是否展示柱状图
        if (!StringUtils.isEmpty(workCell.getIsShowMsg()) && workCell.getIsShowMsg().compareTo(MesExtEnumUtil.WORK_FILE_TYPE.HISTOGRAM.getValue()) == 0) {
            List<MesWorkOrder> workOrderList = workOrderExtService.getWorkOrderListByShiftCode(reqBean.getOrganizeCode(), workCell.getWorkCenterCode(), mesProdShiftKvBean.getShiftCode());
            List<List<StationKvBean>> stationKvBeans = new ArrayList<>();
            if (CollectionUtils.isEmpty(workOrderList)) {
                StationKvBeanUtil.addStationKvBeanList(stationKvBeans, new ArrayList<>(),
                        new StationKvBean(MesPcnExtConstWords.QTY, "工单计划数", MesPcnExtConstWords.ZERO_STR),
                        new StationKvBean(MesPcnExtConstWords.COMPLETE_QTY, "工单完成数", MesPcnExtConstWords.ZERO_STR));
            } else {
                Double qty = workOrderList.stream().map(MesWorkOrder::getQty).reduce((a, b) -> a + b).get();
                Double complateQty = workOrderList.stream().map(MesWorkOrder::getCompleteQty).reduce((a, b) -> a + b).get();

                StationKvBeanUtil.addStationKvBeanList(stationKvBeans, new ArrayList<>(),
                        new StationKvBean(MesPcnExtConstWords.QTY, "工单计划数", qty.toString()),
                        new StationKvBean(MesPcnExtConstWords.COMPLETE_QTY, "工单完成数", complateQty.toString()));
            }
            resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.ECHART.getValue());
            resultBean.setResultList(stationKvBeans);
            return resultBean;
        }

        //判断是否配置的是展示文件
        String url = null;
        if (!StringUtils.isEmpty(workCell.getIsShowMsg()) && !StringUtils.isEmpty(MesExtEnumUtil.WORK_FILE_TYPE.valueOfDescription(workCell.getIsShowMsg()))) {
            url = mediaFileCfgService.getMediaFileUrl(reqBean.getOrganizeCode(), workCell.getFileId());
            if (!StringUtils.isEmpty(url)) {
                JSONObject reqJson = new JSONObject();
                if (workCell.getIsShowMsg().compareTo(MesExtEnumUtil.WORK_FILE_TYPE.WORK_CELL_PICTURE.getValue()) == 0) resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.IMAGE.getValue());
                else resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.VIDEO.getValue());
                reqJson.put(MesPcnExtConstWords.URL, url);
                resultBean.setResultObj(reqJson);
                return resultBean;
            }
        }

        if (StringUtils.isEmpty(url) && !StringUtils.isEmpty(workCell.getIsCountFinish()) && workCell.getIsCountFinish().compareTo(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue()) == 0) {
            //获取上下文工位加工数统计信息
            List<StationKvBean> productionStatisticsContext = productionCustomContextStepService.getProductionStatisticsContext(reqBean);
            if (CollectionUtils.isEmpty(productionStatisticsContext)) productionStatisticsContext = productionCustomContextStepService.getProductionStatisticsContext(mesProdShiftKvBean, MesPcnExtConstWords.ZERO_STR);
            resultBean.setDataType(MesPcnEnumUtil.STATION_DATA_TYPE.TEXT.getValue());
            resultBean.setResultList(productionStatisticsContext);
            return resultBean;
        }

        return null;
    }

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

}
