import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: process.env.VUE_APP_HOST_URL + process.env.VUE_APP_BASE_URL,
  timeout: 50000
})

const isArray = data => Object.prototype.toString.call(data) === '[object Array]'

const showToast = (toast, data, msg) => {
  if (toast) {
    const { status, message } = data
    const isToastArray = isArray(toast)
    const needToast = (isToastArray && toast.indexOf(status) === -1) || (!isToastArray && toast)
    if (needToast) {
      if (status === '200' || data.data === 0) {
        if (message) {
          Message.success(message === 'success' ? '操作成功' : message)
        }
      } else {
        Message.error(message || msg)
      }
    }
  }
}

service.interceptors.request.use((request) => {
  const { id } = store.state.app.userInfo
  const token = sessionStorage.getItem('sxToken')
  if (token) {
    request.headers.token = token
  }
  if (id) {
    request.headers.Pragma = 'no-cache'
    request.headers['Cache-Control'] = 'no-cache, no-store'
    if (request.method !== 'post') {
      if (!request.params) {
        request.params = {}
      }
    } else {
      if (request.toast === undefined) {
        request.toast = true
      }
      if (!request.data) {
        request.data = {}
      }
    }
  }
  return request
})

service.interceptors.response.use(
  (response) => {
    const { data, config } = response
    const { loading, toast = loading } = config

    // if (data.status === 12 || data.status === 10 || data.status === 21) {
    //   store.commit('logout')
    //   location.reload()
    // }
    showToast(toast, data, '内部错误')
    if (data.status === '200' || data.access_token) {
      return data
    } else if (data.status === '50000') {
      sessionStorage.removeItem('sxToken')
      store.commit('app/setUserInfo', {})
      store.commit('app/setTabList', [])
      if (process.env.ROUTER_URL === 'sxSSO') {
        location.href = `${process.env.SSO_URL}?state=${new Date().getTime()}&client_id=process&response_type=code&redirect_uri=${encodeURI(window.location.origin + window.location.pathname + window.location.hash)}`
      } else {
        location.href = '#/login'
      }
    } else {
      return Promise.reject(new Error(data.message))
    }
  },
  (err) => {
    if (err.response.status === 403 || err.response.status === 401) {
      store.commit('app/setUserInfo', {})
      location.href = '#/login'
    } else {
      const data = { code: 1000, message: err.response.data.message || '内部错误', data: {}}
      err.data = data
      showToast(true, data, '内部错误')
    }
    return Promise.reject(err)
  }
)
const fetch = options => service.request(options)
export default fetch
