import Vue from "vue";
import axios from "axios";
import router from "../router";

const ERROR_MSG_CONFIG = require("./errorMsgConfig").default;

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

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

const _axios = axios.create(config);
const _axiosWithoutResponseInterceptors = axios.create(config);

/**
 * A. token lifecycle
 * 1. /login UI => localStorage.removeItem('token') && localStorage.setItem('token')
 * 2. non /login UI => axios if(!wk_token) wk_token = window.sessionStorage.getItem("token"), send request
 * 3. if axios request fail with 401/403, wk_token = null, redirect to /login removeItem('token')
 * 4. logout to /login, before send request, invalidate wk_token
 * */

let wk_token, wk_key;
let wk_orgId;

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    if (
      config.url.includes("/login") === false &&
      config.url.includes("/auth/thirdPartyAccess") === false
    ) {
      if (!wk_token) {
        const user = JSON.parse(window.sessionStorage.getItem("user"));
        if (!user) {
          Vue.prototype.$alert("登录失效,请重新登录！", "提示", {
            confirmButtonText: "确定",
            callback: () => {
              // if (process.env.NODE_ENV !== "production") {
              //   router.push("/login/" + "?orgId=" + wk_orgId);
              // } else {
              //   router.push("/login");
              // }
              router.push("/login/" + "?orgId=" + wk_orgId);
            }
          });
          return;
        }
        wk_token = user.token;
        wk_key = user.key;
        wk_orgId = user.rootOrgId;
      }
      if (wk_token && config.headers.common["token"] == null) {
        config.headers.common["token"] = wk_token;
        config.headers.common["key"] = wk_key;
      }
    } else {
      wk_token = null;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    Vue.prototype.$notify({
      showClose: true,
      message: error,
      type: "error"
    });
    return Promise.reject(error);
  }
);

_axiosWithoutResponseInterceptors.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    if (config.url.includes("/login") === false) {
      if (!wk_token) {
        const user = JSON.parse(window.sessionStorage.getItem("user"));
        wk_token = user.token;
        wk_key = user.key;
        wk_orgId = user.rootOrgId;
      }
      if (wk_token && config.headers.common["token"] == null) {
        config.headers.common["token"] = wk_token;
        config.headers.common["key"] = wk_key;
      }
    } else {
      wk_token = null;
    }
    return config;
  },
  function(error) {
    // Do something with request error
    Vue.prototype.$notify({
      showClose: true,
      message: error,
      type: "error"
    });
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    console.log(error);
    if (!error.response) {
      // "Network Error" 网络不通，直接返回

      Vue.prototype.$notify({
        showClose: true,
        message: "网络连接异常，请检查网络设置。",
        type: "error"
      });
      return Promise.reject(error);
    }
    // 这里是返回状态码不为200时候的错误处理
    let status = error.response.status;

    // 登录失效 跳转登录页面
    if (status == 403 || status == 401) {
      Vue.prototype.$alert("登录失效,请重新登录！", "提示", {
        confirmButtonText: "确定",
        callback: () => {
          router.push("/login/" + "?orgId=" + wk_orgId);
        }
      });
      return Promise.reject(error);
    } else if (status == 405) {
      Vue.prototype.$alert("没有权限！", "提示", {
        confirmButtonText: "确定",
        callback: () => {
          router.push("/login/" + "?orgId=" + wk_orgId);
        }
      });
      return Promise.reject(error);
    }

    if (status != 200) {
      const data = error.response.data;
      if (ERROR_MSG_CONFIG.map(v => v.code).includes(data.code)) {
        const MSG = ERROR_MSG_CONFIG.find(v => v.code === data.code);
        if (MSG.display) {
          Vue.prototype.$notify({
            showClose: true,
            message: MSG.message,
            type: "error"
          });
        }
      } else {
        if (data && data.desc) {
          Vue.prototype.$notify({
            showClose: true,
            message: data.desc,
            type: "error"
          });
        } else {
          Vue.prototype.$notify({
            showClose: true,
            message: "未定义异常: " + JSON.stringify(data, 2),
            type: "error"
          });
        }
      }
      return Promise.reject(error);
    }
  }
);

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

Vue.use(Plugin);

export default Plugin;
