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

import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.BaseSwsService;
import cn.estsh.i3plus.mes.pcn.serviceimpl.fsm.function.IFsmModuleFunctionService;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.util.MesConstWords;
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.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.*;
import cn.estsh.i3plus.pojo.mes.model.ButtonDynamicModel;
import cn.estsh.i3plus.pojo.mes.model.StationRequestBean;
import cn.estsh.i3plus.pojo.mes.model.StationResultBean;
import cn.estsh.i3plus.pojo.mes.repository.*;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description : 工位参数按钮事件接口实现【设备停机】FUNCTION_EQU_DOWNTIME
 **/
@Service
public class MesFunctionEquDowntimeService extends BaseSwsService implements IFsmModuleFunctionService {

    @Autowired
    private IMesBasDowntimeReasonRepository downtimeReasonRDao;
    @Autowired
    private IMesBasDowntimeReasonTypeRepository downtimeReasonTypeRDao;
    @Autowired
    private MesConfigRepository configRepository;
    @Autowired
    private MesDowntimeRecordRepository mesDowntimeRecordRDao;

    @Autowired
    private MesEquipmentRepository mesEquipmentRDao;

    @Autowired
    private MesWcEquipmentRepository wcEquipmentRepository;
    @Override
    public Object doCustomApiDispatch(StationRequestBean reqBean, StationResultBean resultBean, ButtonDynamicModel buttonDynamicModel) {
        String functionValue = buttonDynamicModel.getFunctionValue();
        if (!StringUtil.isEmpty(functionValue)) {
            this.sendMessage(reqBean, resultBean.isWs(false).writeDbLog(MesPcnEnumUtil.WORK_CELL_SCAN_MONITOR_LOG_TYPE.PICK.getValue()).scanInfo(buttonDynamicModel.getFunctionValue()),
                    String.format("生产线[%s]工位[%s]%s成功,提交信息[%s]", reqBean.getWorkCenterCode(), reqBean.getWorkCellCode(), buttonDynamicModel.getButtonName(), buttonDynamicModel.getFunctionValue()),
                    MesPcnEnumUtil.STATION_BUSI_TYPE.RUNNING_INFO, MesPcnEnumUtil.STATION_DATA_TYPE.TEXT);
            //JSON 调用新增接口
            String userInfo = reqBean.getUserInfo();
            String organizeCode = reqBean.getOrganizeCode();
            JSONObject jsonObject= JSONUtil.parseObj(functionValue);
            String reason = jsonObject.getStr("reasonCode");
            String type = jsonObject.getStr("reasonTypeCode");
            if(StringUtil.isEmpty(reason)||StringUtil.isEmpty(type)){
                return true;
            }
            MesWcEquipment  wcEquipmentDbList = wcEquipmentRepository.getByProperty(
                    new String[]{MesPcnExtConstWords.ORGANIZE_CODE, MesPcnExtConstWords.IS_DELETED, MesPcnExtConstWords.IS_VALID,
                            MesPcnExtConstWords.WORK_CENTER_CODE, MesPcnExtConstWords.WORK_CELL_CODE},
                    new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(),
                            reqBean.getWorkCenterCode(), reqBean.getWorkCellCode()});
            MesEquipment mesEquipment = mesEquipmentRDao.getByProperty(
                    new String[]{MesConstWords.ORGANIZE_CODE,MesPcnExtConstWords.EQUIPMENT_CODE, MesConstWords.IS_DELETED, MesConstWords.IS_VALID},
                    new Object[]{organizeCode, wcEquipmentDbList.getEquipmentCode(),
                            CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),
                            CommonEnumUtil.IS_VAILD.VAILD.getValue()});

            DdlPackBean ddlPackBeanDowntime = DdlPackBean.getDdlPackBean(organizeCode);
            DdlPreparedPack.getStringEqualPack(mesEquipment.getEquipmentCode(), "equipmentCode", ddlPackBeanDowntime);
            DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{"createDatetime"}, ddlPackBeanDowntime);
            MesDowntimeRecord mesDowntimeRecordDao = mesDowntimeRecordRDao.getByProperty(ddlPackBeanDowntime);
            if (!StringUtil.isEmpty(mesDowntimeRecordDao)) {
                // 如果有停机结束时间，则不需要修改，否则需要
                if (StringUtil.isEmpty(mesDowntimeRecordDao.getModifyDatetime())) {
                    ConvertBean.serviceModelUpdate(mesDowntimeRecordDao, "MesDowntimeRecordJob");
                    mesDowntimeRecordRDao.update(mesDowntimeRecordDao);
                }
            }

            //新增设备停机记录
            MesDowntimeRecord mesDowntimeRecord = new MesDowntimeRecord();
            mesDowntimeRecord.setOrganizeCode(organizeCode);
            mesDowntimeRecord.setEquipId(mesEquipment.getEquipId());
            mesDowntimeRecord.setEquipmentCode(mesEquipment.getEquipmentCode());
            mesDowntimeRecord.setAreaCode(reqBean.getAreaCode());
            mesDowntimeRecord.setWorkCenterCode(reqBean.getWorkCenterCode());
            mesDowntimeRecord.setWorkCellCode(reqBean.getWorkCellCode());
            mesDowntimeRecord.setReasonCode(StringUtil.isEmpty(reason) ? "" : reason);
            mesDowntimeRecord.setReasonTypeCode(StringUtil.isEmpty(type) ? "" : type);
            ConvertBean.serviceModelInitialize(mesDowntimeRecord, userInfo);
            mesDowntimeRecord.setModifyDatetime(null);
            mesDowntimeRecordRDao.insert(mesDowntimeRecord);


            return true;
        } else {
            DdlPackBean packBean = DdlPackBean.getDdlPackBean(reqBean.getOrganizeCode());
            List<MesDowntimeReasonType> downtimeReasonTypeList = downtimeReasonTypeRDao.findByHqlWhere(packBean);
            if (!CollectionUtils.isEmpty(downtimeReasonTypeList)) {
                //查对应原因
                List<MesDowntimeReason> mesDowntimeReasonList = downtimeReasonRDao.findByProperty(
                        new String[]{"organizeCode", "isDeleted", "isValid"},
                        new Object[]{reqBean.getOrganizeCode(),
                                CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(),
                                CommonEnumUtil.IS_VAILD.VAILD.getValue()});

                Map<String, List<MesDowntimeReason>> reasonMap = mesDowntimeReasonList.stream().collect(Collectors.groupingBy(MesDowntimeReason::getReasonTypeCode));

                for (MesDowntimeReasonType mesDowntimeReasonType : downtimeReasonTypeList) {
                    if (!StringUtil.isEmpty(reasonMap.get(mesDowntimeReasonType.getReasonTypeCode()))) {
                        mesDowntimeReasonType.setDowntimeReasonList(reasonMap.get(mesDowntimeReasonType.getReasonTypeCode()));
                    }
                }
            }
            return downtimeReasonTypeList;
        }
    }

}
