package com.jy.framework.mybatis.join;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.ibatis.reflection.property.PropertyNamer;

public class QueryColumn extends AbstractQueryColumn {

    /**
     * 表别名
     */
    protected final String tableAlias;

    /**
     * 字段
     */
    protected final String field;

    public QueryColumn(String field) {
        this.tableAlias = StringPool.EMPTY;
        this.field = field;
    }

    public QueryColumn(String tableAlias, String field) {
        this.tableAlias = tableAlias;
        this.field = field;
    }

    public <T> QueryColumn(SFunction<T, ?> function) {
        this.tableAlias = StringPool.EMPTY;
        LambdaMeta meta = LambdaUtils.extract(function);
        this.field = StrUtil.toUnderlineCase(PropertyNamer.methodToProperty(meta.getImplMethodName()));
    }

    public <T> QueryColumn(String tableAlias, SFunction<T, ?> function) {
        this.tableAlias = tableAlias;
        LambdaMeta meta = LambdaUtils.extract(function);
        this.field = StrUtil.toUnderlineCase(PropertyNamer.methodToProperty(meta.getImplMethodName()));
    }

    @Override
    protected QueryColumn copy() {
        return new QueryColumn(this.tableAlias, this.field);
    }

    @Override
    protected String format() {
        String sql = StrUtil.isBlank(tableAlias) ? field : tableAlias + StringPool.DOT + field;
        return spliceCompute(sql);
    }

}
