package com.hotent.base.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.hotent.base.datasource.DatabaseContext;
import com.hotent.base.query.QueryField;
import com.hotent.base.query.QueryFilter;
import com.hotent.base.query.QueryOP;

/**
 * SQl的帮助类
 *
 * @company 广州宏天软件股份有限公司
 * @author heyifan
 * @email heyf@jee-soft.cn
 * @date 2020年4月16日
 */
public class SQLUtil {

	/**
	 * 根据数据库连接的URL，取得数据库类型
	 * @param url
	 * @return
	 */
	public static String getDbTypeByUrl(String url) {
		return JdbcUtils.getDbType(url).getDb();
	}

	/**
	 * 取得当前数据源的数据库类型
	 * @return
	 */
	public static String getDbType() {
		return getDbTypeObj().getDb();
	}

	public static DbType getDbTypeObj() {
		DatabaseContext databaseContext = AppUtil.getBean(DatabaseContext.class);
		return databaseContext.getDbTypeObj();
	}
	/**
	 * 是否含有sql注入
	 * @param sql sql语句
	 * @return true:含有，false:含有
	 */
	public static boolean containsSqlInjection(String sql) {
		if(StringUtil.isEmpty(sql)){
			return false;
		}
		Pattern pattern = Pattern.compile("\\b(insert|drop|grant|alter|delete|update|truncate|show)\\b");
		Matcher matcher = pattern.matcher(sql.toLowerCase());
		return matcher.find();
	}
	/**
	 * 将数据库字段为CLOB的数据转成String
	 * @param clob
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public static String ClobToString(Clob clob) throws SQLException, IOException {
		String ret = "";
		Reader read= clob.getCharacterStream();
		BufferedReader br = new BufferedReader(read);
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (s != null) {
			sb.append(s);
			s = br.readLine();
		}
		ret = sb.toString();
		if(br != null){
			br.close();
		}
		if(read != null){
			read.close();
		}
		return ret;
	}

	/**
	 * 把带有BETWEEN查询的时间由String转为时间戳
	 * @param queryFilter
	 */
	public static void StringToTimestamp(QueryFilter queryFilter){
		List<QueryField> querys = queryFilter.getQuerys();
		for (QueryField query : querys) {
			if (query.getOperation().equals(QueryOP.BETWEEN)&& List.class.isInstance(query.getValue())){
				List<Object> objects = new ArrayList<>();
				for (String v : (List<String>)query.getValue()){
					objects.add(Timestamp.valueOf(v));
				}
				query.setValue(objects);
			}
		}
	}
}
