import request from '@/utils/request';
import { setToken } from '@/utils/token-util';
import type { ApiResult } from '@/api';
import type {
  LoginParam,
  LoginResult,
  CaptchaResult,
  SmsCaptchaResult
} from './model';

/**
 * 登录
 */
export async function login(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>('/login', data);
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取验证码
 */
export async function getCaptcha() {
  const res = await request.get<ApiResult<CaptchaResult>>('/captcha');
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 发送短信验证码
 */
export async function sendSmsCaptcha(data: LoginParam) {
  const res = await request.post<ApiResult<SmsCaptchaResult>>(
    '/sendSmsCaptcha',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 登录
 */
export async function remoteLogin(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    'https://open.gxwebsoft.com/api/login',
    data
  );
  if (res.data.code === 0) {
    setToken(res.data.data?.access_token, data.remember);
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 获取企业微信登录链接
 */
export async function getWxWorkQrConnect(data) {
  const res = await request.post<ApiResult<unknown>>('/open/wx-work', data);
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}
