package cn.edu.hactcm.service.impl;

import cn.edu.hactcm.common.CustomException;
import cn.edu.hactcm.entity.Category;
import cn.edu.hactcm.entity.Dish;
import cn.edu.hactcm.entity.Setmeal;
import cn.edu.hactcm.mapper.CategoryMapper;
import cn.edu.hactcm.mapper.DishMapper;
import cn.edu.hactcm.mapper.SetmealMapper;
import cn.edu.hactcm.service.CategoryService;
import cn.edu.hactcm.service.SetmealService;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private DishMapper dishMapper;

    /**
     * 检查是否关联了其他表格数据
     * @param id
     * @return
     */
    public boolean remove(Long id) {
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        Integer meaCount = setmealMapper.selectCount(setmealLambdaQueryWrapper);
        if (meaCount > 0) {
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        Integer dishCount = dishMapper.selectCount(dishLambdaQueryWrapper);
        if (dishCount > 0) {
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }

        boolean flag = super.removeById(id);
        return flag;
    }
}
