package com.ruoyi.framework.config.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.ruoyi.common.utils.SecurityUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Author 吴凯程
 * @Date 2024/12/17
 **/

public class MyTableNameHandler implements TableNameHandler {

    private List<String> tableNames;

    public MyTableNameHandler(String... tableNames) {
        this.tableNames = Arrays.asList(tableNames);
    }


    /**
     * 生成动态表名
     *
     * @param sql       当前执行 SQL
     * @param tableName 表名
     * @return String
     */
    @Override
    public String dynamicTableName(String sql, String tableName) {
        if (tableNames.contains(tableName)) {
            String deptCode = DynamicTableNameHelper.getRequestTable();
            if (Objects.isNull(deptCode)) {
                deptCode = String.valueOf(SecurityUtils.getDeptId()).substring(0, 3);
            }
            DynamicTableNameHelper.remove();
            return tableName + '_' + deptCode;
        }
        return tableName;
    }
}
