import axios from 'axios'
import { ElMessage } from 'element-plus'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const webssoService = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: '',
  // 超时
  timeout: 30000
})
// request拦截器
webssoService.interceptors.request.use(
  config => {
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              let params = propName + '[' + key + ']'
              var subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// 响应拦截器
webssoService.interceptors.response.use(
  res => {
    console.log('返回参数：：', res)
    return Promise.resolve(res.data)
  },
  error => {
    console.log('err::' + error)
    ElMessage({ message: '无法获取用户信息，请确认代理程序是否启动', type: 'error' })
    return Promise.reject(error)
  }
)

// 获取clientHello 同步负责监测 ueky 是否拔出
export function getClientHello(password) {
  return webssoService({
    url: 'http://127.0.0.1:8899/client_hello',
    method: 'post',
    data: { userName: 'key', userPwd: password }
  })
}

// 生成客户验证码
export function getClientAuth(password, serverHello, clientHello) {
  return webssoService({
    url: 'http://127.0.0.1:8899/client_auth',
    method: 'post',
    data: { userName: 'key', userPwd: password, serverHello, clientHello }
  })
}
