package com.xhpc.order.config;

import com.xhpc.common.redis.service.RedisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 启动后加载缓存的组件
 *
 * @author yuyang
 * @Date 2026-05-19 10:34
 */
@Component
@Order(1)
public class ThresholdCacheLoader implements CommandLineRunner {
    private static final Logger logger = LoggerFactory.getLogger(ThresholdCacheLoader.class);

    private static final String CACHE_KEY_CHECK_THRESHOLD = "charging:check:threshold";

    @Autowired
    private RedisService redisService;

    @Autowired
    private ChargingCheckConfig chargingCheckConfig;

    @Override
    public void run(String... args) throws Exception {
        loadThresholdFromCache();
    }

    /**
     * 从Redis缓存加载阈值配置
     */
    public void loadThresholdFromCache() {
        logger.info("开始从缓存加载充电校验阈值配置...");

        try {
            Map<String, Object> thresholdMap = redisService.getCacheMap(CACHE_KEY_CHECK_THRESHOLD);

            if (thresholdMap != null && !thresholdMap.isEmpty()) {
                Integer cachedNumberThreshold = null;
                Integer cachedSocThreshold = null;
                Integer cachedOrderPower = null;
                Integer cachedVoltageThreshold = null;
                Integer cachedCurrentThreshold = null;

                if (thresholdMap.containsKey("numberThreshold")) {
                    cachedNumberThreshold = Integer.parseInt(thresholdMap.get("numberThreshold").toString());
                }
                if (thresholdMap.containsKey("socThreshold")) {
                    cachedSocThreshold = Integer.parseInt(thresholdMap.get("socThreshold").toString());
                }
                if (thresholdMap.containsKey("orderPower")) {
                    cachedOrderPower = Integer.parseInt(thresholdMap.get("orderPower").toString());
                }
                if (thresholdMap.containsKey("voltageThreshold")) {
                    cachedVoltageThreshold = Integer.parseInt(thresholdMap.get("voltageThreshold").toString());
                }
                if (thresholdMap.containsKey("currentThreshold")) {
                    cachedCurrentThreshold = Integer.parseInt(thresholdMap.get("currentThreshold").toString());
                }

                chargingCheckConfig.loadFromCache(cachedNumberThreshold, cachedSocThreshold,
                        cachedOrderPower, cachedVoltageThreshold, cachedCurrentThreshold);
                logger.info("从缓存加载充电校验阈值成功");
            } else {
                logger.info("缓存中无充电校验阈值配置，使用配置文件默认值");
                // 将默认值存入缓存
                saveThresholdToCache();
            }
        } catch (Exception e) {
            logger.error("从缓存加载充电校验阈值失败，使用配置文件默认值", e);
        }
    }

    /**
     * 保存当前阈值到Redis缓存
     */
    public void saveThresholdToCache() {
        try {
            Map<String, Object> thresholdMap = new java.util.HashMap<>();
            thresholdMap.put("numberThreshold", chargingCheckConfig.getNumberThreshold());
            thresholdMap.put("socThreshold", chargingCheckConfig.getSocThreshold());
            thresholdMap.put("orderPower", chargingCheckConfig.getOrderPower());
            thresholdMap.put("voltageThreshold", chargingCheckConfig.getVoltageThreshold());
            thresholdMap.put("currentThreshold", chargingCheckConfig.getCurrentThreshold());
            thresholdMap.put("updateTime", new java.util.Date().toString());

            redisService.setCacheMap(CACHE_KEY_CHECK_THRESHOLD, thresholdMap);
            logger.info("保存充电校验阈值到缓存成功");
        } catch (Exception e) {
            logger.error("保存充电校验阈值到缓存失败", e);
        }
    }

    /**
     * 刷新缓存中的阈值配置（同时更新内存）
     */
    public void refreshCache() {
        logger.info("刷新充电校验阈值缓存...");
        saveThresholdToCache();
        // 重新从缓存加载
        loadThresholdFromCache();
    }

    /**
     * 清除缓存中的阈值配置
     */
    public void clearCache() {
        try {
            redisService.deleteObject(CACHE_KEY_CHECK_THRESHOLD);
            logger.info("清除充电校验阈值缓存成功");
        } catch (Exception e) {
            logger.error("清除充电校验阈值缓存失败", e);
        }
    }
}
