package com.jy.framework.mybatis.join;

import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.StringPool;

import java.util.HashMap;
import java.util.Map;

@SuppressWarnings("unchecked")
public class SqlContext {

    private static final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(HashMap::new);
    private static final String PARAM_NUMBER = "paramNumber";
    private static final String PARAM_MAP = "paramMap";

    public static void init(Map<String, Object> paramMap) {
        Map<String, Object> map = threadLocal.get();
        map.put(PARAM_NUMBER, 1);
        map.put(PARAM_MAP, paramMap);
        threadLocal.set(map);
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static String formatValue(Object value) {
        if (value instanceof AbstractSql sqlFormat) {
            return sqlFormat.format();
        }

        String paramKey = getParamKey();
        getParamMap().put(paramKey, value);
        return StringPool.HASH_LEFT_BRACE + paramKey + StringPool.RIGHT_BRACE;
    }

    public static String getTableDelFlag(String tableName) {
        TableInfo tableInfo = TableInfoHelper.getTableInfo(tableName);
        TableFieldInfo logicDeleteFieldInfo = tableInfo.getLogicDeleteFieldInfo();

        if (logicDeleteFieldInfo == null) {
            return null;
        }
        return logicDeleteFieldInfo.getColumn();
    }

    private static String getParamKey() {
        Map<String, Object> map = threadLocal.get();
        int paramNumber = (int) map.get(PARAM_NUMBER);
        map.put(PARAM_NUMBER, paramNumber + 1);
        return SqlConstant.SQL_PARAM + paramNumber;
    }

    private static Map<String, Object> getParamMap() {
        Map<String, Object> map = threadLocal.get();
        return (Map<String, Object>) map.get(PARAM_MAP);
    }

}
