package cn.quantgroup.customer.config.container;

import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * 在此填写类的用途，注意事项
 *
 * @author xiaoshuai.ma
 * @date 2022-02-18 2:29 下午
 */
@Component
@Slf4j
public class ApolloConfigListener implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    RefreshScope refreshScope;

    @ApolloConfigChangeListener(value = {"application"})
    public void configChange(ConfigChangeEvent event) {
        Set<String> changedKeys = event.changedKeys();
        for (String changedKey : changedKeys) {
            log.info("changed key = {}",changedKey);
            log.info("oldValue={},newValue= {}",event.getChange(changedKey).getOldValue(),event.getChange(changedKey).getNewValue());
            this.applicationContext.publishEvent(new EnvironmentChangeEvent(event.changedKeys()));
            refreshScope.refreshAll();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
