package com.yeejoin.amos.knowledgebase.face.util.sql;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.*;

/**
 * 查询条件块
 */
class SqlBlock extends BaseSqlCondition {

    private List<BaseSqlCondition> conditions;

    SqlBlock(Map<String, Object> resourceMap) {
        super(resourceMap);
        this.conditions = new ArrayList<>();
        Object children = resourceMap.get("children");
        if (children instanceof List) {
            try {
                ((List<Map<String, Object>>) children).forEach(map -> this.conditions.add(BaseSqlCondition.getInstance(map)));
            } catch (ClassCastException e) {
                throw new RuntimeException("条件格式错误");
            }
        } else {
            throw new RuntimeException("条件格式错误");
        }
    }

    @Override
    <T> void composeWrapper(QueryWrapper<T> queryWrapper, String logic) {
        switch (logic) {
            case "or":
                queryWrapper.or(this::composeChild);
                break;
            case "and":
            default:
                queryWrapper.and(this::composeChild);
                break;
        }
    }

    @Override
    boolean validate() {
        return conditions != null && !conditions.isEmpty();
    }

    @Override
    public Set<String> getTagSeqs() {
        Set<String> set = new HashSet<>();
        conditions.forEach(condition -> set.addAll(condition.getTagSeqs()));
        return set;
    }

    @Override
    public int getTotalStatement() {
        return conditions.stream().mapToInt(BaseSqlCondition::getTotalStatement).sum();
    }

    private <T> void composeChild(QueryWrapper<T> wrapper) {
        final String[] nextLogic = {"and"};
        conditions.forEach(condition -> {
            condition.composeWrapper(wrapper, nextLogic[0]);
            nextLogic[0] = condition.getLogic();
        });
    }

}
