package com.tmerclub.cloud.common.sharding.proxy.payment;

import com.tmerclub.cloud.common.sharding.proxy.ShardingAlgorithmHelper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;

/**
 * 自定义复合分表策略算法
 * @author tmerclub
 * @version 1.0
 */
public class CustomTableComplexKeysShardingAlgorithm implements ComplexKeysShardingAlgorithm<Long> {

    /**
     * 分片键优先级依次为：
     * order_id、user_id、refund_id
     * 维度，订单号、售后单号，他们的三个字段的后三位都是userid后三位
     * <p>
     * 虽然是多字段路由，但最后都是取的userId的后三位
     *
     * @param tableNames 表名
     * @param shardingValue 分片键信息
     * @return 匹配的数据源集合
     */
    @Override
    public Collection<String> doSharding(Collection<String> tableNames,
                                         ComplexKeysShardingValue<Long> shardingValue) {
        Collection<Long> orderIdList = shardingValue.getColumnNameAndShardingValuesMap().get("order_id");
        Collection<Long> payIds = shardingValue.getColumnNameAndShardingValuesMap().get("pay_id");
        Collection<Long> userIds = shardingValue.getColumnNameAndShardingValuesMap().get("user_id");
        Collection<Long> refundIds = shardingValue.getColumnNameAndShardingValuesMap().get("refund_id");

        if (CollectionUtils.isNotEmpty(orderIdList)) {
            return ShardingAlgorithmHelper.getTableNames(tableNames, orderIdList);
        }
        if (CollectionUtils.isNotEmpty(payIds)) {
            return ShardingAlgorithmHelper.getTableNames(tableNames, payIds);
        }

        if (CollectionUtils.isNotEmpty(userIds)) {
            return ShardingAlgorithmHelper.getTableNames(tableNames, userIds);
        }

        if (CollectionUtils.isNotEmpty(refundIds)) {
            return ShardingAlgorithmHelper.getTableNames(tableNames, refundIds);
        }
        return null;
    }



}
