package com.jy.framework.mybatis.join;

import cn.hutool.core.lang.Assert;
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 lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.reflection.property.PropertyNamer;

@RequiredArgsConstructor(access = AccessLevel.PROTECTED)
public class TempTable extends AbstractTable {

    private final String alias;
    private final Sql<?> sql;

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

    public QueryColumn field(String field) {
        Assert.notBlank(field, "temp table field must be not blank");
        return new QueryColumn(alias, field);
    }

    @Override
    protected String format() {
        return StringPool.LEFT_BRACKET + sql.format() + StringPool.RIGHT_BRACKET + StringPool.SPACE + alias;
    }

}
