import axios from "axios";
import {
    MessageBox,
    Message,
    Loading
} from "element-ui";
import store from "@/store";
import {
    getToken
} from "@/utils/auth";
let isHandle = false;

// create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API,
    baseURL: "http://10.48.36.43:18810/", // url = base url + request url
    // baseURL: "http://124.70.58.209:18810/", // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 20000, // request timeout
});

let loadingInstance = null;

function startLoading() {
    loadingInstance = Loading.service({
        fullscreen: true,
        text: "拼命加载中...",
        background: "rgba(0, 0, 0, 0.8)",
    });
}

function endLoading() {
    loadingInstance.close();
}
let needLoadingRequestCount = 0;

function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading();
    }
    needLoadingRequestCount++;
}

function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return;
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
        endLoading();
    }
}

// request interceptor
service.interceptors.request.use(
  (config) => {
    if (window.location.hash !== "#/dashboard"&&window.location.hash !=='#/streamRadio/index') {
      showFullScreenLoading();
    }
    const token = localStorage.getItem("token");
    token && (config.headers.Authorization = token);
    // token && (config.headers.token = token);
    return config;
  },
  (error) => {
    if (window.location.hash !== "#/dashboard") {
      tryHideFullScreenLoading();
    }
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    (response) => {
        if (window.location.hash !== "#/dashboard") {
            tryHideFullScreenLoading();
        }
        const res = response.data;
        const rese = response;
        // console.log(rese,'reerrererererere../../../..//');
        // if the custom code is not 20000, it is judged as an error.
        if (res.code !== 200 && !res.type && rese.status !== 200) {
            Message({
                message: res.msg || "Error",
                type: "error",
                duration: 5 * 1000,
            });

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (res.code === 50008 || res.code === 50014) {
                // to re-login
                MessageBox.confirm(
                    "You have been logged out, you can cancel to stay on this page, or log in again",
                    "Confirm logout", {
                        confirmButtonText: "Re-Login",
                        cancelButtonText: "Cancel",
                        type: "warning",
                    }
                ).then(() => {
                    store.dispatch("user/resetToken").then(() => {
                        location.reload();
                    });
                });
            }
            return Promise.reject(new Error(res.msg || "Error"));
        } else if (res.type) {
            return res;
        } else {
            if (res.code == 406) {
                if (isHandle) return;
                isHandle = true;
                let str = res.msg.substr(-19);
                MessageBox.confirm(
                    `当前账号于${str}在其他设备上登录,此设备已退出登录`,
                    "提示", {
                        confirmButtonText: "退出登录",
                        cancelButtonText: "取消",
                        type: "warning",
                    }
                ).then(() => {
                    store.dispatch("user/resetToken").then(() => {
                        location.reload();
                    });
                });
                setTimeout(() => {
                    isHandle = false;
                }, 1000);
            } else if (res.code == 402) {
                if (isHandle) return;
                isHandle = true;
                MessageBox.confirm(`当前账号登录已过期，请重新登录！`, "提示", {
                    confirmButtonText: "退出登录",
                    cancelButtonText: "取消",
                    type: "warning",
                }).then(() => {
                    store.dispatch("user/resetToken").then(() => {
                        location.reload();
                    });
                });
                setTimeout(() => {
                    isHandle = false;
                }, 1000);
            } else {
                return res;
            }
            // return res
        }
    },
    (error) => {
        if (window.location.hash !== "#/dashboard") {
            tryHideFullScreenLoading();
        }
        console.log("err" + error); // for debug
        Message({
            message: error.message,
            type: "error",
            duration: 5 * 1000,
        });
        return Promise.reject(error);
    }
);

export default service;
