// 1 引库
import axios from 'axios'
import qs from 'qs'
import local from '@/utils/local' // 本地封装

// 2 添加配置
axios.defaults.baseURL = ''
axios.defaults.timeout = 50000
// axios.defaults.responseType = 'application/x-www-form-urlencoded'
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*' // 允许所有
// 3 拦截器
axios.interceptors.request.use(
  config => {
    if (local.get('token_sd')) {
      // config.headers.Authorization = local.get('token_sd')
    }
    return config
  },
  err => {
    return Promise.reject(err)
  })

// 响应拦截器
axios.interceptors.response.use(
  response => {
    return response
  },
  err => {
    // if (response.status === 404) {
    //   // 比如跳转到404
    //   router.push({ name: 'login' })
    // }
    return Promise.reject(err)
  })

// 4 暴露方法
const post = (url, data) => {
  return new Promise((resolve, reject) => {
    axios
      .post(url, qs.stringify(data))
      .then(res => {
        resolve(res.data)
        if (res.data.code === 0) {
          window.open('/home/login.html', '_self')
        }
      })
      .catch(err => {
        console.log(err)
      })
  })
}

const get = (url, params) => {
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params })
      .then(res => {
        resolve(res.data)
        if (res.data.code === 0) {
          window.open('/home/login.html', '_self')
        }
      })
      .catch(err => {
        console.log(err)
      })
  })
}

export default {
  post,
  get
}
