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

import cn.estsh.i3plus.ext.mes.pcn.api.base.IMesBasDowntimeReasonTypeService;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.i3plus.pojo.base.util.StringUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesDowntimeReason;
import cn.estsh.i3plus.pojo.mes.bean.MesDowntimeReasonType;
import cn.estsh.i3plus.pojo.mes.repository.IMesBasDowntimeReasonRepository;
import cn.estsh.i3plus.pojo.mes.repository.IMesBasDowntimeReasonTypeRepository;
import lombok.extern.slf4j.Slf4j;
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 : 设备停机类型
 * @Reference :
 * @Author : gsz
 * @CreateDate 2024/5/17 14:06
 * @Modify:
 **/
@Service
@Slf4j
public class MesBasDowntimeReasonTypeServiceImpl implements IMesBasDowntimeReasonTypeService {

    @Autowired
    private IMesBasDowntimeReasonRepository downtimeReasonRDao;
    @Autowired
    private IMesBasDowntimeReasonTypeRepository downtimeReasonTypeRDao;


    /**
     * 查询设备停机类型和原因
     *
     * @param downtimeReasonType
     * @param pager
     * @return
     */
    @Override
    public List<MesDowntimeReasonType> findMesDowntimeTypeReason(MesDowntimeReasonType downtimeReasonType, Pager pager) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(downtimeReasonType.getOrganizeCode());
        DdlPreparedPack.getStringEqualPack(downtimeReasonType.getReasonTypeCode(), "reasonTypeCode", packBean);
        List<MesDowntimeReasonType> downtimeReasonTypeList = downtimeReasonTypeRDao.findByHqlPage(packBean, pager);

        if (!CollectionUtils.isEmpty(downtimeReasonTypeList)) {
            //查对应原因
            List<MesDowntimeReason> mesDowntimeReasonList = downtimeReasonRDao.findByProperty(
                    new String[]{"organizeCode", "isDeleted", "isValid"},
                    new Object[]{downtimeReasonType.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;
    }
}
