import axios from "axios";
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import Qs from "qs";
const JSONbig = require("json-bigint")({ storeAsString: true });
import cookie from "./cookie";
import httpErrorHandler from "./httpErrorHandler";

// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading
let needLoadingRequestCount = 0 // 声明一个对象用于存储请求个数
function startLoading () {
  loading = Vue.prototype.$loading({
    lock: true,
    customClass: 'createLoading',  // 局部class名称
    text: '服务加载中...',
    background: 'rgba(0,0,0,0.5)',
    target: document.querySelector('.loading-area') // 设置加载动画区域
  })
}
function endLoading () {
  loading.close()
}
function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}
function hideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}

const instance = axios.create({
  baseURL: "/m",
  //baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    post: {
      "Content-Type": "application/json;charset=UTF-8",
      dataType: "json",
    },
  },
  transformResponse: [
    (data) => {
      try {
        JSON.parse(data);
        return JSONbig.parse(data);
      } catch (error) {
        return data;
      }
    },
  ],
});
/**
 * 请求拦截器
 */
instance.interceptors.request.use(
  (config) => {
    config.headers.Authorization = window.sessionStorage.getItem("token") || "";

    if (config.isLoading == true) { // 如果配置了isLoading: false，则不显示loading
      showFullScreenLoading()
    }

    return config;
  },
  (err) => {
    hideFullScreenLoading()
    return Promise.reject(err);
  }
);
/**
 * 响应拦截器
 */
instance.interceptors.response.use((response) => {
  hideFullScreenLoading() // 响应成功关闭loading

  return response.data;
}, httpErrorHandler);

/**
 * 封装后的axios post方法
 *
 * @param {string} url 请求路径
 * @param {object} option 请求参数
 * @param {object} [config] 特殊配置项（选填）
 * @returns
 */
export function post(url, option, config = {}) {
  const data = Object.assign({}, option, {
    // __mortals_token__: cookie.getItem('__mortals_token__'),
  });
  return instance.post(url, data, config);
}

/**
 * 封装后的axios get方法
 *
 * @param {string} url 请求路径
 * @param {object} option 请求参数
 * @param {object} [config] 特殊配置项（选填）
 * @returns
 */
export function get(url, option, config = {}) {
  const data = Object.assign({}, option, {
    //__mortals_token__: cookie.getItem('__mortals_token__'),
  });
  return instance.get(url, { params: data }, config);
}

// 文件上传
const uploadInstance = axios.create({
  baseURL: "/m",
  headers: {
    post: {
      "Content-Type": "multipart/form-data",
    },
  },
});

uploadInstance.interceptors.response.use((response) => {
  return response.data;
}, httpErrorHandler);

/**
 * 封装后的axios upload方法
 *
 * @param {string} url 请求路径
 * @param {object} option 请求参数
 * @param {object} [config] 特殊配置项（选填）
 * @returns
 */
export function upload(url, option, config = {}) {
  let formdata = new FormData();
  Object.keys(option).forEach((key) => {
    formdata.append(key, option[key]);
  });
  return uploadInstance.post(url, formdata, config);
}


