/**
 * KRA - User API Service
 */
import request from '@/utils/request';

export interface LoginParams {
  username: string;
  password: string;
  captcha: string;
  captchaId: string;
}

export interface LoginResult {
  user: any;
  token: string;
}

export interface CaptchaResult {
  captchaId: string;
  picPath: string;
  captchaLength: number;
  openCaptcha: boolean;
}

/** 用户登录 */
export const login = (data: LoginParams) => {
  return request.post<ApiResponse<LoginResult>>('/base/login', data);
};

/** 获取验证码 */
export const captcha = () => {
  return request.post<ApiResponse<CaptchaResult>>('/base/captcha');
};

/** 用户注册 */
export const register = (data: any) => {
  return request.post<ApiResponse<any>>('/user/admin_register', data);
};

/** 修改密码 */
export const changePassword = (data: { password: string; newPassword: string }) => {
  return request.post<ApiResponse<any>>('/user/changePassword', data);
};

/** 获取用户列表 */
export const getUserList = (data: PageParams) => {
  return request.post<ApiResponse<PageResult<any>>>('/user/getUserList', data);
};

/** 设置用户权限 */
export const setUserAuthority = (data: { uuid: string; authorityId: string | number }) => {
  return request.post<ApiResponse<any>>('/user/setUserAuthority', {
    ...data,
    authorityId: Number(data.authorityId),
  });
};

/** 删除用户 */
export const deleteUser = (data: { id: number }) => {
  return request.delete<ApiResponse<any>>('/user/deleteUser', { data });
};

/** 设置用户信息 */
export const setUserInfo = (data: any) => {
  return request.put<ApiResponse<any>>('/user/setUserInfo', data);
};

/** 设置自身信息 */
export const setSelfInfo = (data: any) => {
  return request.put<ApiResponse<any>>('/user/setSelfInfo', data);
};

/** 设置自身界面配置 */
export const setSelfSetting = (data: any) => {
  return request.put<ApiResponse<any>>('/user/setSelfSetting', data);
};

/** 设置用户多角色权限 */
export const setUserAuthorities = (data: { ID: number; authorityIds: (number | string)[] }) => {
  return request.post<ApiResponse<any>>('/user/setUserAuthorities', {
    ...data,
    authorityIds: data.authorityIds.map(id => Number(id)),
  });
};

/** 获取用户信息 */
export const getUserInfo = () => {
  return request.get<ApiResponse<{ userInfo: any }>>('/user/getUserInfo');
};

/** 重置密码 */
export const resetPassword = (data: { ID: number; password?: string }) => {
  return request.post<ApiResponse<any>>('/user/resetPassword', data);
};

export default {
  login,
  captcha,
  register,
  changePassword,
  getUserList,
  setUserAuthority,
  deleteUser,
  setUserInfo,
  setSelfInfo,
  setSelfSetting,
  setUserAuthorities,
  getUserInfo,
  resetPassword,
};
