//package com.jwipc.sharding;
//
//import cn.hutool.extra.spring.SpringUtil;
//import com.google.common.collect.Sets;
//import com.jwipc.sharding.mapper.DataShardingMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;
//import org.apache.shardingsphere.infra.instance.metadata.InstanceType;
//import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
//import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
//import org.apache.shardingsphere.mode.manager.ContextManager;
//import org.apache.shardingsphere.mode.manager.listener.ContextManagerLifecycleListener;
//import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
//import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
//
//import java.util.Collection;
//import java.util.LinkedList;
//import java.util.Set;
//import java.util.concurrent.CompletableFuture;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
//import java.util.stream.Collectors;
//
///**
// * <p> </p>
// *
// * @author ZhangJie
// * @version 1.0
// * @since JDK 1.8
// */
//@Slf4j
//public class ContextmanagerListener implements ContextManagerLifecycleListener {
//    @Override
//    public void onInitialized(String s, ContextManager contextManager) {
//        //需要增加异步延迟操作
//        CompletableFuture.runAsync(() -> {
//            try {
//                //需要工厂配置的逻辑
//                Set<String> factoryTable = Sets.newHashSet("t_product_info", "t_purchase_order_detail");
//                log.info("进入监听器:databaseName:{},延迟前", s);
//                while (!AppStarted.started) {
//                    Thread.sleep(1000); // 模拟延迟操作
//                }
//                log.info("进入监听器:databaseName:{},延迟后", s);
//                final DataShardingMapper shardingMapper = SpringUtil.getBean(DataShardingMapper.class);
//                ShardingSphereMetaData shardingSphereMetaData = contextManager
//                        .getMetaDataContexts()
//                        .getMetaData();
//                Collection<RuleConfiguration> newRuleConfigList = new LinkedList<>();
//                final Collection<ShardingSphereRule> logicDb = shardingSphereMetaData.getDatabase("logic_db")
//                        .getRuleMetaData()
//                        .getRules();
//                for (ShardingSphereRule shardingSphereRule : logicDb) {
//                    final RuleConfiguration oldRuleConfig = shardingSphereRule.getConfiguration();
//                    if (oldRuleConfig instanceof ShardingRuleConfiguration) {
//                        // Algorithm provided sharding rule configuration
//                        ShardingRuleConfiguration oldAlgorithmConfig = (ShardingRuleConfiguration) oldRuleConfig;
//                        ShardingRuleConfiguration newAlgorithmConfig = new ShardingRuleConfiguration();
//                        // Sharding table rule configuration Collection
//                        Collection<ShardingTableRuleConfiguration> newTableRuleConfigList = new LinkedList<>();
//                        Collection<ShardingTableRuleConfiguration> oldTableRuleConfigList =
//                                oldAlgorithmConfig.getTables();
//                        oldTableRuleConfigList.forEach(oldTableRuleConfig -> {
//                            if (factoryTable.contains(oldTableRuleConfig.getLogicTable())) {
//                                String newActualDataNodes = oldTableRuleConfig.getActualDataNodes();
//                                Set<String> tt = Sets.newHashSet();
//                                //需要取出表数据是工厂的，规则是工厂是数字编码
//                                final Set<String> factoryCodes = shardingMapper.getFactoryCodes(
//                                        oldTableRuleConfig.getLogicTable() + "%");
//                                for (String str : factoryCodes) {
//                                    Pattern pattern = Pattern.compile("\\d+");
//                                    Matcher matcher = pattern.matcher(str);
//                                    if (matcher.find()) {
//                                        String numberStr = matcher.group();
//                                        int number = Integer.parseInt(numberStr);
//                                        tt.add(newActualDataNodes + "_" + number);
//                                    }
//                                }
//                                log.info("{}", tt.stream().collect(Collectors.joining(",")));
//                                ShardingTableRuleConfiguration newTableRuleConfig = new ShardingTableRuleConfiguration(
//                                        oldTableRuleConfig.getLogicTable(),
//                                        tt.stream().collect(Collectors.joining(",")));
//                                newTableRuleConfig.setTableShardingStrategy(
//                                        oldTableRuleConfig.getTableShardingStrategy());
//                                newTableRuleConfig.setDatabaseShardingStrategy(
//                                        oldTableRuleConfig.getDatabaseShardingStrategy());
//                                newTableRuleConfig.setKeyGenerateStrategy(oldTableRuleConfig.getKeyGenerateStrategy());
//                                newTableRuleConfigList.add(newTableRuleConfig);
//                            } else {
//                                newTableRuleConfigList.add(oldTableRuleConfig);
//                            }
//                        });
//                        newAlgorithmConfig.setTables(newTableRuleConfigList);
//                        newAlgorithmConfig.setAutoTables(oldAlgorithmConfig.getAutoTables());
//                        newAlgorithmConfig.setBindingTableGroups(oldAlgorithmConfig.getBindingTableGroups());
//                        newAlgorithmConfig.setDefaultDatabaseShardingStrategy(
//                                oldAlgorithmConfig.getDefaultDatabaseShardingStrategy());
//                        newAlgorithmConfig.setDefaultTableShardingStrategy(
//                                oldAlgorithmConfig.getDefaultTableShardingStrategy());
//                        newAlgorithmConfig.setDefaultKeyGenerateStrategy(
//                                oldAlgorithmConfig.getDefaultKeyGenerateStrategy());
//                        newAlgorithmConfig.setDefaultShardingColumn(oldAlgorithmConfig.getDefaultShardingColumn());
//                        newAlgorithmConfig.setShardingAlgorithms(oldAlgorithmConfig.getShardingAlgorithms());
//                        newAlgorithmConfig.setKeyGenerators(oldAlgorithmConfig.getKeyGenerators());
//
//                        newRuleConfigList.add(newAlgorithmConfig);
//                    } else {
//                        newRuleConfigList.add(oldRuleConfig);
//                    }
//                }
//                // update context
//                contextManager.getConfigurationContextManager().alterRuleConfiguration(s, newRuleConfigList);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//        });
//
//    }
//
//    @Override
//    public void onDestroyed(String s, InstanceType instanceType) {
//
//    }
//}
