package com.casic.missiles.service.listeners.processor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.casic.missiles.dto.flowable.NotifyEventStatusDTO;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.notifyevent.ActionStatusBeanEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.service.listeners.NotifyEventPostProcessor;
import com.casic.missiles.mapper.MeterFixedAssetsMapper;
import com.casic.missiles.mapper.equipment.EquipmentStandardApplyEquipmentMapper;
import com.casic.missiles.model.equipment.EquipmentFixedAssets;
import com.casic.missiles.model.equipment.EquipmentStandardApplyEquipment;
import com.casic.missiles.utils.SpringContextUtil;
import org.springframework.stereotype.Service;

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

/**
 * @author xzz
 *
 *   审批通过后修改标准装置业务状态
 */
@Service(ActionStatusBeanEnum.APPLY_BEAN_NAME)
public class EquipmentApplyEventPostProcessor implements NotifyEventPostProcessor {

    @Override
    public void doHandleNotifyEvent( NotifyEventStatusDTO notifyEventStatusDTO) {
        MeterFixedAssetsMapper meterFixedAssetsMapper = SpringContextUtil.getBean(MeterFixedAssetsMapper.class);
        EquipmentStandardApplyEquipmentMapper applyEquipmentMapper = SpringContextUtil.getBean(EquipmentStandardApplyEquipmentMapper.class);
        // 通过申请id查询出申请设备列表
        QueryWrapper<EquipmentStandardApplyEquipment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("standard_apply_id", notifyEventStatusDTO.getId());
        List<EquipmentStandardApplyEquipment> equipmentStandardApplyEquipments = applyEquipmentMapper.selectList(queryWrapper);
        List<Long> equipmentIds = equipmentStandardApplyEquipments.stream().map(EquipmentStandardApplyEquipment::getEquipmentId).collect(Collectors.toList());
        // 修改对应设备状态
        UpdateWrapper<EquipmentFixedAssets> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("id", equipmentIds).set("manager_state", notifyEventStatusDTO.getStatus());
        if (meterFixedAssetsMapper.update(null, updateWrapper) <= 0) {
            throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
        }
    }

}
