import Vue from 'vue'
import axios from 'axios'
import router from '../router'
import _ from 'lodash'
import { Toast, Notify } from 'vant'
import { getCookieValue } from '../utils'
import { platform } from '../utils/platform'

const host = window.location.host
const domain = host.substring(0, host.indexOf('.')) || host.substring(0, host.indexOf(':'))
const request = axios.create({
  withCredentials: true,
  baseURL: process.env.API_DOMAIN,
  timeout: 50000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
})
let tingbangSource = 'h5'
if (platform.isAlipay) {
  tingbangSource = 'alipay'
} else if (platform.isWeixin) {
  tingbangSource = 'wechat'
}
let loading = null
// 当前正在请求的数量
let needLoadingRequestCount = 0

// 显示loading
function showLoading () {
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Toast.loading({
      message: '拼命获取中',
      forbidClick: true,
      duration: 0
    })
  }
  needLoadingRequestCount++
}

// 隐藏loading
function hideLoading () {
  needLoadingRequestCount--
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0) // 做个保护
  if (needLoadingRequestCount === 0) {
    // 关闭loading
    toHideLoading()
  }
}

// 防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
function toHideLoading () {
  _.debounce(() => {
    loading.clear()
    loading = null
  }, 300)
}

// Add a request interceptor
request.interceptors.request.use(request => {
  const requestUrl = request.url

  request.headers.token = getCookieValue('afhousetoken')
  request.headers.tingbangSource = tingbangSource
  if (platform.isWeixin) {
    // 因为微信开发者工具重复授权，本地开发时写死
    if (/^(0|192|10|localhost)/.test(domain)) {
      // request.url += '&owner_open_id=0c540a8d284b38f84d2f8ad262ab5d2c'
      request.headers.wechatToken = '0c540a8d284b38f84d2f8ad262ab5d2c'
    } else {
      request.headers.wechatToken = getCookieValue('afhousewechatToken')
    }
  }
  request.url = requestUrl + (requestUrl.indexOf('?') > -1 ? '&' : '?') + 'nextUrl=' + encodeURIComponent(location.href)

  // 判断当前请求是否设置了不显示Loading
  if (request.showLoading) {
    showLoading()
  }

  return request
}, error => {
  // 判断当前请求是否设置了不显示Loading
  if (loading) {
    hideLoading()
  }
  Notify({
    type: 'warning',
    message: '请求超时'
  })
  // Do something with request error
  return Promise.reject(error)
})

// Add a response interceptor
request.interceptors.response.use(response => {
  // Do something with response data
  const { code, url } = response.data
  if (loading) {
    hideLoading()
  }
  if (code === 301 && url) {
    Vue.cookie.delete('afhousewechatToken')
    location.replace(url)
  } else if (code === 403 && router.currentRoute.name !== 'Login') {
    router.replace({
      path: '/login',
      query: {
        nextUrl: router.currentRoute.fullPath
      }
    })
  }
  return response.data
}, (error) => {
  if (loading) {
    hideLoading()
  }
  Notify({
    type: 'danger',
    message: '数据获取失败！'
  })
  // Do something with response error
  return Promise.reject(error)
})

export default request
