import axios from 'axios'
import store from '@/store/index'
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";
import { apiList, aesKey } from "./config";
window.apiList = apiList
var baseURLSign = 0
var ajax = zhCn.ajax
// 创建axios实例
const base64 = ['password', 'old_password', 'new_password', 'new_password2', 'password_transaction']

const service = axios.create({
  baseURL: window.apiList[baseURLSign], // api的base_url
  timeout: 60000, // 请求超时时间,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  }
})
// request拦截器
service.interceptors.request.use(
  config => {
    if (config.getApiCount) {
      if (config.baseURL.indexOf('api.jdnxtrade.com') === -1) {
        config.baseURL = window.apiList[config.getApiCount]
      }
    } else {
      if (config.baseURL.indexOf('api.jdnxtrade.com') === -1) {
        config.baseURL = window.apiList[baseURLSign]
      }
      var data = ''
      if (config.data) {
        data = JSON.parse(JSON.stringify(config.data))
      }
      base64.forEach(item => {
        if(data && data[item]) {
          data[item] = encryption(data[item], aesKey)
        }
      })
      if (data) {
        data = qs.stringify(data)
      }
      config.data = data
      if(config.url.indexOf('/info/v2/') == -1) {
        config.headers.language = store.getters.language
      }
      var userToken = store.getters.token
      if(!config.headers.authorization && userToken) {
        config.headers.authorization = 'Bearer ' + userToken
      } else {
        if (config.update) {
          config.headers.authorization = 'Bearer ' + store.getters.socketToken
        }
      }
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)
// respone拦截器
service.interceptors.response.use(
  response => {
    if (response.status == 200) {
      if (response.config.getApiCount) {
        baseURLSign = response.config.getApiCount
      }
      var data = response.data || {}
      if (data.code) {
        if (data.code == 4000) {
          if (response.config.login === 1) {
            return Promise.reject(response.data)
          }
          if (store.getters.token) {
            store.commit('SET_LOGIN', false)
            store.commit('setAccountList', [])
            store.commit('setCashInfo', {})
            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 || data
        }
        if (data.code == -2) {
          return Promise.reject(response.data)
        }
        if (data.group == 9999) {
          bus.$emit('abnormalPopSign')
          return Promise.reject(response.data)
        }
        if (data.code !== 5003) {
          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 == window.apiList.length) {
      if (config.login != 1) {
        // store.commit('setNetwork', true)
      }
      return Promise.reject(error)
    }
    return service(config)
  }
)
function getErrMsg(data, type){
  var 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('{p}') !== -1) {
    msg = msg.replace('{p}', data.return_param ||  (data.data && (data.data.min_amount || data.data.max_amount || Number(data.data))) || '')
  }
  // 网络拥堵，请稍后再试。
  return msg || data.msg || i18n.t('ajax.l3')
}
export default service
