package org.springblade.gateway.common_gateway.util;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.gateway.common_gateway.constant.PlatformSettingConstant;
import org.springblade.gateway.common_gateway.dto.ActiveSettingDto;
import org.springblade.gateway.common_gateway.dto.PageSettingDto;
import org.springblade.gateway.common_gateway.enums.PlatformSettingEnum;
import org.springblade.sing.desk.entity.PlatformSetting;
import org.springblade.sing.desk.service.IPlatformSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotNull;

/**
 * @Author: Silent
 * @Description 获取平台设置工具
 * @Date: Created in 15:18 2021/11/9
 * @Modified By:
 */
@Component
@Slf4j
public class PlatformSettingUtil {
	@Autowired
	private IPlatformSettingService platformSettingService;

	@Autowired
	private BladeRedis bladeRedis;

	/**
	 * 获取页面配置
	 * @return
	 */
	public PageSettingDto getPageSetting(){
		return getPlatformSettingByCache(PlatformSettingEnum.PAGE_INTERFACE_SHOW.name(),PageSettingDto.class);
	}

	/**
	 * 获取活动配置
	 * @return
	 */
	public ActiveSettingDto getActiveSetting(){
		return getPlatformSettingByCache(PlatformSettingEnum.ACTIVE_SETTING.name(),ActiveSettingDto.class);
	}

	/**
	 * 获取平台设置
	 * @return
	 */
	public <T> T getPlatformSettingByCache(String key,@NotNull Class<T> tClass){
		String platformSettingByCache = getPlatformSettingByCache(key);
		if(StringUtils.isNotEmpty(platformSettingByCache)){
			try {
				return JSON.parseObject(platformSettingByCache,tClass);
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
		return null;
	}

	/**
	 * 获取平台设置
	 * @return
	 */
	public String getPlatformSettingByCache(String key){
		String value = bladeRedis.hGet(PlatformSettingConstant.cacheKey,key);
		if(ObjectUtils.isEmpty(value)){
			PlatformSetting platformSetting = platformSettingService.getOne(Wrappers.<PlatformSetting>lambdaQuery().eq(PlatformSetting::getKey, key));
			//返回值
			if(ObjectUtils.isNotEmpty(platformSetting)){
				//添加到缓存
				setPlatformSettingToCache(platformSetting);
				return platformSetting.getValue();
			}
		}
		return value;
	}

	/**
	 * 设置平台设置缓存
	 * @param platformSetting
	 */
	public void setPlatformSettingToCache(PlatformSetting platformSetting){
		if(ObjectUtils.isEmpty(platformSetting)){
			return;
		}
		bladeRedis.hSet(PlatformSettingConstant.cacheKey, platformSetting.getKey(),platformSetting.getValue());
	}
}
