/**
 * author 赵越
 * 2018-11-04
 */

import axios from 'axios'
import Vue from 'vue'

/**
 *
 * @param {string} path 请求地址的 path
 * @param {string} data 请求实体
 * @param {object} payload 其他选项
 * @param {object} promise 返回一个 promise
 */
const get = async (path, data, payload) => {
  let result = await request('get', path, data, payload)
  return result
}

/**
 *
 * @param {string} path 请求地址的 path
 * @param {string} data 请求实体
 * @param {object} payload 其他选项
 * @param {object} promise 返回一个 promise
 */
const post = async (path, data = {}, payload) => {
  let formData = ''
  for(const key in data) {
    if(data.hasOwnProperty(key)) {
      const element = data[key]
      if(element || element === 0) formData += `${key}=${element}&`
    }
  }
  formData = formData.slice(0, formData.length - 1)

  let result = await request('post', path, formData, { config: { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } } })

  return result
}

/**
 *
 * @param {method} method 请求方法
 * @param {string} path 请求地址的 path
 * @param {string} data 请求实体
 * @param {object} payload 其他选项
 * @param {object} promise 返回一个 promise
 */
const request = async (method, path, data, payload = {}) => {
  let host = ''
  let url = host + path
  const body = {
    url,
    data,
    method,
    params: data,
  }
  if(payload.config) Object.assign(body, payload.config, { params: '' })

  // console.log(`url: ${url}`)
  consoleFormat({ body })

  const res = await axios.request(body)
  let rData = res.data
  if(typeof rData !== 'object') rData = JSON.parse(rData)
  // consoleFormat({ rData })
  if(rData.status === 1) return rData
  else if(rData.status === -99) {
    location.href = '/login'
    return
  } else {
    Vue.prototype.$message.error(rData.info)
    rData.status = 0
    return rData
  }
}

const consoleFormat = obj => {
  const key = Object.keys(obj)[0]
  // console.log(key + ':')
  // console.dir(obj[key])
  // console.log()
}

Vue.prototype.$get = get
Vue.prototype.$post = post
Vue.prototype.$request = request