/**
 * 用户相关API接口
 */

import request from '@/utils/request.js'
import md5 from '@/utils/md5.js'
import { base64Encode } from '@/utils/base64.js'

/**
 * 用户登录
 * 使用password模式（无需验证码）
 */
export function login(data) {
  // 构建URL参数
  const params = {
    tenantId: '000000',
    username: data.username,
    password: md5(data.password),
    grant_type: 'password',  // 使用password模式
    scope: 'all',
    type: 'account'
  }

  // 转换为URL查询字符串
  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&')

  // 使用saber3客户端凭证
  const basicAuth = 'Basic ' + base64Encode('saber3:saber3_secret')

  return request.post(`/blade-auth/oauth/token?${queryString}`, null, {
    header: {
      'Authorization': basicAuth,
      'Tenant-Id': '000000'
    }
  })
}

/**
 * 用户注册
 */
export function register(data) {
  return request.post('/blade-system/user/register', {
    tenantId: '000000',
    userType: 2, // 2-app
    account: data.account,
    password: md5(data.password),
    phone: data.phone,
    realName: data.realName,
    sex: data.sex,
    code: data.code
  })
}

/**
 * 获取验证码
 */
export function getCaptcha(phone) {
  return request.post('/blade-auth/captcha/send', {
    phone: phone
  })
}

/**
 * 刷新Token
 */
export function refreshToken(refreshToken) {
  return request.post('/blade-auth/oauth/token', {
    tenantId: '000000',
    refresh_token: refreshToken,
    grant_type: 'refresh_token'
  })
}

/**
 * 退出登录
 */
export function logout() {
  return request.post('/blade-auth/logout')
}

export default {
  login,
  register,
  getCaptcha,
  refreshToken,
  logout,

  /**
   * 获取用户信息
   * @returns {Promise}
   */
  getUserInfo() {
    return request.get('/blade-system/user/info')
  },

  /**
   * 修改密码
   * @param {Object} data { oldPassword, newPassword, newPassword1 }
   * @returns {Promise}
   */
  updatePassword(data) {
    return request.post('/blade-system/user/update-password', {
      oldPassword: md5(data.oldPassword),
      newPassword: md5(data.newPassword),
      newPassword1: md5(data.newPassword1)
    })
  },

  /**
   * 修改用户基本信息
   * @param {Object} data 用户信息
   * @returns {Promise}
   */
  updateUserInfo(data) {
    return request.post('/blade-system/user/update', data)
  }
}
