package com.usoftchina.uas.office.service;

import com.usoftchina.uas.office.context.ContextHolder;
import com.usoftchina.uas.office.entity.DataCenter;
import com.usoftchina.uas.office.event.DataCenterEvent;
import com.usoftchina.uas.office.jdbc.DynamicDataSourceRegister;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author yingp
 * @date 2020/1/15
 */
@Service
public class DataCenterService extends AbstractService {

    @Autowired
    private DynamicDataSourceRegister dynamicDataSourceRegister;

    @Cacheable("DataCenter")
    public DataCenter find() {
        return queryForBean("select * from DataCenter", DataCenter.class);
    }

    @CacheEvict("DataCenter")
    public void save(DataCenter dataCenter) throws Exception {
        if (null != dataCenter.getOuterUrl()) {
            if (!dataCenter.getOuterUrl().endsWith("/")) {
                dataCenter.setOuterUrl(dataCenter.getOuterUrl() + "/");
            }
        }
        jdbcTemplate.update("update DataCenter set url=?,username=?,password=?,driverClassName=?,outerUrl=?",
                dataCenter.getUrl(), dataCenter.getUsername(), dataCenter.getPassword(), dataCenter.getDriverClassName(), dataCenter.getOuterUrl());
        dynamicDataSourceRegister.unregister(dataCenter);
        if (null != dataCenter.getUsername() && null != dataCenter.getPassword() && null != dataCenter.getUrl()) {
            dynamicDataSourceRegister.register(dataCenter);
            ContextHolder.getApplicationContext().publishEvent(new DataCenterEvent(this, dataCenter));
        }
        DataCenter.INSTANCE = dataCenter;
    }

    @Async
    @EventListener(ContextRefreshedEvent.class)
    public void onApplicationRefreshedEvent(ContextRefreshedEvent event) throws Exception {
        DataCenter dataCenter = find();
        if (null == dataCenter) {
            jdbcTemplate.update("insert into DataCenter(id,driverClassName,url,password) values (1,'oracle.jdbc.OracleDriver','jdbc:oracle:thin:@127.0.0.1:1521:orcl','select!#%*(')");
            dataCenter = find();
        } else {
            if (null != dataCenter.getUsername() && null != dataCenter.getPassword() && null != dataCenter.getUrl()) {
                dynamicDataSourceRegister.register(dataCenter);
                ContextHolder.getApplicationContext().publishEvent(new DataCenterEvent(this, dataCenter));
            }
        }
        DataCenter.INSTANCE = dataCenter;
    }
}
