import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'

const httpRequest = axios.create({
  baseURL: process.env.baseURL,
  timeout: 60000,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})

// 请求拦截
httpRequest.interceptors.request.use(
  function(config) {
    if (config.url.includes('/api/cms')) {
      const defaultParams = {
        timestamp: parseInt(Date.now() / 1000),
        nonce: Math.random()
          .toString(36)
          .slice(-8)
      }
      // 接口请求参数
      let params = config.params || config.data
      // 排序
      function alphabeticalSort(a, b) {
        return a.localeCompare(b)
      }
      params = Object.assign({}, defaultParams, params)
      const str = qs.stringify(Object.assign({}, params, { salt: 'n7xAav2tSjn9Ysnr' }), { sort: alphabeticalSort })
      const strs = qs.parse(str)
      Object.keys(strs).map(item => {
        strs[item] = Array.isArray(strs[item]) ? JSON.stringify(strs[item]) : strs[item]
      })
      params.signature = 'UG7wBenexQhiuD2wpCwuxkU0jqcj006d'
      if (config.method === 'post') {
        config.data = params
      } else {
        config.params = params
      }
    }
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    if (config.headers['Content-Type'] === 'multipart/form-data') {
      const form = new window.FormData()
      for (const key in config.data) {
        form.append(key, config.data[key])
      }
      config.data = form
    }
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)

// 响应拦截
httpRequest.interceptors.response.use(
  function(response) {
    const { data } = response
    // zws
    if (parseInt(data.code)) {
      return Promise.reject(data)
    }
    if (parseInt(data.error) && data.message === '需要登录才能调用接口') {
      location.href = `${process.env.loginURL}/login/index?redirect_uri=${encodeURIComponent(location.href)}`
      return Promise.reject(data)
    }

    // enrollment
    if (parseInt(data.error)) {
      Message.error(data.message)
      return Promise.reject(data)
    }
    return data
  },
  function(error) {
    if (error.response) {
      const { message } = error.response.data
      Message.error(message || error.response.data)
      return Promise.reject(error.response)
    } else {
      Message.error(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
