package org.xyzh.message.config;

import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.StringUtils;
import org.xyzh.api.system.service.SysConfigService;

import java.util.Properties;

/**
 * @description 动态配置加载器 - 从数据库加载邮件和短信配置
 * @filename DynamicConfigLoader.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-12-05
 */
@Configuration
@Order(100)  // 确保在其他组件初始化之后再加载配置
public class DynamicConfigLoader implements ApplicationRunner {
    
    private static final Logger logger = LoggerFactory.getLogger(DynamicConfigLoader.class);
    
    @DubboReference(version = "1.0.0", group = "system", timeout = 5000, check = false, retries = 0)
    private SysConfigService sysConfigService;
    
    @Autowired(required = false)
    private JavaMailSenderImpl mailSender;
    
    @Autowired(required = false)
    private EmailConfigProperties emailConfigProperties;
    
    @Autowired(required = false)
    private SmsConfigProperties smsConfigProperties;
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("=== 开始加载动态配置 ===");
        
        try {
            // 加载邮件配置
            if (emailConfigProperties != null) {
                loadEmailConfig();
            } else {
                logger.warn("EmailConfigProperties未注入，跳过邮件配置加载");
            }
            
            // 加载短信配置
            if (smsConfigProperties != null) {
                loadSmsConfig();
            } else {
                logger.warn("SmsConfigProperties未注入，跳过短信配置加载");
            }
            
            logger.info("=== 动态配置加载完成 ===");
        } catch (Exception e) {
            logger.error("动态配置加载失败", e);
        }
    }
    
    /**
     * 加载邮件配置
     */
    private void loadEmailConfig() {
        try {
            if (sysConfigService == null) {
                logger.warn("SysConfigService未注入，无法加载邮件配置");
                return;
            }
            
            String host = sysConfigService.getStringConfig("email.host");
            String port = sysConfigService.getStringConfig("email.port");
            String username = sysConfigService.getStringConfig("email.username");
            String password = sysConfigService.getStringConfig("email.password");
            String fromName = sysConfigService.getStringConfig("email.fromName");
            String sslEnable = sysConfigService.getStringConfig("email.ssl.enable");
            String timeout = sysConfigService.getStringConfig("email.timeout");
            
            // 更新配置属性
            emailConfigProperties.setHost(host);
            emailConfigProperties.setPort(StringUtils.hasText(port) ? Integer.valueOf(port) : 587);
            emailConfigProperties.setUsername(username);
            emailConfigProperties.setPassword(password);
            emailConfigProperties.setFromName(fromName);
            emailConfigProperties.setSslEnable("true".equalsIgnoreCase(sslEnable));
            emailConfigProperties.setTimeout(StringUtils.hasText(timeout) ? Integer.valueOf(timeout) : 30000);
            
            // 如果邮箱配置完整，则配置JavaMailSender
            if (mailSender != null && StringUtils.hasText(host) && StringUtils.hasText(username) && StringUtils.hasText(password)) {
                mailSender.setHost(host);
                mailSender.setPort(emailConfigProperties.getPort());
                mailSender.setUsername(username);
                mailSender.setPassword(password);
                
                // 设置邮件属性
                Properties props = mailSender.getJavaMailProperties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", emailConfigProperties.getSslEnable() ? "true" : "false");
                props.put("mail.smtp.starttls.required", emailConfigProperties.getSslEnable() ? "true" : "false");
                props.put("mail.smtp.timeout", emailConfigProperties.getTimeout());
                props.put("mail.smtp.connectiontimeout", emailConfigProperties.getTimeout());
                
                logger.info("邮件配置加载成功: host={}, port={}, username={}", host, emailConfigProperties.getPort(), username);
            } else {
                logger.warn("邮件配置不完整，将使用默认配置或模拟模式");
            }
            
        } catch (Exception e) {
            logger.error("加载邮件配置失败", e);
        }
    }
    
    /**
     * 加载短信配置
     */
    private void loadSmsConfig() {
        try {
            if (sysConfigService == null) {
                logger.warn("SysConfigService未注入，无法加载短信配置");
                return;
            }
            
            String provider = sysConfigService.getStringConfig("sms.provider");
            String accessKeyId = sysConfigService.getStringConfig("sms.accessKeyId");
            String accessKeySecret = sysConfigService.getStringConfig("sms.accessKeySecret");
            String signName = sysConfigService.getStringConfig("sms.signName");
            String templateCodeLogin = sysConfigService.getStringConfig("sms.templateCode.login");
            String templateCodeRegister = sysConfigService.getStringConfig("sms.templateCode.register");
            String timeout = sysConfigService.getStringConfig("sms.timeout");
            
            // 更新配置属性
            smsConfigProperties.setProvider(StringUtils.hasText(provider) ? provider : "aliyun");
            smsConfigProperties.setAccessKeyId(accessKeyId);
            smsConfigProperties.setAccessKeySecret(accessKeySecret);
            smsConfigProperties.setSignName(StringUtils.hasText(signName) ? signName : "校园新闻");
            smsConfigProperties.setTemplateCodeLogin(templateCodeLogin);
            smsConfigProperties.setTemplateCodeRegister(templateCodeRegister);
            smsConfigProperties.setTimeout(StringUtils.hasText(timeout) ? Integer.valueOf(timeout) : 30000);
            
            if (StringUtils.hasText(accessKeyId) && StringUtils.hasText(accessKeySecret)) {
                logger.info("短信配置加载成功: provider={}, signName={}", smsConfigProperties.getProvider(), smsConfigProperties.getSignName());
            } else {
                logger.warn("短信配置不完整，将使用模拟模式");
            }
            
        } catch (Exception e) {
            logger.error("加载短信配置失败", e);
        }
    }
}
