package com.ruoyi.tjfx.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.tjfx.common.ApiResponse;
import com.ruoyi.tjfx.common.PageResponse;
import com.ruoyi.tjfx.service.CategoryService;
import com.ruoyi.tjfx.entity.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@SaIgnore
@Slf4j
@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;
    @GetMapping("/simple")
    public ApiResponse<List<Category>> getSimpleCategories() {
        try {
            List<Category> categories = categoryService.getAllSimple();
            return ApiResponse.success(categories);
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            return ApiResponse.error("获取分类列表失败");
        }
    }
/*
    @GetMapping
    public ApiResponse<List<Category>> listAll() {
        return ApiResponse.success(categoryService.listAll(), "获取成功");
    }*/

    /**
     * 分页查询分类
     */
    @GetMapping()
    public ApiResponse<PageResponse<Category>> getPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {
        try {
            PageResponse<Category> result = categoryService.getPage(page, pageSize, name);
            return ApiResponse.success(result, "获取成功");
        } catch (Exception e) {
            log.error("获取分类列表失败", e);
            return ApiResponse.error("获取分类列表失败");
        }
    }

    @GetMapping("/{id}")
    public ApiResponse<Category> getById(@PathVariable Long id) {
        Category data = categoryService.getById(id);
        if (data == null) return ApiResponse.error(404, "数据不存在");
        return ApiResponse.success(data, "获取成功");
    }

    @PostMapping
    public ApiResponse<Void> add(@RequestBody Category category) {
        categoryService.add(category);
        return ApiResponse.success(null, "新增成功");
    }

    @PutMapping("/{id}")
    public ApiResponse<Void> update(@PathVariable Long id, @RequestBody Category category) {
        categoryService.update(id, category);
        return ApiResponse.success(null, "更新成功");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        categoryService.delete(id);
        return ApiResponse.success(null, "删除成功");
    }
}
