import {
  clubListRespSchema,
  clubRespSchema,
  ordinarySchema,
  uploadAvatarRespSchema,
  userInfoListRespSchema,
  userInfoRespSchema,
} from '@/schemas/response';
import { type ValidationErrorCallback, request } from '.';
import { REQUEST_BASE_URL } from '@/env';
import { ElMessage, type UploadRawFile } from 'element-plus';
export type PagedParams = {
  /** 页码，从1开始 */
  page: number;
  /** 每页数据量 */
  num: number;
};
export async function getUserInfo({
  userID,
  onValidationError,
}: {
  userID?: number;
  onValidationError?: ValidationErrorCallback;
}) {
  let url = '/api/user/info';
  if (userID !== undefined) {
    url += `/${userID}`;
  }
  const resp = await request(userInfoRespSchema, {
    url,
    errorDescription: '获取用户信息失败',
    onValidationError,
  });
  return resp;
}
// #region Avatar
export const getAvatarURL = (avatar: string | undefined) =>
  avatar && `${REQUEST_BASE_URL}/api/avatar/${avatar}`;
export function validateAvatarFile(file: UploadRawFile) {
  if (!file.type.startsWith('image')) {
    ElMessage.error('只能上传图片');
    return false;
  }
  if (file.size > 1024 * 1024) {
    ElMessage.error('文件大小不能超过1MB');
    return false;
  }
  return true;
}
export function uploadAvatar(file: File) {
  const formData = new FormData();
  formData.append('file', file);
  return request(uploadAvatarRespSchema, {
    url: '/api/avatar/upload',
    method: 'post',
    data: formData,
    errorDescription: '上传头像失败',
  });
}
// #endregion
// #region 社团
export const getClubById = (id: number) =>
  request(clubRespSchema, {
    url: `/api/club/${id}`,
    errorDescription: '获取社团信息失败',
  }).then((r) => r?.data);
export const getClubList = (params: PagedParams) =>
  request(clubListRespSchema, {
    url: '/api/club/',
    params: params,
  });
export const changeClubName = (id: number, name: string) =>
  request(ordinarySchema, {
    url: '/api/club/name',
    method: 'put',
    data: { clubId: id, name },
    errorDescription: '修改社团名称失败',
  });
export const changeClubCommit = (id: number, commit: string) =>
  request(ordinarySchema, {
    url: '/api/club/commit',
    method: 'put',
    data: { clubId: id, commit },
    errorDescription: '修改社团简介失败',
  });
export const changeClubAvatar = (id: number, code: string) =>
  request(ordinarySchema, {
    url: '/api/club/avatar',
    method: 'put',
    params: {
      code,
      clubId: id,
    },
    errorDescription: '修改社团头像失败',
  });
export const getUserByClubId = (clubId: number, params: PagedParams) =>
  request(userInfoListRespSchema, {
    url: '/api/club/user/list',
    params: Object.assign(params, { clubId }),
    errorDescription: '获取社团成员列表失败',
  });
export const removeUserFromClub = (userId: number, clubId: number) =>
  request(ordinarySchema, {
    url: '/api/club/user/remove',
    method: 'delete',
    params: {
      userId,
      clubId,
    },
  });
// #endregion
