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

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.casic.missiles.dto.business.outsource.OrderSampleDTO;
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.mapper.business.BusinessOrderSampleRelationMapper;
import com.casic.missiles.mapper.business.BusinessOutsourceProjectSampleRelationMapper;
import com.casic.missiles.model.business.BusinessOutsourceProjectSampleRelation;
import com.casic.missiles.service.listeners.NotifyEventPostProcessor;
import com.casic.missiles.utils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @Description: 分包项目验收审批通过处理
 *               分包项目验收通过后更新所有样品状态为检测完
 * @Author: wangpeng
 * @Date: 2023/3/29 16:21
 */
@Service(ActionStatusBeanEnum.OUTSOURCE_PROJECT_CHECK_BEAN_NAME)
public class OutsourceProjectCheckEventPostProcessor implements NotifyEventPostProcessor {
    @Autowired
    private BusinessOutsourceProjectSampleRelationMapper projectSampleRelationMapper;
    @Autowired
    private BusinessOrderSampleRelationMapper orderSampleRelationMapper;

    @Override
    public void doHandleNotifyEvent(NotifyEventStatusDTO notifyEventStatusDTO) {
        Long id = Long.valueOf(notifyEventStatusDTO.getId());
        Assert.isFalse(Objects.isNull(id), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        //查询分包项目&样品关联表得到委托书id、样品id，按委托书、样品id更新委托书&样品关联表样品状态为检测完
        QueryWrapper<BusinessOutsourceProjectSampleRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("project_id", id);
        List<BusinessOutsourceProjectSampleRelation> outsourceProjectSampleRelations = projectSampleRelationMapper.selectList(wrapper);
        if(CollectionUtils.isEmpty(outsourceProjectSampleRelations)){
            return;
        }
        List<OrderSampleDTO> orderSampleDTOS = ConvertUtils.sourceToTarget(outsourceProjectSampleRelations, OrderSampleDTO.class);
        int updateFlag = orderSampleRelationMapper.updateStatusBatchByOrderAndSample(orderSampleDTOS);
        if (updateFlag <= 0) {
            throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
        }
    }

}
