/*
 * @Author: Kane
 * @Date: 2022-12-22 17:18:10
 * @LastEditors: Kane
 * @LastEditTime: 2023-02-06 09:19:32
 * @FilePath: /IT工具综合平台/src/utils/api/request.js
 * @Description: 配置axios拦截器
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
import axios from "axios";
import store from "../../store/index";
import router from "@/router";
import { ElMessageBox } from "element-plus";

const service = axios.create(
    {
        baseURL: "",
        timeout: 10000, //十秒超时
    }
);

/**
 * 加上请求拦截器
 */
service.interceptors.request.use(
    function (config)
    {
        //axios拦截器请求，在请求的header加上用户名和token
        if (store.state.app.userInfo)
        {
            //如果userInfo存在，则加上用户名和token
            const username = store.state.app.userInfo.staff_info.p13uid;
            const token = store.state.app.userInfo.token;

            config.headers["token"] = token;
            config.headers["username"] = username;

            console.log("拦截器，加上username和token！", username, token);
        }
        else
        {
            console.log("拦截器，userinfo为空！");
        }

        return config;
    },
    function (error)
    {
        console.log("请求拦截器失败！");
        return Promise.reject(error);
    }
);

//响应拦截器
service.interceptors.response.use(
    function (response)
    {
        //200
        if (response.status === 200)
        {
            console.log("响应拦截器，响应代码", response.status);
        }

        //401，用户token失效，跳转到
        if (response.state === 401)
        {
            ElMessageBox.confirm(
                "用户登录超时，请重新登录",
                "警告",
                {
                    confirmButtonText: "是",
                    cancelButtonText: "否",
                    type: "warning",
                }
            ).then(() =>
            {
                router.replace("/login");
            }).catch(() =>
            {
                router.replace("/login");
            });
        }

        return response;
    },
    function (error)
    {
        console.log("响应拦截器，异常信息：", error);

        return Promise.reject(error);
    }
);

export default service;