import request from '/@/utils/request';

export function fetchPage(query?: Object) {
	return request({
		url: '/admin/tenant/page',
		method: 'get',
		params: query,
	});
}

export function fetchList(query?: object) {
	return request({
		url: '/admin/tenant/list',
		method: 'get',
		params: query,
	});
}

// 获取个人租户信息
export function getPersonalTenant() {
	return request({
		url: '/admin/tenant/user-tenant',
		method: 'get',
	});
}

export function addObj(obj?: Object) {
	return request({
		url: '/admin/tenant',
		method: 'post',
		data: obj,
	});
}

export function getObj(id?: string) {
	return request({
		url: '/admin/tenant/details/' + id,
		method: 'get',
	});
}

export function getObjDetails(obj?: object) {
	return request({
		url: '/admin/tenant/details',
		method: 'get',
		params: obj,
	});
}

export function delObj(ids?: Object) {
	return request({
		url: '/admin/tenant',
		method: 'delete',
		data: ids,
	});
}

export function putObj(obj?: Object) {
	return request({
		url: '/admin/tenant',
		method: 'put',
		data: obj,
	});
}

export function validateTenantName(rule: any, value: any, callback: any, isEdit: boolean) {
	if (isEdit) {
		return callback();
	}

	getObjDetails({ name: value }).then((response) => {
		const result = response.data;
		if (result !== null) {
			callback(new Error('租户名称已经存在'));
		} else {
			callback();
		}
	});
}

export function validateTenantCode(rule: any, value: any, callback: any, isEdit: boolean) {
	if (isEdit) {
		return callback();
	}

	getObjDetails({ code: value }).then((response) => {
		const result = response.data;
		if (result !== null) {
			callback(new Error('租户编码已经存在'));
		} else {
			callback();
		}
	});
}

export function treemenu() {
	return request({
		url: '/admin/tenant/tree/menu',
		method: 'get',
	});
}

// 获取租户用户列表（分页）
export function fetchUserPage(query?: Object) {
	return request({
		url: '/admin/tenant/user-tenant/page',
		method: 'get',
		params: query,
	});
}

// 从租户中移除用户
export function removeUsersFromTenant(data: { tenantId: string; userIds: string[] }) {
	return request({
		url: '/admin/tenant/remove-users',
		method: 'delete',
		data,
	});
}

// 邀请用户到租户
export function inviteUserToTenant(data: { tenantId: string; userIds: string[]; roleId: string; postId?: string; deptId?: string }) {
	return request({
		url: '/admin/tenant/user-tenant',
		method: 'post',
		data,
	});
}

// 获取可邀请的用户列表
export function getAvailableUsers(params: { tenantId?: string; username?: string }) {
	return request({
		url: '/admin/tenant/list-users',
		method: 'get',
		params,
	});
}

// 获取租户角色列表
export function getTenantOrg(params?: { tenantId?: string }) {
	return request({
		url: '/admin/tenant/list-org',
		method: 'get',
		params,
	});
}

// 切换个人租户
export function switchPersonalTenant(tenantId: string) {
	return request({
		url: '/admin/tenant/personal/update',
		method: 'put',
		data: { tenantId },
	});
}