package com.usoftchina.uas.office.service;

import com.alibaba.fastjson.JSON;
import com.usoftchina.uas.office.entity.DataCenter;
import com.usoftchina.uas.office.event.DataCenterEvent;
import com.usoftchina.uas.office.event.MasterEvent;
import com.usoftchina.uas.office.jdbc.DataSourceBean;
import com.usoftchina.uas.office.jdbc.DataSourceHolder;
import com.usoftchina.uas.office.jdbc.SchemaUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StreamUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author yingp
 * @date 2020/1/18
 */
@Service
public class SchemaService extends AbstractService {

    private final Logger logger = LoggerFactory.getLogger(SchemaService.class);

    /**
     * 刷新账套下的表结构
     *
     * @param bean
     * @throws IOException
     */
    public void refreshSchema(DataSourceBean bean) throws IOException {
        try {
            DataSourceHolder.set(bean);
            ClassPathResource resource = new ClassPathResource("erp_schema.json");
            String schemaJson = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
            List<SchemaUtils.Table> tableList = JSON.parseArray(schemaJson, SchemaUtils.Table.class);
            if (!CollectionUtils.isEmpty(tableList)) {
                logger.debug("refresh schema for " + bean.username());
                tableList.forEach(table -> table.create(jdbcTemplate));
            }
        } finally {
            DataSourceHolder.clear();
        }
    }

    @EventListener(DataCenterEvent.class)
    public void onDataCenterEvent(DataCenterEvent event) throws Exception {
        refreshSchema(event.getDataCenter());
    }

    @Async
    @EventListener(MasterEvent.class)
    public void onMasterEvent(MasterEvent event) throws Exception {
        if (!event.getMaster().username().equalsIgnoreCase(DataCenter.INSTANCE.username())
                && !event.getMaster().url().equalsIgnoreCase(DataCenter.INSTANCE.url())) {
            refreshSchema(event.getMaster());
        }
    }
}
