// ==========================================================================
// 数据表：sys_menus - 系统菜单
// ==========================================================================

TABLE_NAME = 'sys_menus';
COLUMN_KEY = 'menu_id';
TABLE_FIELDS = '*';

'use api/lib/sql.js';

function getPlaceholders(condition) {
	const columnsArr = Object.keys(condition);
	const placeholders = [];
	const tempParams = [];
	columnsArr.forEach((item) => {
		if (item == 'menuName') {
			placeholders.push(`menu_name LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		} else if (item == 'status') {
			placeholders.push(`status = ?`);
			tempParams.push(condition[item]);
		}
	});

	return {
		placeholders: placeholders.join(' AND '),
		tempParams: tempParams,
	};
}

function selectData(condition) {
	const newPlaceholders = getPlaceholders(condition).placeholders;
	if (newPlaceholders) {
		const tempParams = getPlaceholders(condition).tempParams;
		return {
			query: `SELECT * FROM sys_menus WHERE ${newPlaceholders} AND delete_time IS NULL ORDER BY sort ASC`,
			params: [...tempParams],
		};
	} else {
		return {
			query: `SELECT * FROM sys_menus WHERE delete_time IS NULL ORDER BY sort ASC`,
			params: [],
		};
	}
}

function list() {
	const data = payload.get().query;
	// 格式化这个query参数
	let newData = {};
	Object.keys(data).forEach((item) => {
		newData[item] = data[item][0];
	});

	const LIST_DATA = selectData(newData);
	const result = SQL.query(DB_NAME, LIST_DATA.query, ...LIST_DATA.params);
	// 格式化数据
	const newResult = result.map((itemO) => {
		const newObj = {};
		Object.keys(itemO).forEach((item) => {
			newObj[underscoreToCamel(item)] = itemO[item];
		});
		return {
			...newObj,
			parentId: newObj.parentId == 0 ? null : newObj.parentId
		};
	});
	const formatRes = formatMenuData(newResult);
	return okMsg(formatRes);
}

function formatMenuData(data, parentId = null) {
	return data
		.filter((item) => item.parentId == parentId)
		.map((item) => ({
			...item,
			children: formatMenuData(data, item.menuId),
		}));
}

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

	switch (payload.get().method) {
		case 'GET':
			return list();
		case 'PUT':
			return sql_update();
		case 'POST':
			return sql_insert();
		case 'DELETE':
			return sql_delete();
		default:
			response.status.notFound();
			return `404 page not found`;
	}
}
