package com.sundot.airport.framework.config;

import com.sundot.airport.common.utils.GeometricMeanUtils;
import com.sundot.airport.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;

/**
 * 绩效参数配置初始化
 *
 * @author wangxx
 * @date 2026-03-16
 */
@Component
public class PerformanceConfigInitializer {

    @Autowired
    private ISysConfigService configService;

    /**
     * 应用启动时初始化绩效参数配置
     */
    @PostConstruct
    public void init() {
        try {
            // 从数据库读取配置
            String paramAStr = configService.selectConfigByKey("item.performance.matrix.param_a");
            String paramBStr = configService.selectConfigByKey("item.performance.matrix.param_b");
            String paramCStr = configService.selectConfigByKey("item.performance.matrix.param_c");

            // 解析参数值，如果不存在则使用默认值
            double paramA = parseParam(paramAStr, 3.0);
            double paramB = parseParam(paramBStr, 5.0);
            double paramC = parseParam(paramCStr, 2.0);

            // 设置到 GeometricMeanUtils
            GeometricMeanUtils.setParams(paramA, paramB, paramC);
        } catch (Exception e) {
            // 使用默认值
            GeometricMeanUtils.setParams(3.0, 5.0, 2.0);
        }
    }

    /**
     * 解析参数值
     *
     * @param value        配置值
     * @param defaultValue 默认值
     * @return 解析后的 double 值
     */
    private double parseParam(String value, double defaultValue) {
        if (value == null || value.isEmpty()) {
            return defaultValue;
        }

        try {
            return new BigDecimal(value).doubleValue();
        } catch (Exception e) {
            return defaultValue;
        }
    }

}
