// ==========================================================================
// 所属模块：SysUsers
// 生成日期：2024-03-24 16:10:31 +0800 CST
// 生成路径: /system/users/users/function.js
// 生成人：xScript_Engine
// 数据表：sys_users - 用户表(系统账户列表使用)
// ==========================================================================

TABLE_NAME = 'sys_users';
COLUMN_KEY = 'user_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 == 'nickname') {
			placeholders.push(`nickname LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		} else if (item == 'phone') {
			placeholders.push(`phone LIKE ?`);
			tempParams.push('%' + condition[item] + '%');
		} else if (item == 'status') {
			placeholders.push(`status = ?`);
			tempParams.push(condition[item]);
		} else if (item == 'organizationId') {
			placeholders.push(`organization_id = ?`);
			tempParams.push(condition[item]);
		}
	});

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

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

	const data = payload.get().query;
	if (!Object.keys(data).length) {
		// 根据id查询详情
		var useParent = scriptPath != payload.get().path.substring(1);
		if (useParent) {
			let value = payload.get().path.split('/').pop();
			const result = SQL.query(
				'system_sql',
				`SELECT user_id,nickname,phone,role_id,role_key,role_name,email,organization_id,organization_name,post_id,post_name,remark,status,username,autograph,last_login_ip,last_login_time FROM ${TABLE_NAME} WHERE delete_time IS NULL AND ${COLUMN_KEY} = ?`,
				value
			);
			// 获取岗位和角色
			// const posts = SQL.query('system_sql', 'SELECT * FROM oa_posts WHERE delete_time IS NULL');
			const roles = SQL.query('system_sql', 'SELECT * FROM sys_roles WHERE delete_time IS NULL');
			if (result.length) {
				return okMsg({ data: result[0], roles });
			}
			return errMsg(507, '获取失败');
		}
	}

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

	// 总数据
	const COUNT_TOTAL = countTotal(newData);
	const total = SQL.query('system_sql', COUNT_TOTAL.query, ...COUNT_TOTAL.params);
	// 分页数据
	const LIST_DATA = selectData(newData);
	const result = SQL.query('system_sql', LIST_DATA.query, ...LIST_DATA.params);
	return okMsg({ data: result, total: total[0].count, pageNum: Number(newData.pageNum), pageSize: Number(newData.pageSize) });
}



function insert() {
	const data = payload.get().body?.toObject();
	const newData = {};
	console.log("crypto.bcrypt", crypto.bcrypt)
	Object.keys(data).forEach((item) => {
		if (camelToUnderscore(item) == 'password') {
			newData[camelToUnderscore(item)] = crypto.bcrypt.encrypt(data[item]);
		} else {
			newData[camelToUnderscore(item)] = data[item];
		}
	});
	const columnsArr = Object.keys(newData);
	let dataArr = Object.values(newData);
	const placeholders = [];

	columnsArr.push(COLUMN_KEY)
	columnsArr.push('proprietor_id')
	columnsArr.push('proprietor_name')

	dataArr.push(ex.suid().base58())
	dataArr.push(USER_INFO.user_id)
	dataArr.push(USER_INFO.nickname)

	dataArr.forEach(() => {
		placeholders.push('?');
	});
	placeholders.join(',');

	const columnsStr = columnsArr.join(',');
	const query = `INSERT INTO ${TABLE_NAME} (${columnsStr}) VALUES (${placeholders})`;
	const res = SQL.exec('system_sql', query, ...dataArr);

	if (res) {
		return okMsg(res);
	}
	return errMsg(507, '添加失败');
}


function main() {
	'use api/user/acl/excerpt.js'

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