import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Users, UsersParam } from './model';
import { MODULES_API_URL } from '@/config/setting';

/**
 * 分页查询用户
 */
export async function pageUsers(params: UsersParam) {
  const res = await request.get<ApiResult<PageResult<Users>>>(
    MODULES_API_URL + '/shop/users/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询用户列表
 */
export async function listUsers(params?: UsersParam) {
  const res = await request.get<ApiResult<Users[]>>(
    MODULES_API_URL + '/shop/users',
    {
      params
    }
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加用户
 */
export async function addUsers(data: Users) {
  const res = await request.post<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/users',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改用户
 */
export async function updateUsers(data: Users) {
  const res = await request.put<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/users',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除用户
 */
export async function removeUsers(id?: number) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/users/' + id
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除用户
 */
export async function removeBatchUsers(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    MODULES_API_URL + '/shop/users/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 根据id查询用户
 */
export async function getUsers(id: number) {
  const res = await request.get<ApiResult<Users>>(
    MODULES_API_URL + '/shop/users/' + id
  );
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}
