/**
 * 封装axios
 */

import axios from "axios"
import router from "../router"
import store from "../store/index";
import api from "../api/index";
import jwt_decode from "jwt-decode"

const toLogin = () => {
    router.push("/login")
}

const errorHandle = (status, other) => {
    switch (status) {
        case 400:
            console.log("请求信息发生错误");
            break;
        case 401:
            console.log("用户信息验证失败:token验证失败");
            // localStorage.removeItem("token")
            // toLogin();
            break;
        case 403:
            console.log("请求被限制");
            // localStorage.removeItem("token")
            // toLogin();
            break;
        case 404:
            console.log("客户端错误");
            break;
        default:
            console.log(other);
            break;
    }
}

const instance = axios.create({
    timeout: 8000
})

/**
 * 请求和响应拦截
 */

instance.interceptors.request.use(
    config => {
        const token = localStorage.getItem("x-token")
            // console.log(token, "token")
        config.data = JSON.stringify(config.data);
        config.headers = {
            'Content-Type': 'application/json',
            'X-Token': token,
        }
        return config;
    },
    error => {
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    response => {
        if (response.data.code === 0 && response.headers["x-token"]) {
            localStorage.setItem("x-token", response.headers["x-token"])
                // 更新游戏的token
                // api.info().then(res => {
                //     console.log(res, "res===================")
                //     store.dispatch("userInfoAction", res.data.data)
                //     localStorage.setItem("userInfo", JSON.stringify(res.data.data));
                // })
            const token = jwt_decode(response.headers["x-token"])
            store.dispatch("tokenAction", token.jti)
            localStorage.setItem("token", token.jti);
            // console.log(token.jti, "token.jti", store.state.token, "store", localStorage.getItem("token"), "========")
        }
        return response.status === 200 ? Promise.resolve(response) : Promise.reject(response)
    },
    error => {
        const {
            response
        } = error;
        if (response) {
            //  处理错误信息
            errorHandle(response.status, response.data);
            return Promise.reject(response);
        } else {
            // 断网操作，请求发生错误
            console.log("断网操作，请求发生错误");
        }
    }
)

export default instance;