import axios from 'axios'
import Message from '@huntianning/components/packages/message'

let instance = null

function captureBusinessError(error) {
  if (error && error.data && error.data.status === 'FAIL') {
    const message = error.data.data || error.data.message || '未知异常'
    Message.error(message)
  }
  return Promise.reject(error)
}

export const init = (options) => {
  options = Object.assign({
    baseURL: null,
    withCredentials: true,
    requestInterceptor: null,
    responseInterceptor: null
  }, options)
  instance = axios.create(options)

  instance.interceptors.request.use(config => {
    if (options.requestInterceptor) {
      return options.requestInterceptor(config)
    }
    return config
  }, error => {
    return Promise.reject(error)
  })

  instance.interceptors.response.use(response => {
    if (options.responseInterceptor) {
      return options.responseInterceptor(response)
    }
    return response
  }, error => {
    let message = '未知错误'
    if (error.response) {
      if (error.response.status === 404) {
        message = '服务未找到'
      } else if (error.response.status === 500) {
        message = '服务异常'
      } else if (error.response.status === 401) {
        message = '登录失效'
      }
    }
    Message.error(message)
    return Promise.reject(error)
  })
}

export function post(url, data, opts) {
  if (!instance) {
    throw new Error('[Request] 使用前请先执行init方法初始化')
  }
  return instance.post(url, data, opts).then(null, captureBusinessError)
}

export function get(url, params) {
  if (!instance) {
    throw new Error('[Request] 使用前请先执行init方法初始化')
  }
  return instance.get(url, {
    params
  }).then(null, captureBusinessError)
}

export function del(url, params) {
  if (!instance) {
    throw new Error('[Request] 使用前请先执行init方法初始化')
  }
  return instance.delete(url, {
    params
  }).then(null, captureBusinessError)
}

export function put(url, data) {
  if (!instance) {
    throw new Error('[Request] 使用前请先执行init方法初始化')
  }
  return instance.put(url, data).then(null, captureBusinessError)
}

/**
 * 从服务器请求登录用户数据
*/
export function mockGetLoginUser(username) {
  return post('/system/user/sendSmsCode', {
    username,
    type: 'HTN'
  }).then(code => {
    return post(`/auth/login?code=${code}&type=HTN&username=${username}`)
  })
}
