package org.springblade.sqlfly.opt;

import java.util.List;
import java.util.Map;

import org.springblade.sqlfly.config.Column;
import org.springblade.sqlfly.config.Table;
import org.springblade.sqlfly.type.JavaType;
import org.springblade.sqlfly.type.MysqlType;

import com.alibaba.fastjson2.JSON;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;

/**
 * mysql数据库操作
 * 
 * @author William
 * @date 2022年10月28日 上午11:29:54
 */
public class FlyMysql extends IFly {

	protected FlyMysql() {
	}

	@Override
	public List<Table> getTableList(String schema) {
		String sql = "select table_name, table_comment, create_time, update_time from information_schema.tables where table_schema = (select database())";
		List<Map<String, Object>> retList = fly.getMapList(sql);
		String json = JSON.toJSONString(retList);
		List<Table> list = JSONUtil.toList(json, Table.class);
		return list;
	}

	public Table getTable(String schema, String tableName) {
		String sql = "select table_name, table_comment, create_time, update_time from information_schema.tables where table_schema = (select database()) and table_name = '"
				+ tableName + "'";
		Map<String, Object> ret = fly.getMap(sql);
		String json = JSON.toJSONString(ret);
		Table table = JSONUtil.toBean(json, Table.class);
		return table;
	}

	@Override
	public List<Column> getColumnList(String tableName) {
		String sql = "select column_name, data_type, column_comment, is_nullable, extra from information_schema.columns where table_name = '"
				+ tableName + "' and table_schema = (select database()) order by ordinal_position";
		List<Map<String, Object>> retList = fly.getMapList(sql);
		String json = JSON.toJSONString(retList);
		List<Column> columns = JSONUtil.toList(json, Column.class);
		JavaType javaType = new MysqlType();
		columns.forEach(col -> {
			col.setJavaType(javaType.get(col.getDataType()));
		});
		findPrimaryKey(tableName, columns);
		return columns;
	}

	private void findPrimaryKey(String tableName, List<Column> list) {
		String primaryColumn = "";
		String sql = "describe " + tableName;
		List<Map<String, Object>> retList = fly.getMapList(sql);
		if (retList == null || retList.isEmpty()) {
			return;
		}

		for (Map<String, Object> map : retList) {
			if (map.get("Key") != null && map.get("Key").toString().equalsIgnoreCase("PRI")) {
				primaryColumn = map.get("Field").toString();
				break;
			}

			if (map.get("COLUMN_KEY") != null && map.get("COLUMN_KEY").toString().equalsIgnoreCase("PRI")) {
				primaryColumn = map.get("COLUMN_NAME").toString();
				break;
			}
		}
		if (StrUtil.isNotBlank(primaryColumn)) {
			// 有主键
			for (Column col : list) {
				if (col.getColumnName().equalsIgnoreCase(primaryColumn)) {
					col.setPrimaryKey(true);
					col.setIsNullable("NO");
					break;
				}
			}
		}
	}

}
