import axios from 'axios'
import store from '@/store/index'
import { removeCookie } from "@/utils/cookie";
import router from '@/router'
import qs from 'qs'
import {encryption} from '@/utils/aes'
import { Notify } from 'vant';
import bus from '@/utils/bus'
import i18n from '@/lang'
import zhCn from "@/lang/zh-CN";
let ajax = zhCn.ajax
// 创建axios实例
const key = 'WMqg4XECmU4NHvK7'
const base64 = ['password','re_password', 'old_password', 'new_password', 'new_password2', 'password_transaction', 'input_password_transaction']

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // api的base_url
  timeout: 200000, // 请求超时时间,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  }
})
// request拦截器
service.interceptors.request.use(
  config => {
    let data = ''
    if (config.data) {
      data = JSON.parse(JSON.stringify(config.data))
    }
    base64.forEach(item => {
      if(data && data[item]) {
        data[item] = encryption(data[item],key)
      }
    })
    let userToken = store.getters.token
    if(config.baseURL.indexOf('info.jdnx.com') == -1) {
      config.headers.language = store.getters.language
    }
    if(!config.headers.authorization && userToken) {
      config.headers.authorization = 'Bearer ' + userToken
    } else {
      if (config.update) {
        config.headers.authorization = 'Bearer ' + store.getters.socketToken
      }
    }
    if (data) {
      data = qs.stringify(data)
    }
    config.data = data
    return config
  },
  error => {
    Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.status == 200) {
      let data = response.data || {}
      if (data.code) {
        if (data.code == 4000) {
          if (response.config.login === 1) {
            return Promise.reject(response.data)
          }
          if (store.getters.token) {
            removeCookie('userToken')
            store.commit('SET_LOGIN', false)
            store.commit('setToken', '')
            bus.$emit('init')
            if (router.currentRoute.meta.mustLogin) {
              Notify({
                // message: '登录已过期',
                message: i18n.t('ajax.l2'),
                type: 'danger'
              })
              router.replace('/login?rejectUrl=' + router.currentRoute.fullPath)
            }
          }
          return Promise.reject(response.data)
        }
        if (data.code == 1000) {
          if (response.config.login === 1) {
            return Promise.reject(response.data)
          }
          router.replace('/thaw')
          return Promise.reject(response.data)
        }
        if (data.code == '200') {
          return data.token || data.pageInfo || data.data || data.amount
        }
        if (data.code == -2) {
          return Promise.reject(response.data)
        }
        Notify({
          message: data.code ? getErrMsg(data, response.config.type) : data.msg,
          type: 'danger',
          duration: 1500
        })
        return Promise.reject(response.data)
      } else {
        return data.pageInfo || data.data || data
      }
    } else {
      Notify({
        message: response.data.message || response.data.msg,
        type: 'danger'
      })
      return Promise.reject(response.data)
    }
  },
  error => {
    var config = error.config
    if (config.getApiCount) {
      config.getApiCount += 1
    } else {
      config.getApiCount = 1
    }
    if (config.getApiCount == 5) {
      store.commit('setNetwork', true)
      return Promise.reject(error)
    }
    return service(config)
  }
)
function getErrMsg(data, type){
  let msg = ajax[data.code] ? i18n.t('ajax.' + data.code) : '';
  if ((data.code == '1007' || data.code == '1002') && type) {
    msg = i18n.t('ajax.' + (data.code + '' + type))
  }
  if (msg && msg.indexOf('{param}') !== -1) {
    msg = msg.replace('{param}', data.return_param ||  (data.data && (data.data.min_amount || data.data.max_amount)) || '')
  }
  // 网络拥堵，请稍后再试。
  return msg || data.msg || i18n.t('ajax.l3')
}
export default service
