package cn.edu.hactcm.cotroller;


import cn.edu.hactcm.common.R;
import cn.edu.hactcm.entity.Category;
import cn.edu.hactcm.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category){
        boolean flag = categoryService.save(category);
        if (flag) {
            return R.success("新增分类成功");
        }
        return R.error("新增分类失败！");
    }

    /**
     * 分页显示菜品分类
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> getPage(int page,int pageSize){
        Page<Category> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);
        pageInfo = categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 删除菜品分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> deleteById(@RequestParam Long ids){

        //remove方法已重写，检查是否关联了其他表格数据
        return categoryService.remove(ids) ? R.success("删除成功") : R.error("删除失败");

//        boolean flag = categoryService.removeById(ids);
        /*boolean flag = categoryService.remove(ids);
        if (flag) {
            return R.success("删除成功");
        }
        return R.error("删除失败");*/
    }

    /**
     * 分类修改
     * @param category
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody Category category){
        log.info(category.toString());
        return categoryService.updateById(category) ? R.success("修改成功") : R.error("修改失败");
    }

    /**
     * 新增菜品页面准备下拉列表数据，选择菜品分类
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> getList(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null,Category::getType,category.getType())
                .orderByAsc(Category::getSort).orderByDesc(Category::getCreateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
