package com.fjhx.utils.wrapperUtil;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.property.PropertyNamer;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;

@SuppressWarnings({"unused"})
@Getter
public class KeywordData {

    private final String sqlFieldName;

    public KeywordData(String sqlFieldName) {
        this.sqlFieldName = sqlFieldName;
    }

    public <K, V> KeywordData(SFunction<K, V> function) {
        this.sqlFieldName = getSqlFieldName(function);
    }

    public <K, V> KeywordData(String alias, SFunction<K, V> function) {
        this.sqlFieldName = alias + "." + getSqlFieldName(function);
    }

    /**
     * 获取sql字段名
     * 例：getSqlFieldName(Entity::getBaseId) -》 return "base_id"
     */
    @SneakyThrows
    private <K, V> String getSqlFieldName(SFunction<K, V> function) {
        Method method = function.getClass().getDeclaredMethod("writeReplace");
        method.setAccessible(true);
        SerializedLambda serializedLambda = (SerializedLambda) method.invoke(function);
        String fieldName = PropertyNamer.methodToProperty(serializedLambda.getImplMethodName());
        return StrUtil.toUnderlineCase(fieldName);
    }

}
