// ==========================================================================
// 数据表：sys_organizations - 系统接口数据
// ==========================================================================

TABLE_NAME = 'sys_organizations';
COLUMN_KEY = 'organization_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 == 'organizationName') {
			placeholders.push(`organization_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_organizations WHERE ${newPlaceholders} AND delete_time IS NULL ORDER BY sort ASC`,
			params: [...tempParams],
		};
	} else {
		return {
			query: `SELECT * FROM sys_organizations 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 = formatOrgData(newResult);
	return okMsg(formatRes);
}


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

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`;
	}
}
