package com.njcn.microservice.listener;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;

public class NacosLogbackConfigLoader implements SpringApplicationRunListener, ApplicationListener<ApplicationEnvironmentPreparedEvent>  {

    private final SpringApplication application;
    private final String[] args;

    public NacosLogbackConfigLoader(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
    }

    @Override
    public void starting() {
        // Empty implementation
    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        String active = environment.getProperty("spring.profiles.active");
        if(!"jb".equalsIgnoreCase(active)){




            String serverAddr = environment.getProperty("spring.cloud.nacos.config.server-addr");
            String namespace = environment.getProperty("spring.cloud.nacos.config.namespace");
            String projectName = environment.getProperty("microservice.ename");
            String logLevel = environment.getProperty("logging.level.root");
            String url = String.format("http://%s/nacos/v1/cs/configs?tenant=%s&group=DEFAULT_GROUP&dataId=logback.xml", serverAddr, namespace);
            HttpHeaders headers = new HttpHeaders();
            headers.set("cndl408125hawen", "lanxia201");
            HttpEntity<String> entity = new HttpEntity<>(headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
            if (response.getStatusCode().is2xxSuccessful()) {
                String logbackConfigContent = response.getBody();
                //替换项目名称
                //logbackConfigContent = logbackConfigContent.replace("projectDefaultName",projectName);
               // logbackConfigContent = logbackConfigContent.replace("logDefaultLevel",logLevel);
                // 应用获取到的Logback配置
                applyLogbackConfig(logbackConfigContent,logLevel,projectName);
            }
        }
    }

    private void applyLogbackConfig(String logbackConfigContent,String logLevel,String projectName) {
        LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        // 注意：变量名必须与 XML 中 ${...} 内的名称完全一致
        context.putProperty("log.projectName", projectName != null ? projectName : "undefined_pqs");
        context.putProperty("log.commonLevel", logLevel != null ? logLevel : "INFO");

        try (ByteArrayInputStream inputStream = new ByteArrayInputStream(logbackConfigContent.getBytes(StandardCharsets.UTF_8))) {
            configurator.doConfigure(inputStream);
            Logger root = context.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
            if("debug".equalsIgnoreCase(logLevel)){
                root.setLevel(Level.DEBUG);
            }
            if("info".equalsIgnoreCase(logLevel)){
                root.setLevel(Level.INFO);
            }
            if("error".equalsIgnoreCase(logLevel)){
                root.setLevel(Level.ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        // Empty implementation
    }




}
