package com.jay.monitor.data.server.store.mysql;

import com.jay.monitor.data.server.config.props.MonitorProperties;
import com.jay.monitor.data.server.enums.DataSplitType;
import com.jay.monitor.data.server.enums.StoreType;
import com.jay.monitor.data.server.factory.DataIdFactory;
import com.jay.monitor.data.server.store.AbstractSplitDataProcess;
import com.jay.monitor.data.server.utils.MonitorPropertiesUtil;
import com.jay.monitor.data.server.utils.SqlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Map;

/**
 * @Module 数据拆分
 * @Description Mysql数据拆分
 * @Author liukaixiong
 * @Date 2020/11/5 15:47
 */
@Component
public class MysqlDDLProcess extends AbstractSplitDataProcess {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DataSource dataSource;

    @Autowired
    private DataIdFactory dataIdFactory;

    @Autowired
    private MonitorProperties monitorProperties;

    @Override
    public void splitDataInvoke(DataSplitType splitData) {

        String currentId = dataIdFactory.getCurrentId(splitData);

        if (currentId == null) {
            logger.warn("得不到当前编号 -> " + splitData);
            return;
        }

        Map<String, DataSplitType> tableRule = MonitorPropertiesUtil.getMysqlTableRuleMap(monitorProperties);

        if (tableRule == null) {
            logger.info("MYSQL 找不到对应的数据拆分规则");
            return;
        }

        // 遍历配置文件中的表，并根据当前的编号修改，去规则中进行匹配，然后创建
        tableRule.forEach((tableName, V) -> {
            if (V == splitData) {
                try {
                    String newTableName = getNewTableName(tableName, currentId);
                    SqlUtils.createTable(dataSource.getConnection(), getNewTableName(tableName, currentId), tableName);
                    logger.info("根据数据拆分规则:" + splitData + " 创建存储表名称: " + newTableName + " 参考表:" + tableName);
                } catch (Exception e) {
                    logger.error("获取链接失败", e);
                }
            }
        });
    }

    @Override
    public String getDataId(String tableName, DataSplitType dataSplitType) {
        String currentId = dataIdFactory.getCurrentId(dataSplitType);
        return currentId;
    }

    protected String getNewTableName(String tableName, String id) {
        return tableName + "_" + id;
    }

    @Override
    public StoreType storeType() {
        return StoreType.MYSQL;
    }

}
