package com.younike.admin.controller.system;

import com.younike.admin.utils.ShiroUtils;
import com.younike.common.bean.APIResult;
import com.younike.common.bean.ResultGenerator;
import com.younike.common.constant.UserConstants;
import com.younike.common.core.controller.BaseController;
import com.younike.common.core.dto.AjaxResult;
import com.younike.common.core.page.TableResult;
import com.younike.service.pojo.SysConfig;
import com.younike.service.service.ISysConfigService;


import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 配置信息
 *
 * @author Andrew
 */
@RestController
@RequestMapping("/system/config")
public class SysConfigController extends BaseController {

    @Autowired
    private ISysConfigService configService;

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    public AjaxResult getConfigKey(@PathVariable String configKey) {
        return AjaxResult.success(configService.selectConfigByKey(configKey));
    }

    /**
     * 获取参数列表
     */
    @RequiresPermissions("system:config:list")
    @GetMapping("/list")
    public TableResult list(SysConfig config) {
        startPage();
        List<SysConfig> configs = configService.selectConfigList(config);
        return getDataTable(configs);
    }

    /**
     * 新增参数
     */
    @PostMapping("")
    public APIResult addConfig(@RequestBody SysConfig config) {
        //检查唯一性
        if (!configService.checkConfigKeyUnique(config).equals(UserConstants.CONFIG_KEY_UNIQUE)) {
            return ResultGenerator.getFailResult("该参数键名已存在");
        }
        config.setCreateBy(ShiroUtils.getLoginName());
        configService.insertConfig(config);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 根据id查找参数
     */
    @GetMapping(value = "/{configId}")
    public SysConfig getConfig(@PathVariable Long configId) {
        return configService.selectConfigById(configId);
    }

    /**
     * 更新参数
     */
    @PutMapping("")

    public APIResult updateConfig(@RequestBody SysConfig config) {
        //检查唯一性
        if (!configService.checkConfigKeyUnique(config).equals(UserConstants.CONFIG_KEY_UNIQUE)) {
            return ResultGenerator.getFailResult("该参数键名已存在");
        }
        config.setUpdateBy(ShiroUtils.getLoginName());
        configService.updateConfig(config);
        return ResultGenerator.getSuccessResult();
    }

    /**
     * 删除参数
     */
    @DeleteMapping(value = "/{configIds}")

    public APIResult deleteConfigs(@PathVariable String configIds) {
        try {
            configService.deleteConfigByIds(configIds);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return ResultGenerator.getSuccessResult();
    }
}
