// 创建数据表的信息
//
'use api/core/runtime/database/sql/tables.js';
'use api/lib/camelAndUnderscore.js';

// 根据sql列类型获取html类型
function getHtmlTypeFromColumnType(columnType) {
	// const ColumnTypeStr = ['char', 'varchar', 'narchar', 'varchar2', 'tinytext', 'text', 'mediumtext', 'longtext']; // to "input";
	const ColumnTypeTime = ['datetime', 'time', 'date', 'timestamp', 'timestamptz']; // to "datetime";
	// const ColumnTypeNumber = [
	// 	'smallint',
	// 	'mediumint',
	// 	'int',
	// 	'int2',
	// 	'int4',
	// 	'int8',
	// 	'number',
	// 	'integer',
	// 	'numeric',
	// 	'bigint',
	// 	'float',
	// 	'float4',
	// 	'float8',
	// 	'double',
	// 	'decimal',
	// ]; // to "input";
	const ColumnTypeBool = ['tinyint', 'bool', 'boolean']; // to "switch";
	const dataType = columnType.toLowerCase();
	if (ColumnTypeTime.includes(dataType)) {
		return 'datetime';
	} else if (ColumnTypeBool.includes(dataType)) {
		return 'switch';
	} else {
		return 'input';
	}
}

function main() {
	// 验证用户权限
	'use api/user/acl/excerpt.js'

	let data = payload.get().body?.toObject();
	if (data.db) {
		DB_NAME = data.db;
	}
	TABLE_NAME = data.tables;

	let dbInfo = SQL.query('system_sql', 'SELECT * FROM sys_database WHERE name = ?;', DB_NAME);
	if (!dbInfo.length) {
		return errMsg(507, '数据库不存在');
	}
	dbInfo = dbInfo[0];

	// TABLE_NAME 可能由多个组成，采用, 分割
	let tables = TABLE_NAME.split(',');
	tables.forEach((table) => {
		let pkColumn = '';

		let tableInfo = getTableInfo();
		let tableCollums = getTableCollums();

		tableCollums.forEach((pk) => {
			// pk_column 是取Key为PKI的Field值
			if (pk.Key == 'PRI') {
				pkColumn = pk.Field;
				return pkColumn;
			}
		});

		let moduleName = table.replace('_', '-');
		let businessName = moduleName.replace(/^.*?-/, '');
		let packageName = capitalizeFirstLetter(underscoreToCamel(table));

		let stmt =
			'INSERT INTO dm_tables (db_id, db_name, db_comment, table_id, table_name, table_comment, class_name, module_name, business_name, function_name, function_author, pk_column,  pk_field_name, proprietor_id, proprietor_name) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';

		const tableId = ex.suid().base58()

		let res = SQL.exec(
			'system_sql',
			stmt,
			dbInfo.db_id,
			dbInfo.name,
			dbInfo.comment,
			tableId,
			table,
			tableInfo[0]['TABLE_COMMENT'],
			packageName,
			moduleName,
			businessName,
			capitalizeFirstLetter(businessName),
			USER_INFO.username + '-' + USER_INFO.nickname,
			pkColumn,
			underscoreToCamel(pkColumn),
			USER_INFO.user_id,
			USER_INFO.nickname,
		);

		if (!res) {
			return errMsg(507, '创建表信息失败');
		}

		// let fieldName = underscoreToCamel(col.Field);
		const temp = [];
		for (let i = 0; i < tableCollums.length; i++) {
			let col = tableCollums[i];
			let stmt =
				'INSERT INTO dm_table_columns (column_id, table_id, sort, table_name, column_name, column_comment, column_type, column_key, field_name, is_pk, is_required, is_increment, html_type, proprietor_id, proprietor_name) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);';
			//           							         tid, 	sort,  tname    , cname,       ccomment,	      ctype,      ckey,    	  jfield,   ispk,   isrequired,      isinc,     htype      oid,     own
			let params = [
				ex.suid().base58(),
				tableId,
				i + 1,
				TABLE_NAME,
				col.Field,
				col.Comment,
				col.Type,
				col.Key,
				underscoreToCamel(col.Field),
				col.Key == 'PKI' ? 1 : 0,
				col.Null == 'NO' ? 1 : 0,
				col.Extra.includes('auto_increment') ? 1 : 0,
				getHtmlTypeFromColumnType(col.Type),
				USER_INFO.user_id,
				USER_INFO.nickname,
			];
			SQL.push('system_sql', stmt, ...params);
			temp.push(params);
		}
	});


	return okMsg('创建表信息成功');
}
