package com.elab.core.spring.method;

import com.alibaba.druid.sql.SQLUtils;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.elab.core.dao.model.JdbcParamsModel;
import com.elab.core.exception.CoreException;

import java.util.List;

/**
 * 默认的SQL检验执行
 *
 * @author Liukx
 * @create 2018-02-05 17:37
 * @email liukx@elab-plus.com
 **/
public class DefaultCheckSQLProcess implements CheckSqlProcess {

    private final String whereName = "where";

    private final String updateType = "update";

    private final String insertType = "insert";

    private final String deleteType = "delete";

    @Override
    public void checkProcess(JdbcParamsModel model, Object o) throws Exception {

        String sql = model.getSql();

//        if (o == null && isUpdate(sql) && isUpdate(sql)) {
//            throw new CoreException(" 当前SQL执行,参数不能为null ");
//        }
        // List<SQLStatement> mysql = SQLUtils.parseStatements(model.getSql(), "mysql");
        if (sql.toLowerCase().indexOf(whereName) < 0) {
            throw new CoreException("where条件后面必须有一个参数以上");
        }

    }

    /**
     * 是否是修改类型的SQL
     *
     * @param sql
     * @return
     */
    private boolean isUpdate(String sql) {
        return sql.toLowerCase().trim().startsWith(updateType);
    }

    private boolean isDelete(String sql) {
        return sql.toLowerCase().trim().startsWith(deleteType);
    }

    /**
     * 是否是添加类型的SQL
     *
     * @param sql
     * @return
     */
    private boolean isInsert(String sql) {
        return sql.toLowerCase().startsWith(insertType);
    }

    public static void main(String[] args) {
        String sql = "update c_user_info set updated = ?,\n" +
                "mobile_time = ?, source = ? and brand_id = ? and user_id = ?";

    }
}
