package cc.smtweb.framework.core.mvc.service;

import cc.smtweb.framework.core.common.R;
import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.common.SwMap;
import cc.smtweb.framework.core.db.DbEngine;
import cc.smtweb.framework.core.db.cache.ModelTableCache;
import cc.smtweb.framework.core.db.impl.DefaultEntity;
import cc.smtweb.framework.core.db.vo.ModelField;
import cc.smtweb.framework.core.db.vo.ModelTable;
import cc.smtweb.framework.core.exception.BizException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by Akmm at 2022/3/2 19:52
 * 默认实体实现
 */
public class DefaultComboHandler<T extends DefaultEntity> extends DefaultListHandler<T> {

    public DefaultComboHandler(String tableName) {
        super(tableName);
    }

    public R filter() {
        return R.success(filterData());
    }

    protected SwListData filterData() {
        String text = params.readString("text");
        if (StringUtils.isEmpty(text)) throw new BizException("没有搜素内容！");

        SqlPara sqlPara = buildDataSql();
        String sort = params.readString("sort");
        String order = params.readString("order");

        StringBuilder sqlFilter = new StringBuilder();
        List<Object> args = new ArrayList<>(sqlPara.paras.length);
        Collections.addAll(args, sqlPara.paras);

        buildFilterCondition(text, sqlFilter, args);
        if (sqlFilter.length() == 0) throw new BizException("没有待搜索的字段！");

        String sql = "select ar.* from (" + sqlPara.sql + ") ar where " + sqlFilter.substring(4);
        if (StringUtils.isNotEmpty(sort)) {
            sql += " order by ar." + sort + " " + order;
            if (StringUtils.isNotEmpty(getPkFieldName())) {
                sql += "," + getPkFieldName();
            }
        }

        List<SwMap> listData = DbEngine.getInstance().pagedQuery(sql, SwMap.class, 0, 10, args.toArray());
        afterQuery(listData);
        return SwListData.create(listData, 0);
    }

    //搜索条件
    protected void buildFilterCondition(String text, StringBuilder sqlFilter, List<Object> args) {
        List<String> fields = new ArrayList<>();
        getFilterFields(fields);
        if (fields.isEmpty()) return;

        text = text + "%";//combo不支持全模糊
        for (String field : fields) {
            sqlFilter.append(" or " + field + " like ?");
            args.add(text);
        }

    }

    //构建参与搜索的字段，默认为code和name字段
    protected void getFilterFields(List<String> fields) {
        ModelTable table = ModelTableCache.getInstance().getByName(tableName);
        ModelField field = table.findFieldByType(SwEnum.FieldType.CODE.value);
        if (field != null) fields.add(field.getName());

        field = table.findFieldByType(SwEnum.FieldType.NAME.value);
        if (field != null) fields.add(field.getName());
    }
}
