import Vue from "vue";
// import Store from "@/store";
import axios from "axios";
import { loadProgressBar } from "axios-progress-bar";
import cachingGet from "./axiosCache";
import { notifyInvalidTokenThrottled } from "./axiosNotice";
import { getToken, removeToken, getSessionId } from "../auth/auth";
import axiosRetry from "axios-retry";
import { PLATFORM, DEVICE_ID } from "@/constant/constants";
import { Notification, MessageBox } from "element-ui";
import CryptoJS from "crypto-js";
import router from "@/router";

// console.log(btoa(CryptoJS.SHA1("pWWQ0qyaXL8QHni4ig9YiWYTKr8UVQd4")));
// console.log(
//   CryptoJS.enc.Base64.stringify(
//     CryptoJS.SHA1("pWWQ0qyaXL8QHni4ig9YiWYTKr8UVQd4")
//   )
// );
//QpVbMSbQrMVCxQEKqks8+E34+W8=
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.BASE_URL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

const config = {
  // baseURL: process.env.baseURL || process.env.apiUrl || ""
  timeout: 3 * 60 * 1000, // Timeout
  withCredentials: true, // Check cross-site Access-Control
};
const cacheGetUrls = [];

const _axiosApp = axios.create(config);
axiosRetry(_axiosApp);

function gToken(method, url, token, now) {
  // const now = Date.now();
  // console.log(`${getSessionId()} ${method}&${url}&${now}&${token}`);
  // const a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  // let randomStr = "";
  // for (let i = 0; i < 6; i++) {
  //   const idx = Math.round(Math.random() * 100) % a.length;
  //   randomStr += a[idx];
  // }

  const Authorization = `Token ${getSessionId()}:${CryptoJS.enc.Base64.stringify(
    CryptoJS.SHA1("post&" + url + "&" + now + "&" + token)
  )}`;

  return Authorization;
}

_axiosApp.interceptors.request.use(
  function (config) {
    const wk_token = getToken();
    const now = Date.now();
    if (wk_token) {
      const completeURL = new URL("http://nasty.com" + config.url);
      const path = completeURL.pathname;
      config.headers.common["Authorization"] = gToken(
        config.method,
        path,
        wk_token,
        now
      );
      // config.headers.common["Authorization"] = wk_token;
    }
    config.headers.common["platform"] = PLATFORM;
    config.headers.common["deviceId"] = DEVICE_ID;
    config.headers.common["time"] = now;
    return config;
  },
  function (error) {
    // Do something with request error
    Vue.prototype.$notify({
      showClose: true,
      message: error,
      type: "error",
    });
    return Promise.reject(error);
  }
);
let unauthMsgBoxIsShow = false;
// Add a response interceptor
_axiosApp.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    const showErrorMessage = !error.config?.noErrorMessage;
    if (!error.response) {
      if (showErrorMessage) {
        // "Network Error" 网络不通，直接返回
        Notification({
          showClose: true,
          message: "网络连接异常，请检查网络设置。",
          type: "error",
        });
      }
      return Promise.reject(error);
    }
    // 这里是返回状态码不为200时候的错误处理
    let status = error.response.status;

    // 登录失效 跳转登录页面
    if (status == 403 || status == 401) {
      notifyInvalidTokenThrottled();
      removeToken();
      return Promise.reject(error);
    } else if (status == 405) {
      if (showErrorMessage) {
        Notification({
          showClose: true,
          message: "没有权限！",
          type: "error",
        });
      }
      return Promise.reject(error);
    } else if (status == 502) {
      if (showErrorMessage) {
        Notification({
          showClose: true,
          message: "服务器异常(502)！",
          type: "error",
        });
      }
      return Promise.reject(error);
    }

    if (status != 200) {
      const data = error.response.data;

      if (status === 500 && data && data.code === 500012) {
        if (unauthMsgBoxIsShow) return error;
        unauthMsgBoxIsShow = true;
        MessageBox.confirm("身份验证失效，请重新登录！", "错误提示", {
          type: "warning",
          closeOnClickModal: false,
          closeOnPressEscape: false,
          showClose: false,
          callback: (action) => {
            unauthMsgBoxIsShow = false;
            if (action !== "confirm") return;
            router.push({ name: "Login" });
          },
        });
        return Promise.reject(error);
      }

      if (data && data.message) {
        if (showErrorMessage) {
          Notification({
            showClose: true,
            message: data.message,
            type: "error",
          });
        }
      } else {
        if (showErrorMessage) {
          Notification({
            showClose: true,
            message: "未定义异常: " + JSON.stringify(data, 2),
            type: "error",
          });
        }
      }
      return Promise.reject(error);
    }
  }
);

_axiosApp.get = cachingGet(_axiosApp.get, cacheGetUrls);
loadProgressBar(_axiosApp);

Plugin.install = function (Vue) {
  Object.defineProperties(Vue.prototype, {
    $http: {
      get() {
        return _axiosApp;
      },
    },
  });
};

Vue.use(Plugin);

export default Plugin;

export const httpApp = _axiosApp;
