import axios from 'axios'
import qs from 'qs'
import { Notify } from 'vant'

const httpRequest = axios.create({
  baseURL: 'https://project-api.ezijing.com',
  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
    if (parseInt(data.code)) {
      Notify(data.msg)
      return Promise.reject(data)
    }
    return data
  },
  function(error) {
    if (error.response) {
      const { message } = error.response.data
      Notify(message || error.response.data)
      return Promise.reject(error.response)
    } else {
      Notify(error)
    }
    return Promise.reject(error)
  }
)

export default httpRequest
