/*
 * @Author       : yuanrunwei
 * @Date         : 2020-05-18 12:05:37
 * @LastEditors: XuTongZhang
 * @LastEditTime: 2020-08-12 11:55:58
 * @FilePath     : \batterycloud-admin\src\common\api\axios.js
 */
import axios from 'axios'
import vue from '../../main'
import { Message, Loading } from 'element-ui'
// import { all } from 'core-js/fn/promise'
let api = ''
let loading
const whiteList = ['test', 'production']
const allowList = [ // 文件请求路径数组
  '/export/export2Web'
]
const fileUpload = ['/upload/uploadImg']

const service = axios.create({
  baseURL: process.env.VUE_APP_API + '/admin',
  // baseURL: 'http://47.100.59.52:7785',
  timeout: 90000
})

service.interceptors.request.use(
  config => {
    console.log(config.url)
    if (!fileUpload.includes(config.url)) {
      let data = {
        'from': 0,
        'page': 1,
        'rows': 10,
        'companyId': localStorage.getItem('managerid') - 0,
        'sidx': '',
        'sord': '',
        'token': localStorage.getItem('token'),
        'reqdata': {}
      }
      config.data = Object.assign(data, config.data)
    }
    loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    if (allowList.includes(config.url)) {
      // config.headers['Content-Type'] = 'application/vnd.ms-excel'
      // console.log(config)
      config.responseType = 'blob'
    }
    if (config.url === '/addr/all_addr') {
      config.baseURL = process.env.VUE_APP_API
    }
    console.log(config)

    config.headers['Authorization'] = localStorage.getItem('token')
    api = config.url
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  res => {
    console.log(res)
    let a = false
    return new Promise((resolve, reject) => {
      allowList.forEach(item => {
        console.log(res.config.url)
        if (res.config.url === item) {
          // resolve(res.data)
          const content = res.data
          const blob = new Blob([content])
          console.log(blob)
          const fileName = '人才库.xls'
          if ('download' in document.createElement('a')) { // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else { // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
          a = true
        }
      })
      if (a) {
        loading.close()
        return
      }
      if (res.data.state === 206) {
        localStorage.clear()
        // sessionStorage.claer()
        vue.$cookies.removeCookies()
        loading.close()
        setTimeout(() => {
          location.reload()
        }, 100)
      }
      if (fileUpload.indexOf(api) !== -1) {
        loading.close()
        resolve(res.data)
      } else if (res.status === 200) {
        if (res.data.state !== 100) {
          Message({
            message: res.data.msg,
            type: 'error',
            duration: 5 * 1000
          })
          loading.close()
          reject(res.data.msg)
        } else {
          resolve(res.data)
          loading.close()
        }
      } else {
        loading.close()
        Message({
          message: res.statusText,
          type: 'error',
          duration: 5 * 1000
        })
        if (res.status > 100 && res.status < 200) {
          if (whiteList.indexOf(process.env.NODE_ENV) !== -1) {
            let url = `http://monitor.info666.com/monitor/alert?projectAbbr=batterycloud-test&errorMsg=接口：${api}(${res.statusText})&logPath=前端开发环境(${process.env.NODE_ENV})`
            axios.get(url)
            loading.close()
          }
        }
        loading.close()
        reject(res)
      }
      // }
    })
  },
  error => {
    loading.close()
    Message({
      message: '请求异常' + error,
      type: 'error',
      duration: 5 * 1000
    })
  }
)
export default service
