import Vue from 'vue'
import axios from 'axios'
import router from '../router'
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'
}

// 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) {
    request.headers.wechatToken = getCookieValue('afhousewechatToken')
  }
  request.url = requestUrl + (requestUrl.indexOf('?') > -1 ? '&' : '?') + 'nextUrl=' + encodeURIComponent(location.href)
  // 因为微信开发者工具重复授权，本地开发时写死
  if (/^(0|192|10|localhost)|(test$)/.test(domain)) {
    // request.url += '&owner_open_id=0c540a8d284b38f84d2f8ad262ab5d2c'
    request.headers.wechatToken = '0c540a8d284b38f84d2f8ad262ab5d2c'
  }
  return request
}, error => {
  // 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 (code === 301 && url) {
    Vue.cookie.delete('afhousewechatToken')
    location.replace(url)
  } else if (code === 403) {
    router.push('/login')
  }
  return response.data
}, (error) => {
  // Do something with response error
  return Promise.reject(error)
})

export default request
