package com.starry.admin.modules.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starry.admin.modules.system.entity.SysDictEntity;
import com.starry.admin.modules.system.service.ISysDictService;
import com.starry.admin.modules.system.vo.SysDictVo;
import com.starry.common.annotation.Log;
import com.starry.common.enums.BusinessType;
import com.starry.common.result.R;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


/**
 * 字典表Controller
 *
 * @author admin
 */
@RestController
@RequestMapping("/system/dict")
public class SysDictController {
    @Resource
    private ISysDictService xlDictService;

    /**
     * 查询字典表列表
     */
    @PreAuthorize("@customSs.hasPermission('system:dict:list')")
    @GetMapping("/list")
    public R list(SysDictVo dictVo) {
        Page<SysDictEntity> list = xlDictService.selectXlDictList(dictVo);
        return R.ok(list);
    }


    /**
     * 获取字典表详细信息
     */
    @PreAuthorize("@customSs.hasPermission('system:dict:query')")
    @GetMapping(value = "/{dictId}")
    public R getInfo(@PathVariable("dictId") Long dictId) {
        return R.ok(xlDictService.selectXlDictByDictId(dictId));
    }

    /**
     * 新增字典表
     */
    @PreAuthorize("@customSs.hasPermission('system:dict:create')")
    @Log(title = "字典表", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public R create(@RequestBody SysDictEntity sysDictEntity) {
        boolean success = xlDictService.create(sysDictEntity);
        if (success) {
            return R.ok();
        }
        return R.error("添加失败");
    }

    /**
     * 修改字典表
     */
    @PreAuthorize("@customSs.hasPermission('system:dict:edit')")
    @Log(title = "字典表", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/update/{dictId}")
    public R update(@PathVariable Long dictId, @RequestBody SysDictEntity sysDictEntity) {
        sysDictEntity.setDictId(dictId);
        boolean success = xlDictService.update(sysDictEntity);
        if (success) {
            return R.ok();
        }
        return R.error("修改失败");
    }

    /**
     * 删除字典表
     */
    @PreAuthorize("@customSs.hasPermission('system:dict:remove')")
    @Log(title = "字典表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dictIds}")
    public R remove(@PathVariable Long[] dictIds) {
        return R.ok(xlDictService.deleteXlDictByDictIds(dictIds));
    }

    @GetMapping("/optionselect")
    public R optionselect() {
        List<SysDictEntity> list = xlDictService.selectDictTypeAll();
        return R.ok(list);
    }

    /**
     * 刷新字典缓存
     */
    @PreAuthorize("@customSs.hasPermission('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public R refreshCache() {
        xlDictService.resetDictCache();
        return R.ok();
    }
}
