/**
 * @Author: NanKeYang
 * @Description: axios封装
 * @Data: 2019/12/27 15:41
 */
import axios from 'axios'
import {Toast} from 'mand-mobile'
import store from '@/store'
import qs from 'qs'

// create an axios instance
const service = axios.create({
    baseURL: process.env.NODE_ENV == 'development' ? process.env.VUE_APP_BASE_API : location.host, // url = base url + request url
    timeout: 1000 * 60 * 10 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // console.log(config)
        if (config.method === 'post') {
            if (config.headers['Content-Type'] != 'multipart/form-data') {
                config.data = qs.stringify(config.data, {
                    arrayFormat: 'brackets'
                })
            }
        }
        if (store.getters.token) {
            // config.headers['Authorization'] = getToken()
        }
        return config
    },
    error => {
        // do something with request error
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        // 处理错误返回
        if (res.code !== 200 && res.code !== 0 && res.code !== 1) {
            Toast.failed('请求失败')
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            // if (res.code === 200) {
            //     Toast.succeed('请求成功')
            // }
            return res
        }
    },
    error => {
        Toast.failed('请求失败')
        return Promise.reject(error)
    }
)

export default service
