package <%=packageName%>.anltr;

import <%=packageName%>.service.CommonConditionQueryService;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
<%_ if (ormTool !== 'mybatis') { _%>
import org.springframework.data.jpa.domain.Specification;
<%_ } else { _%>
import com.baomidou.mybatisplus.core.conditions.segments.MergeSegments;
import com.baomidou.mybatisplus.core.enums.SqlKeyword;
<%_ } _%>
<%_
    const expressType = ormTool !== 'mybatis' ? 'Specification' : 'MergeSegments';
_%>

public class CriteriaLogicExprListener extends LogicExprBaseListener {

    public ParseTreeProperty<<%= expressType%>> specifications = new ParseTreeProperty<>();

    @Override
    public void exitOr(LogicExprParser.OrContext ctx) {
        <%= expressType%> left = specifications.get(ctx.expr(0));
        <%= expressType%> right = specifications.get(ctx.expr(1));
        if (left != null && right != null) {
            <%_ if (ormTool !== 'mybatis') { _%>
            specifications.put(ctx, left.or(right));
            <%_ } else { _%>
            left.add(SqlKeyword.OR);
            left.add(right);
            specifications.put(ctx, left);
            <%_ } _%>
        }
        super.exitOr(ctx);
    }

    @Override
    public void exitStat(LogicExprParser.StatContext ctx) {
        specifications.put(ctx, specifications.get(ctx.expr()));
        super.exitStat(ctx);
    }

    @Override
    public void exitVar(LogicExprParser.VarContext ctx) {
        // 获得表达式指定的specification
        specifications.put(ctx, (<%= expressType%>) CommonConditionQueryService.specificationMap.get(ctx.VAR().getText()));
        super.exitVar(ctx);
    }

    @Override
    public void exitAnd(LogicExprParser.AndContext ctx) {
        <%= expressType%> left = specifications.get(ctx.expr(0));
        <%= expressType%> right = specifications.get(ctx.expr(1));
        if (left != null && right != null) {
            <%_ if (ormTool !== 'mybatis') { _%>
            specifications.put(ctx, left.and(right));
            <%_ } else { _%>
            left.add(SqlKeyword.AND);
            left.add(right);
            specifications.put(ctx, left);
            <%_ } _%>
        }
        super.exitAnd(ctx);
    }

    @Override
    public void exitGroup(LogicExprParser.GroupContext ctx) {
        specifications.put(ctx, specifications.get(ctx.expr()));
        super.exitGroup(ctx);
    }

}
