package com.gyee.wisdom.alarm.sharding.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gyee.wisdom.alarm.sharding.entity.Datadictionary;
import com.gyee.wisdom.alarm.sharding.service.DatadictionaryService;
import com.gyee.wisdom.alarm.sharding.util.ResponseWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @descrition:
 * @author:Xugp
 * @date:2022-05-12
 */
@Slf4j
@RestController
@RequestMapping("/datadictionary")
@CrossOrigin
@Api(tags = {"字典接口"})
public class DatadictionaryController {

    @Autowired
    private DatadictionaryService datadictionaryService;

    @GetMapping()
    public List<Datadictionary> getAllDatadictionary() {
        List<Datadictionary> datadictionaries = datadictionaryService.getAllDatadictionary();
        return datadictionaries;
    }

    @ApiOperation("分页查询字典")
    @GetMapping(value = "/page")
    public ResponseWrapper queryByPage(
            @ApiParam(value = "当前页") @RequestParam(value = "pagenum") Integer pageNum,
            @ApiParam(value = "分页大小") @RequestParam(value = "pagesize") Integer pageSize,
            @ApiParam(value = "字典名称") @RequestParam(value = "name", required = false) String name,
            @ApiParam(value = "字典类型") @RequestParam(value = "category", required = false) String category
    ) {
        Page<Datadictionary> page = new Page(pageNum, pageSize);
        IPage<Datadictionary> pageResult = datadictionaryService.pageQueryAll(page, name,category);

        return ResponseWrapper.success("请求成功",pageResult);
    }

    @ApiOperation("新增或修改字典")
    @PostMapping(value = "/saveorupdate")
    @ResponseBody
    public ResponseWrapper saveDatadictionary(@ApiParam(value = "字典对象") @RequestBody Datadictionary datadictionary){
        ResponseWrapper<Datadictionary> wrapper = null;
        int result = datadictionaryService.saveOrUpdateDatadictionary(datadictionary);
        if (result <= 0) {
            wrapper = ResponseWrapper.error("操作数据库失败");
        }
        else {
            wrapper = ResponseWrapper.success("操作数据库成功");
        }
        return wrapper;
    }

    @ApiOperation("删除字典")
    @DeleteMapping(value = "/{id}")
    @ResponseBody
    public ResponseWrapper deleteDatadictionary(
            @ApiParam(value = "字典编号") @PathVariable("id") String id) {
        ResponseWrapper wrapper = null;
        int s = datadictionaryService.deleteDatadictionary(id);
        if (s > 0) {
            wrapper = ResponseWrapper.success("删除成功!", s);
            return wrapper;
        } else {
            wrapper = ResponseWrapper.error("删除失败!");
            return wrapper;
        }

    }
}
