import axios from "axios";
import {
  removeAuth
} from "../utils/auth";
import qs from "qs";
import {
  Dialog,
  Notify
} from 'quasar'

var showLoginMessageBox = false;
axios.defaults.headers["Content-Type"] = "application/json;charset=UTF-8"; //application/x-www-form-urlencoded;charset=UTF-8

const service = axios.create({
  baseURL: process.env.API,
  timeout: 15000
});

// request拦截器
service.interceptors.request.use(
  config => {
    if (config.headers["responseType"] == "arraybuffer") {
      config.responseType = "arraybuffer";
    }
    const flag =
      config.headers["Content-Type"] &&
      config.headers["Content-Type"].indexOf("application/json") !== -1;
    if (!flag) {
      const mult =
        config.headers["Content-Type"] &&
        config.headers["Content-Type"].indexOf("multipart/form-data") !== -1;
      if (mult) {
        config.data = config.data;
      } else {
        config.data = qs.stringify(config.data);
      }
    } else {
      config.data = {
        "Msg": config.data
      }
    }
    return config;
  },
  error => {
    //TODO  新增网络请求异常处理业务
    return Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    // TODO 确定后台的CODE码
    if (response.status === 200 && response.config.responseType === "arraybuffer") {
      // 文件类型特殊处理
      return response;
    } else if (res.Code != 1) {
      // TODO 确定后台的CODE码
      if (res.Code == 10000) {
        if (!showLoginMessageBox) {
          showLoginMessageBox = true;
          Dialog.create({
            title: "登出",
            message: "抱歉，你的账户信息已失效，你需要重新登录使用",
            persistent: true
          }).onOk(() => {
            removeAuth()
              .then(() => {
                location.reload(); // 为了重新实例化vue-router对象 避免bug
              })
              .catch(() => {
                location.reload();
              });
          });
        }
      } else {
        if (res.Message) {
          Notify.create({
            icon: "error",
            color: "negative",
            message: res.Message,
            position: "top"
          });
        }
      }
      return Promise.reject(res);
    } else {
      return res;
    }
  },
  error => {
    Notify.create({
      icon: "error",
      color: "negative",
      message: "网络请求失败，请稍候再试",
      position: "top"
    });
    return Promise.reject(error);
  }
);

export default service;
