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

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.EntityDao;
import cc.smtweb.framework.core.db.EntityHelper;
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 org.apache.commons.lang3.StringUtils;

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

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

    public DefaultListHandler(String tableName) {
        this.tableName = tableName;
    }

    @Override
    protected SqlPara buildSqlPara() {
        EntityDao dao = DbEngine.getInstance().findDao(tableName);
        StringBuilder sql = new StringBuilder(512);
        List<Object> args = new ArrayList<>();
        dao.handleSelect(sql, null);

        StringBuilder sqlCondition = new StringBuilder(128);
        buildCondition(sqlCondition, args);
        String filter = sqlCondition.toString().trim();
        if (StringUtils.isNotEmpty(filter)) {
            if (filter.startsWith("or ")) {
                sql.append("\nwhere ").append(filter.substring(3));
            } else if (filter.startsWith("and ")) {
                sql.append("\nwhere ").append(filter.substring(4));
            } else if (!filter.startsWith("where ")) {
                sql.append("\nwhere ").append(filter);
            } else {
                sql.append(filter);
            }
        }

        buildOrder(sql);

        return new SqlPara(sql.toString(), args.toArray());
    }

    protected void buildCondition(StringBuilder sql, List<Object> args) {
    }

    protected void buildOrder(StringBuilder sql) {
        ModelTable table = ModelTableCache.getInstance().getByName(tableName);
        if (table == null) return;
        sql.append(" order by ");

        ModelField field = table.findFieldByType(SwEnum.FieldType.CODE.value);
        if (field != null) sql.append(field.getName()).append(",");
        sql.append(table.getIdField());
    }

    @Override
    protected void afterQuery(List<SwMap> listData) {
        super.afterQuery(listData);
        EntityHelper.loadBeanText(tableName, listData, null);
    }
}
