package com.jd.lightapplication.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.model.ConfigInfo;
import com.jd.lightapplication.service.ConfigInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@Slf4j
@RestController()
@RequestMapping("/api/config")
@Api(tags = "系统配置表")
public class ConfigInfoController {

    @Resource
    private ConfigInfoService configInfoService;

    @GetMapping("/list")
    @ApiOperation(value = "1、分页查询")
    public R queryPageBean(Page page, ConfigInfo configInfo) {
        return R.success(configInfoService.page(page, configInfo));
    }

    @PostMapping("/addBean")
    @ApiOperation(value = "2、新增")
    public R addBean(@RequestBody ConfigInfo configInfo) {
        //判断key是否重复
        if (configInfoService.findByKey(configInfo.getConfigKey()) != null) {
            return R.fail("当前配置key已存在:" + configInfo.getConfigKey());
        }
        configInfo.setCreateTime(DateUtil.now());
        configInfoService.save(configInfo);
        return R.success();
    }

    @PostMapping("/updateBean")
    @ApiOperation(value = "3、修改")
    public R updateBean(@RequestBody ConfigInfo configInfo) {
        //判断key是否重复
        ConfigInfo bean = configInfoService.findByKey(configInfo.getConfigKey());
        if (bean != null && bean.getId() != configInfo.getId()) {
            return R.fail("当前配置key已存在:" + configInfo.getConfigKey());
        }
        configInfo.setUpdateTime(DateUtil.now());
        configInfoService.updateById(configInfo);
        return R.success();
    }

    @PostMapping("/deleteById")
    @ApiOperation(value = "4、删除")
    public R deleteById(long id) {
        configInfoService.removeById(id);
        return R.success();
    }

    @GetMapping("/find/{key}")
    @ApiOperation(value = "5、根据配置key查询配置信息")
    public R findByKey(String key) {
        return R.success(configInfoService.findByKey(key));
    }

}