/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.user.platform.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.common.bean.SysConfig;
import com.yami.shop.bean.param.ScoreConfigParam;
import com.yami.shop.common.annotation.SysLog;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;


/**
 * 积分其他配置管理实现
 *
 * @author lhd
 * @version 1.0.0
 * @since 2020-02-26
 */
@RestController
@RequestMapping("/user/scoreExplainConfig")
public class ScoreOtherConfigController {
	@Autowired
	private SysConfigService sysConfigService;


	/**
	 * 配置信息
	 */
	@GetMapping("/info/{id}")
	@PreAuthorize("@pms.hasPermission('score:explainConfig:info')")
	public ResponseEntity<SysConfig> info(@PathVariable("id") String key){
		SysConfig config = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getParamKey,key));
		if(Objects.isNull(config)){
			return ResponseEntity.ok(new SysConfig());
		}
		return ResponseEntity.ok(config);
	}

	/**
	 * 保存配置
	 */
	@SysLog("保存配置")
	@PostMapping
	@PreAuthorize("@pms.hasPermission('score:explainConfig:save')")
	public ResponseEntity<Void> save(@RequestBody  SysConfig config){
		if (sysConfigService.count(new LambdaQueryWrapper<SysConfig>()
				.eq(SysConfig::getParamKey, config.getParamKey())) > 0) {
			throw new GlobalException("系统已存在相同配置的key，无法重复添加,请刷新重试！");
		}
		sysConfigService.save(config);
		sysConfigService.removeSysConfig(config.getParamKey());
		return ResponseEntity.ok().build();
	}

	/**
	 * 修改配置
	 */
	@SysLog("修改配置")
	@PutMapping
	@PreAuthorize("@pms.hasPermission('score:explainConfig:update')")
	public ResponseEntity<Void> update(@RequestBody @Valid SysConfig config){
		SysConfig dbSysConfig = sysConfigService.getOne(new LambdaQueryWrapper<SysConfig>()
				.eq(SysConfig::getParamKey, config.getParamKey()));
		dbSysConfig.setParamValue(config.getParamValue());
		sysConfigService.updateById(dbSysConfig);
		sysConfigService.removeSysConfig(config.getParamKey());
		return ResponseEntity.ok().build();
	}


}
