package io.renren.modules.generator.controller;

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

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/category")
@DataSource("slave2")
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();
        System.out.println("所有类别");
        for (CategoryEntity categoryEntity:list){
            System.out.println(categoryEntity.getCategoryName());
        }
        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();
    }
}
