package com.qiaoba.module.system.controller;

import com.qiaoba.api.system.entity.SysDictData;
import com.qiaoba.api.system.entity.param.SysDictDataParam;
import com.qiaoba.common.base.result.AjaxResult;
import com.qiaoba.common.base.validate.AddGroup;
import com.qiaoba.common.base.validate.EditGroup;
import com.qiaoba.common.database.entity.PageQuery;
import com.qiaoba.common.database.entity.TableDataInfo;
import com.qiaoba.common.poi.util.ExcelUtil;
import com.qiaoba.module.system.service.SysDictDataService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Size;
import java.util.List;

/**
 * 字典数据管理 Web层
 *
 * @author ailanyin
 * @version 1.0
 * @since 2022-09-22 04:20:28
 */
@Validated
@RestController
@RequestMapping("/system/dict/data")
@RequiredArgsConstructor
public class SysDictDataController {

    private final SysDictDataService sysDictDataService;

    @PreAuthorize("hasAuthority('system:dict:list')")
    @GetMapping("/list")
    public TableDataInfo list(@Validated SysDictDataParam param, PageQuery pageQuery) {
        return sysDictDataService.selectPageList(param, pageQuery);
    }

    @PreAuthorize("hasAuthority('system:dict:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, @Validated SysDictDataParam param) {
        List<SysDictData> list = sysDictDataService.selectList(param);
        ExcelUtil.exportExcel(list, SysDictData.class, "字典数据", response);
    }

    @PreAuthorize("hasAuthority('system:dict:query')")
    @GetMapping(value = "/{dictCode}")
    public AjaxResult getInfo(@Size(max = 30, message = "dictCode不合法") @PathVariable String dictCode) {
        return AjaxResult.success(sysDictDataService.selectById(dictCode));
    }

    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@Size(max = 30, message = "dictType不合法") @PathVariable String dictType) {
        return AjaxResult.success(sysDictDataService.selectFromCache(dictType));
    }

    @PreAuthorize("hasAuthority('system:dict:add')")
    @PostMapping
    public AjaxResult add(@Validated(AddGroup.class) @RequestBody SysDictData sysDictData) {
        return AjaxResult.toAjax(sysDictDataService.insert(sysDictData));
    }

    @PreAuthorize("hasAuthority('system:dict:edit')")
    @PutMapping
    public AjaxResult edit(@Validated(EditGroup.class) @RequestBody SysDictData sysDictData) {
        return AjaxResult.toAjax(sysDictDataService.update(sysDictData));
    }

    @PreAuthorize("hasAuthority('system:dict:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable List<String> ids) {
        return AjaxResult.toAjax(sysDictDataService.deleteByIds(ids));
    }
}
