import { message, notification } from 'antd';
import axios, { InternalAxiosRequestConfig } from 'axios'
import { isOs, sign } from './index.ts';
import { getGameId, getToken, removeToken } from './auth.ts';

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

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

// 创建axios实例
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 1000 * 60 * 2
})

// request拦截器
service.interceptors.request.use((config: InternalAxiosRequestConfig<any>) => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false
    let timestamp = Date.now()
    let token = getToken()
    if (token && !isToken && config?.headers) {
        config.headers['token'] = token // 让每个请求携带自定义token 请根据实际
    }
    config.headers['timestamp'] = timestamp
    config.headers['channel'] = window.location.search.substr(1) || window.location.search.substring(1) || ''
    config.headers['deviceType'] = 3
    config.headers['gameId'] = getGameId()
    config.headers['os'] = isOs()
    config.headers['sign'] = sign(timestamp)
    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 || code === 40400) {
        message.error({
            content: msg || '请登录',
            onClose: () => {
                removeToken()
                window.location.reload()
            }
        })
    } else if (code === 310) {
        if (expired) return; // 避免多次触发
        expired = true;
        removeToken()
        message.error({
            content: msg,
            duration: 2,
            onClose: () => {
                window.location.reload()
            }
        })
        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 => {
    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