import request from "@/utils/request";

// 登录（平台端 / 使用租户名称）
export function login(data) {
  return request({
    url: `/platform/login`,
    method: "post",
    data,
  });
}

/** 当前登录用户信息（含角色名称），需携带 token */
export function getCurrentUser() {
  return request({
    url: `/platform/currentUser`,
    method: "get",
  });
}

// 发送登录验证码（手机号）
export function sendLoginCode(data) {
  return request({
    url: "/platform/sendLoginCode",
    method: "post",
    data,
  });
}

// 手机号验证码登录
export function loginBySms(data) {
  return request({
    url: "/platform/loginBySms",
    method: "post",
    data,
  });
}
// 登出
export function logout(userInfo = null) {
  // 如果没有传入 userInfo，尝试从 localStorage 获取
  if (!userInfo) {
    const cachedUserInfo = localStorage.getItem('userInfo');
    if (cachedUserInfo) {
      try {
        userInfo = JSON.parse(cachedUserInfo);
      } catch (e) {
        console.error('Failed to parse userInfo from localStorage:', e);
      }
    }
  }
  
  return request({
    url: `/platform/logout`,
    method: "post",
    data: userInfo ? { userInfo: userInfo } : {},
  });
}

/**
 * 获取极验3.0数据
 * @returns {Promise}
 */
export function getGeetest3Infos() {
  return request({
    url: '/platform/login/getGeetest3Infos',
    method: 'get'
  });
}

/**
 * 获取极验4.0数据
 * @returns {Promise}
 */
export function getGeetest4Infos() {
  return request({
    url: '/platform/login/getGeetest4Infos',
    method: 'get'
  });
}

/**
 * 判断是否开启验证
 * @returns {Promise}
 */
export function getOpenVerify() {
  return request({
    url: '/platform/login/getOpenVerify',
    method: 'get'
  });
}

// 忘记密码重置
export function resetPassword(data) {
  return request({
    url: "/platform/resetPassword",
    method: "post",
    data,
  });
}

// 发送找回密码验证码
export function sendResetCode(data) {
  return request({
    url: "/platform/sendResetCode",
    method: "post",
    data,
  });
}

// 租户端自助注册（/backend/*，与 go-platform routers/backend 一致）
export function register(data) {
  return request({
    url: "/backend/register",
    method: "post",
    data,
  });
}

export function sendRegisterCode(data) {
  return request({
    url: "/backend/sendRegisterCode",
    method: "post",
    data,
  });
}