import axios from 'axios'
import {MessageBox, Message} from 'element-ui'
import store from '@/store'
import {getToken} from '@/utils/auth'
import {aesEncrypt_HmacSha256} from './encryption/utils.js'
import * as queryString from 'query-string'
import moment from 'moment'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 600000 // request timeout
})

function typeOf(obj) {
  const toString = Object.prototype.toString
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object Blob]': 'blob'
  }
  return map[toString.call(obj)]
}

const key = 's#e@5f98H*^his%t'
// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = getToken()
    }
    var paramsObject = ''
    if (config.method === 'get' || config.method === 'delete') {
      paramsObject = Object.assign({}, config.params)
    } else if (config.method === 'post' || config.method === 'put') {
      paramsObject = Object.assign({}, config.data)
      JSONToString(paramsObject)
    }
    if (config.url === 'system/user/profile/updatePwd') {
      paramsObject = Object.assign({}, config.params)
      JSONToString(paramsObject)
    }

    function JSONToString(paramsObject) {
      Object.keys(paramsObject).forEach(key => {
        var item = paramsObject[key]
        if (item === null || item === undefined) {
          paramsObject[key] = ''
        }
        if (typeOf(item) === 'object' || typeOf(item) === 'array') {
          paramsObject[key] = JSON.stringify(item)
        }
      })
    }

    console.log('paramsObject===', paramsObject)
    const queryString1 = queryString.stringify(paramsObject)
    console.log('queryString1===', queryString1)
    const queryString2 = encodeURIComponent(queryString1).replace('+', '%20').replace('*', '%2A').replace('%7E', '~')
    console.log('queryString2===', queryString2)
    config.headers['signature'] = aesEncrypt_HmacSha256(queryString2, key)
    config.headers['timestamp'] = moment().format('YYYY-MM-DD HH:mm:ss') // 格式化输出

    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code === 200) {
      return res
    } else {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.code === 401) {
        MessageBox.confirm('请重新登录', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.msg || 'Error'))
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
