// ==========================================================================
// 所属模块：Uploads
// 生成日期：2024-02-08 17:09:21 +0800 CST
// 生成路径: uploads/function.js
// 生成人：xScript_Engine
// 数据表：sys_files - 文件上传
// ==========================================================================

response.headers.add('X-Script-Version', 'uploads-1.0');

function upload() {
	const params = payload.get().query;
	const file_id = ex.suid().base58();
	let file_path = '/uploads/' + file_id;
	let upload_result
	if (!params.signature) {
		return errMsg(400, '缺少参数');
	}
	const sql = `SELECT * FROM sys_files WHERE file_hash =? LIMIT 1;`;
	let res = SQL.query('system_sql', sql, params.signature);
	if (res.length > 0) {
		res = res[0]
		let file_name = payload.get().path.split('/').pop()
		file_path = res.file_path;

		upload_result = {
			name: file_name,
			type: res.file_type,
			size: res.file_size,
		};
	}
	else {
		upload_result = response.upload(rootPath + file_path);
		upload_result.new = true;
	}

	if (upload_result.name) {
		const sql = `INSERT INTO sys_files (file_id, file_name, file_path, file_type, file_size, file_hash, proprietor_id, proprietor_name, privacy,is_folder,parent_id) VALUES (?, ?, ?, ? , ? , ?, ?, ?, ?, ?, ?);`;
		SQL.exec(
			'system_sql',
			sql,
			file_id,
			upload_result.name,
			file_path,
			upload_result.type,
			upload_result.size,
			params.signature,
			USER_INFO.user_id,
			USER_INFO.nickname,
			params.privacy ? params.privacy : 0,
			params.isFolder ? params.isFolder : 0,
			params.parentId ? params.parentId : 0
		);

		// 		if (upload_result.new) {
		// 			return ''
		// 		}
		return okMsg({ id: file_id, name: upload_result.name, type: upload_result.type, size: upload_result.size })
	}
	return errMsg(507, '上传失败');
}

function info() {
	const fileId = payload.get().query.fileId;
	const res = SQL.query('system_sql', `SELECT * FROM sys_files WHERE delete_time IS NULL AND file_id = ?;`, fileId);

	return JSON.stringify({
		filePath: res[0].file_path,
		fileType: res[0].file_type,
		fileSize: res[0].file_size,
	});
}

function del() {
	const fileId = payload.get().query.fileId;
	const file_path = rootPath + '/uploads/' + fileId;
	// 数据库更新
	const res = SQL.exec('system_sql', `UPDATE sys_files SET delete_time = NOW() WHERE file_id =?`, fileId);
	if (res) {
		return okMsg(res);
	}

	return errMsg(507, '删除失败');
}

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

	switch (payload.get().method) {
		case 'POST':
			return upload();
		case 'DELETE':
			return del();
		default:
			response.status.notFound();
			return `404 page not found`;
	}
}
