package org.springblade.gateway.common_gateway.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.api.R;
import org.springblade.gateway.common_gateway.enums.PlatformSettingEnum;
import org.springblade.gateway.common_gateway.util.PlatformSettingUtil;
import org.springblade.sing.desk.entity.PlatformSetting;
import org.springblade.sing.desk.service.IPlatformSettingService;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 15:00 2021/11/9
 * @Modified By:
 */
@RestController
@AllArgsConstructor
@RequestMapping("app/platformsetting")
@Api(value = "平台设置", tags = "平台设置接口")
public class AppPlatFormSettingController extends BladeController {
	private IPlatformSettingService platformSettingService;

	private PlatformSettingUtil platformSettingUtil;

	/**
	 * 获取平台设置
	 */
	@GetMapping("/getPlatformValue")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取平台配置", notes = "传入key")
	public R<String> getPlatformSetting(@RequestParam PlatformSettingEnum platformSettingEnum){
		return R.data(platformSettingUtil.getPlatformSettingByCache(platformSettingEnum.name()));
	}

	/**
	 * 获取平台配置
	 */
	@GetMapping("/getPlatformValueByList")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "获取平台配置", notes = "传入key")
	public R<Map<String,String>> getPlatformValueByList(@RequestParam String keys){
		String[] split = keys.split(",");
		Map<String, String> result = new HashMap<>();
		for (String key : split) {
			String value = platformSettingUtil.getPlatformSettingByCache(key);
			if(StringUtils.isNotEmpty(value)){
				result.put(key,value);
			}
		}
		return R.data(result);
	}

	/**
	 * 修改平台设置
	 */
	@PostMapping("/updatePlatformValue")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "更新平台配置", notes = "传入key")
	public R<Boolean> getPlatformSetting(@Valid PlatformSetting platformSetting){
		platformSettingUtil.setPlatformSettingToCache(platformSetting);
		return R.data(platformSettingService.saveOrUpdate(platformSetting, Wrappers.<PlatformSetting>lambdaUpdate().eq(PlatformSetting::getKey,platformSetting.getKey())));
	}
}
