package com.gic.haoban.manage.service.dao.mapper.content.holo;

import com.alibaba.hologres.client.HoloClient;
import com.alibaba.hologres.client.HoloConfig;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * @Author MUSI
 * @Date 2023/9/4 4:11 PM
 * @Description
 * @Version
 **/
@Slf4j
@Component
public class HoloDataSource implements InitializingBean, DisposableBean {

    HoloClient client;

    public synchronized void init() {

        try {
            Config appConfig = ConfigService.getAppConfig();
            String holoUrl = appConfig.getProperty("holo.url", "");
            String holoUserName = appConfig.getProperty("holo.username", "");
            String holoPassword = appConfig.getProperty("holo.password", "");
            HoloConfig holoConfig = new HoloConfig();
            holoConfig.setJdbcUrl(holoUrl);
            holoConfig.setUsername(holoUserName);
            holoConfig.setPassword(holoPassword);
            holoConfig.setConnectionMaxIdleMs(13000);
            this.client = new HoloClient(holoConfig);
            this.client.setAsyncCommit(false);
            log.info("holo链接初始化完成");
        }catch (Exception ex) {
            log.info("初始化client 异常 >>>", ex);
        }
    }

    @Override
    public void destroy() throws Exception {
        if (client != null) {
            client.close();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (client == null) {
            this.init();
        }
    }


    public HoloClient getClient() {
        if (this.client == null) {
            this.init();
        }
        return this.client;
    }
}
