package tech.glinfo.enbao.modules.sh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.glinfo.enbao.common.utils.PageUtils;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.modules.sh.entity.ShCategoryEntity;
import tech.glinfo.enbao.modules.sh.entity.ShProductEntity;
import tech.glinfo.enbao.modules.sh.service.ShCategoryService;
import tech.glinfo.enbao.modules.sh.service.ShProductService;

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


/**
 * 产品分类
 *
 * @author linzhenjie
 * @email linzhenjie@gltech.com
 * @date 2019-12-05 15:29:57
 */
@RestController
@RequestMapping("sh/category")
public class ShCategoryController {
    @Autowired
    private ShCategoryService shCategoryService;

    @Autowired
    private ShProductService shProductService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sh:category:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = shCategoryService.queryPage(params);

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


    /**
     * 列表
     */
    @RequestMapping("/listAll")
    public R listAll(){

        return R.ok().put("categoryOptions", shCategoryService.list());
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sh:category:info")
    public R info(@PathVariable("id") Integer id){
		ShCategoryEntity shCategory = shCategoryService.getById(id);

        return R.ok().put("category", shCategory);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sh:category:save")
    public R save(@RequestBody ShCategoryEntity shCategory){
        shCategoryService.save(shCategory);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sh:category:update")
    public R update(@RequestBody ShCategoryEntity shCategory){
        shCategoryService.updateById(shCategory);

		//改变产品的分类名称
        ShProductEntity shProductEntity = new ShProductEntity();
        shProductEntity.setCategoryName(shCategory.getName());
        shProductService.update(shProductEntity, new QueryWrapper<ShProductEntity>().eq("category_id", shCategory.getId()));

        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete/{id}")
    @RequiresPermissions("sh:category:delete")
    public R delete(@PathVariable("id") long id){
        //判断分类下面是否关联产品
        List<ShProductEntity> list = shProductService.list(new QueryWrapper<ShProductEntity>().eq("category_id", id));

        if(list.size() > 0){
            return R.error("该分类关联了产品，请先删除产品");
        }

        shCategoryService.removeById(id);

        return R.ok();
    }

}
