import { message, notification } from 'antd';
import modal from 'antd/es/modal';
import axios, { AxiosRequestConfig } from 'axios'
import qs from 'qs';
let { weApi } = process.env.CONFIG;

const errorCode: { [x: string]: string } = {
    '401': '认证失败，无法访问系统资源',
    '403': '当前操作没有权限',
    '404': '访问资源不存在',
    'default': '系统未知错误,请反馈给管理员'
}

// 标识登录过期的状态
let expired = false;
(axios.defaults.headers as any)['Content-Type'] = 'application/json;charset=utf-8'

// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: weApi,
    timeout: 300000
})

// request拦截器
service.interceptors.request.use((config: AxiosRequestConfig<any>) => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    if (localStorage.getItem('Admin-Token') && !isToken && config?.headers) {
        config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('Admin-Token') // 让每个请求携带自定义token 请根据实际
    }
    // 处理get穿数组
    if (config.method === 'get') {
        config.paramsSerializer = function (params) {
            return qs.stringify(params, { arrayFormat: 'repeat' })
        }
    }
    return config
}, error => {
    console.log(error)
    Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
    // 未设置状态码则默认成功状态
    const code = res.data.code || 200;
    // 获取错误信息
    const msg = errorCode[code] || res.data.msg || errorCode['default']
    if (code === 401) {
        modal.warning({
            title: '系统提示',
            content: '登录状态已过期，您可以继续留在该页面，或者重新登录',
            onOk: () => {
                localStorage.removeItem('Admin-Token')
                sessionStorage.removeItem('userId')
                window.location.href = window.location.origin + '/#/login'
            }
        })
    } else if (code === 310) {
        if (expired) return; // 避免多次触发
        expired = true;
        localStorage.removeItem('Admin-Token')
        sessionStorage.removeItem('userId')
        message.error({
            content: msg,
            duration: 2,
            onClose: () => {
                window.location.href = window.location.origin + '/#/login'
            }
        })
        return Promise.reject(new Error(msg))
    } else if (code === 500) {
        message.error(msg)
        return Promise.reject(new Error(msg))
    } else if (code !== 200) {
        notification.error({
            message: code,
            description: msg
        })
        return Promise.reject('error')
    } else {
        return res.data
    }
}, error => {
    console.log('interceptors.response--->', error)
    let { message: msg } = error;
    if (msg == "Network Error") {
        msg = "后端接口连接异常";
    } else if (msg.includes("timeout")) {
        msg = "系统接口请求超时";
    } else if (msg.includes("Request failed with status code")) {
        msg = "系统接口" + msg.substr(msg.length - 3) + "异常";
    }
    message.error({ content: msg, duration: 5 })
    return Promise.reject(error)
})

export default service