// ==========================================================================
// 所属模块：DevGenTableColumns
// 生成日期：2024-02-20 16:41:27 +0800 CST
// 生成路径: apps/system/function.js
// 生成人：xScript_Engine
// 数据表：dm_table_columns - DevGenTableColumns
// ==========================================================================

function select() {
	let value = payload.get().path.split('/').pop();
	let columns = "*";
	if (payload.get().query?.showAll) {
		SQL.cache.remove('system_sql',
			`SELECT * FROM dm_table_columns WHERE table_id = '${value}';`)
		SQL.cache.remove('system_sql',
			`SELECT * FROM dm_tables WHERE table_id = '${value}';`
		)
	} else {
		columns = `column_comment AS columnTitle,dict_type AS dictType,field_name AS fieldName,html_width AS htmlWidth,html_type AS htmlType,is_list AS isList,is_query AS isQuery,sort`;
	}
	const result = SQL.query('system_sql', `SELECT ${columns} FROM dm_table_columns WHERE delete_time IS NULL AND table_id = ?`, value);
	if (result.length) {
		const newResult = result.map((itemR) => {
			const obj = {};
			Object.keys(itemR).forEach((item) => {
				obj[underscoreToCamel(item)] = itemR[item];
			});
			return obj;
		});

		if (newResult) {
			return okMsg(newResult);
		}
	}
	return errMsg(507, '获取失败');
}

function update() {
	const data = payload.get().body?.toObject();
	delete data.createTime;
	delete data.updateTime;
	// 验证data.tableName 和 data.columnName 只能有字母数字下划线
	if (!/^[a-zA-Z0-9_]+$/.test(data.tableName) || !/^[a-zA-Z0-9_]+$/.test(data.columnName) || !/^[a-zA-Z0-9_]+$/.test(data.dbName)) {
		return errMsg(405, '不支持的数据');
	}
	const newData = {};
	Object.keys(data).forEach((item) => {
		newData[camelToUnderscore(item)] = data[item];
	});
	let filter = payload.get().path.split('/').pop();
	const columnsArr = Object.keys(newData);
	let dataArr = [];
	const placeholders = [];
	columnsArr.forEach((item) => {
		if (newData[item]) {
			placeholders.push(`${item} = ?`);
			dataArr.push(newData[item]);
			// 如果在 item是 is_index 字段，并且值为 1，那么将 对应的数据表里面的字段添加到索引里面
			if (item == 'is_index' && newData[item] == 1) {
				const indexSql = `ALTER TABLE ${data.TABLE_NAME} ADD INDEX idx_x_${data.columnName} (${data.columnName})`;
				SQL.push(data.dbName, indexSql);
			}
		} else {
			placeholders.push(`${item} = NULL`);
			// 如果在 item是 is_index 字段，并且值为 0，那么将 对应的数据表里面的字段删除索引
			if (item == 'is_index' && newData[item] == 0) {
				if (t.length > 15 || c.length > 15) {
					return errMsg(413, '数据过长');
				}

				const indexSql = `ALTER TABLE ${data.TABLE_NAME} DROP INDEX idx_x_${data.columnName}`;
				SQL.push(data.dbName, indexSql);
			}
		}
	});
	const newPlaceholders = placeholders.join(',');
	const query = `UPDATE dm_table_columns SET ${newPlaceholders} WHERE column_id = ?`;

	const res = SQL.exec('system_sql', query, ...[...dataArr, filter]);
	if (res) {
		return okMsg(res);
	}
	return errMsg(507, '更新失败');
}

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

	switch (payload.get().method) {
		case 'GET':
			return select();
		case 'PUT':
			return update();
		default:
			response.status.notFound();
			return `404 page not found`;
	}
}

// response.headers.add('X-Script-Version', 'system-gentablecolumns-gen-146')

// var tableId = '2'
// TABLE_NAME = 'dm_table_columns'
// COLUMN_KEY = 'table_id'

// 'use api/dm/sql/sqlBaseCurdByTableId.js'
