/*
 * @Author: wt 1241351815@qq.com
 * @Date: 2022-04-25 10:21:19
 * @LastEditors: wt 1241351815@qq.com
 * @LastEditTime: 2022-05-12 18:19:11
 * @FilePath: \securityHtml\src\utils\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Cookies from "js-cookie";
let baseURL = window.PLATFROM_CONFIG.baseUrl
axios.defaults.headers['Content-Type'] = 'application/json;multipart/form-data;charset=utf-8'
const service = axios.create({
    baseURL: baseURL, // url = base url + request url
    timeout: 10000, // request timeout
    // withCredentials:true,

})

// request interceptor
service.interceptors.request.use(config => {
        // 是否需要设置 token
        // const isToken = (config.headers || {}).isToken === false
        if (getToken()) {
            config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        if (config.method == 'get') {
            let ext_str = config.url.indexOf('?') == -1 ? '?' : '&';
            let obj_val = '';
            for (let k in config.data) {
                obj_val += k + "=" + config.data[k] + "&";
            }
            config.url += ext_str + obj_val;
        }
        return config
    },
    error => {
        // do something with request error
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(response => {
    if (response.data.status === 'SUCCESS') {
        return response.data;
    } else {
        if (response.data.code == "401") {
            MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                store.dispatch('logout').then(() => {
                    location.href = '/#/login';
                })
            }).catch(() => {});
        }
    }
}, error => {
    Message({
        showClose: true,
        message: (error.response.data.msg).split(":")[1],
        type: 'error'
    });
    return {}
})

export default service