package io.renren.modules.sys.controller.algs;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.sys.controller.AbstractController;
import io.renren.modules.sys.entity.SysRoleEntity;
import io.renren.modules.sys.entity.algs.CategoryEntity;
import io.renren.modules.sys.service.CategoryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Ivan Q
 * @Date: 2021/5/31 16:34
 */
@RestController
@RequestMapping("/category")
public class CategoryController extends AbstractController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 类别列表
     * 不返回完全，返回一页的数据
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:category:list")
    public R list(@RequestParam Map<String, Object> params){

        PageUtils page = categoryService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 类别列表
     * 用于其他数据页面中对，所有类别的获取.
     * 如果想要设置权限，打开@RequiresPermissions
     */
    @GetMapping("/select")
//    @RequiresPermissions("sys:category:select")
    public R select(){
        List<CategoryEntity> list = (List<CategoryEntity>) categoryService.list();
        return R.ok().put("list", list);
    }

    /**
     * 删除类别
     */
    @SysLog("删除类别")
    @PostMapping("/delete")
    @RequiresPermissions("sys:category:delete")
    public R delete(@RequestBody Long[] categoryIds){
        categoryService.deleteBatch(categoryIds);

        return R.ok();
    }

    /**
     * 保存类别
     */
    @SysLog("保存类别")
    @PostMapping("/save")
    @RequiresPermissions("sys:category:save")
    public R save(@RequestBody CategoryEntity category){
        ValidatorUtils.validateEntity(category);
        List<CategoryEntity> list = (List<CategoryEntity>) categoryService.list();
        for(CategoryEntity categoryEntity : list){
            if(categoryEntity.getCategoryName().equals(category.getCategoryName())) return R.error("已存在重复类别");
        }
        categoryService.save(category);
        return R.ok();
    }
}
