import axios from 'axios';
import qs from 'query-string';
import type { RouteRecordNormalized } from 'vue-router';
import type { UserState } from '@/store/modules/user/types';
import { encryptWithBase64 } from '@/utils/encrypt';
import type { PaymentRecord } from './sys-user-payment';

export interface LoginData {
  username: string;
  password: string;
  totpCode: string;
  verifyCode: string;
  verifyKey: string;
}

export interface LoginRes {
  token: string;
}

export function login(data: LoginData) {
  data.password = encryptWithBase64(data.password);
  return axios.post<LoginRes>('/api/user/login', data);
}

export function logout() {
  return axios.post<LoginRes>('/api/user/logout');
}

export function getUserInfo() {
  return axios.post<UserState>('/api/user/info');
}

export function getMenuList() {
  return axios.post<RouteRecordNormalized[]>('/api/user/menu');
}

export function getCaptchaAPI() {
  return axios.get<{ key: string; img: string }>('/api/captcha');
}

// 修改密码
export function changePassword(data: {
  oldPassword: string;
  newPassword: string;
  totpCode: string;
}) {
  data = {
    oldPassword: encryptWithBase64(data.oldPassword),
    newPassword: encryptWithBase64(data.newPassword),
    totpCode: data.totpCode
  };
  return axios.put('/api/user/changePwd', data);
}

export interface statisticsRecord {
  appleAccountCount: number;
  payment?: PaymentRecord;
}

export function queryStatistics() {
  return axios.get<statisticsRecord>('/api/sysUser/statistics');
}

// 获取当前账号是否开启了二步验证
export function queryTotpStatus() {
  return axios.get<{
    status: boolean;
    image?: string;
    otpSecret?: string;
    otpKey?: string;
  }>('/api/user/totp/status');
}

// 设置两步验证
export function setTotp(data: {
  code: string;
  password: string;
  otpKey: string;
  otpSecret: string;
}) {
  data.password = encryptWithBase64(data.password);
  return axios.post('/api/user/totp/set', data);
}

// 查看两步验证图像
export function getTotpImage(params: { code: string }) {
  return axios.get<{ image: string }>('/api/user/totp/image', {
    params,
    paramsSerializer: obj => {
      return qs.stringify(obj);
    }
  });
}

// 重置二步验证
export function resetTotp(data: { code: string }) {
  return axios.post('/api/user/totp/reset', data);
}

// 暂停或重启账号
export function pauseOrRestartAccount(data: { id: string }) {
  return axios.put('/api/user/status/pauseOrRestart', data);
}

export type UserSimpleInfo = { id: string; userName: string };

// 获取所有用户列表
export function getAllSimpleUserList() {
  return axios.get<{ list: UserSimpleInfo[] }>('/api/user/getSimpleAll');
}
