import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken, getRefreshToken } from "@/utils/auth";
import { CodeSr } from "@/api/user";
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

const service = axios.create({
    //baseURL: '/PMS3/Application/third/dnzlxt/api',
    baseURL: '/api',
    timeout: 50000,
});

// service.interceptors.request.use(
//   config => {
//      if(config.url !=='/pqs-oauth2/oauth/token' || config.params.grant_type=='refresh_token'){
//      if (store.getters.token){
//       config.headers['Authorization'] = getToken()
//      }
//    }else{
//       store.dispatch('user/remToken').then(() => {
//       //location.reload()
//     })
//    }
//     return config
//   },
//   error => {
//     return Promise.reject(error)
//   }
// )

//拦截器

service.interceptors.request.use(
    (config) => {
        config.headers["Authorization"] =
            "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySW5kZXgiOiIwOTE4ODgzMTAyOGE0MmQ4YjBmZWEwZDQ0M2ZmYmZiMSIsInVzZXJfbmFtZSI6ImNneXFyc3kiLCJzY29wZSI6WyJhbGwiXSwibmlja25hbWUiOiLotoXpq5jljovltYzlhaXkvb_nlKjnlKjmiLciLCJ1c2VyVHlwZSI6MiwiZGVwdEluZGV4IjoiNTY5OWU1OTE2YTE4YTYzODFlMWFjOTJkYTViZDI2MjgiLCJleHAiOjI1OTQ0MDIzMzYsImF1dGhvcml0aWVzIjpbImZvcm1hbF91c2VyIl0sImp0aSI6IjBlNTk1NWYyLWRmMzYtNDkyNS05NzI2LTI5MDQ4Y2YzYTkyYyIsImNsaWVudF9pZCI6Im5qY250ZXN0IiwiaGVhZFNjdWxwdHVyZSI6bnVsbH0.TrVqk5e2oBCmIQqax9zUefGoSaqr-WFeNfe8fUhOEIyW0YjOkCHl4WC06aJk_bLfLDnE8OzMFoPb_0PSzve0H1f20EcZGjWDEXd3YEZ9BsfgDb52TGALvAwxikQnF8oG4MPS6d0dQhkDrVqCskCy-YvjSpa48fsDDPgWUjfYdJaNN_2m1bKr1kdOdyp-XHl1_c6QcGCLnaA7uSdTLtuQnChy82vDHbOiN1SNO-wbp1WdK0MmW2r_HvdYBEe-3L921787qbpwaej0S6hJ1rvZJCqKvT0o9L0GlO_QEGAsEcu0Jdl-l49MaskqLpBsM-wsBUS_W0rjF4GL0pMBs-TJAw";
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
let refreshing = false, // 正在刷新标识，避免重复刷新
    waitQueue = []; // 请求等待队列
service.interceptors.response.use(
    ({ config, data }) => {
        const { code, message } = data;
        //console.log(data);
        if (code !== "A0000") {
            if (code === "A0202") {
                // access_token过期，尝试续期token
                if (refreshing == false) {
                    refreshing = true; // 切换正在刷新标识，其他请求先进请求等待队列中
                    const refreshToken = getRefreshToken();
                    return store
                        .dispatch("user/refreshToken", refreshToken)
                        .then((token) => {
                            config.headers["Authorization"] = token;
                            config.baseURL = ""; // 请求重试时，url已包含baseURL
                            waitQueue.forEach((callback) => callback(token)); // 已成功刷新token，队列中的所有请求重试
                            waitQueue = [];
                            return service(config);
                        })
                        .catch(() => {
                            // token续期失败
                            MessageBox.confirm("当前页面已失效，请重新认证", "确认退出", {
                                confirmButtonText: "重新登录",
                                cancelButtonText: "取消",
                                type: "warning",
                                showClose: false,
                                showCancelButton: false,
                                closeOnClickModal: false,
                                type: "warning",
                            }).then(() => {
                                store.dispatch("user/resetToken").then(() => {});
                            });
                        })
                        .finally(() => {
                            refreshing = false;
                        });
                } else {
                    return new Promise((resolve) => {
                        waitQueue.push((token) => {
                            config.headers["Authorization"] = token;
                            config.baseURL = "";
                            resolve(service(config));
                        });
                    });
                }
            } else if (code === "A0024") {
                // token被禁止访问，添加到黑名单，跳转至登录页
                MessageBox.confirm("会话已过期，请重新认证", "警告", {
                    confirmButtonText: "重新登录",
                    cancelButtonText: "取消",
                    type: "warning",
                    showClose: false,
                    showCancelButton: false,
                    closeOnClickModal: false,
                }).then(() => {
                    store.dispatch("user/resetToken").then(() => {
                        location.reload();
                    });
                });
                // store.dispatch('user/resetToken').then(() => {

                //  })
            } else if (code === "A0101") {
                Message({ message: message, type: "warning" });
                return data;
            } else if (code === "A0002") {
                Message({ message: message, type: "warning" });
                return data;
            } else if (message) {
                Message({ message: message, type: "warning" });
                if (code === "A0095" || code === "A0094" || code === "A0001") {
                    Message({ message: message, type: "warning" });
                    return data;
                }
                if (code === "A0101") {
                    //  if(window.sessionStorage.getItem('imgcode')){ window.sessionStorage.removeItem('imgcode')}else{ window.sessionStorage.setItem('imgcode',false) }
                    Message({ message: message, type: "warning" });
                    return Promise.reject(new Error(message));
                }
            } else {
                // alert(22222)
                return data;
            }
        } else {
            return data;
        }
    },
    (error) => {
        return Promise.reject(error);
    }
);
export default service;