package cn.edu.hactcm.service.impl;

import cn.edu.hactcm.common.CustomException;
import cn.edu.hactcm.dto.SetmealDto;
import cn.edu.hactcm.entity.Setmeal;
import cn.edu.hactcm.entity.SetmealDish;
import cn.edu.hactcm.mapper.SetmealMapper;
import cn.edu.hactcm.service.SetmealDishService;
import cn.edu.hactcm.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 添加套餐
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);

        for (SetmealDish setmealDish : setmealDto.getSetmealDishes()) {
            setmealDish.setSetmealId(setmealDto.getId());
        }

        setmealDishService.saveBatch(setmealDto.getSetmealDishes());
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> list) {
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId,list).eq(Setmeal::getStatus,1);
        int count = setmealService.count(queryWrapper);
        if (count > 0) {
            throw new CustomException("有套餐正在售卖中，不可删除！");
        }
        this.removeByIds(list);

        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapperLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapperLambdaQueryWrapper.in(SetmealDish::getSetmealId,list);
        setmealDishService.remove(setmealDishLambdaQueryWrapperLambdaQueryWrapper);

    }
}
