import axios from 'axios';
import store from '@/store';

import { Message } from 'element-ui';
import { getToken } from '@/utils/auth';

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

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json';
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    const { code, status, message, error } = res;
    if (code === 404) {
      Message({
        message: '请求的资源不存在',
        type: 'error',
        duration: 3 * 1000,
      });

      return Promise.reject(new Error(message || 'Error'));
    }

    // 返回数据失败
    if (status === 0) {
      Message({
        message: `${error}`,
        type: 'error',
        duration: 3 * 1000,
      });

      return Promise.reject(new Error(`${error}` || 'Error'));
    }

    // 无效的操作用户
    if (status === -1) {
      Message({
        message: error,
        type: 'error',
        duration: 3 * 1000,
      });
      store.dispatch('user/signOut');
      const match = /#\/(.*?)\?/.exec(window.location.hash); // 使用 exec 方法进行匹配

      // 答题跳转链接
      let extractedString = '';
      if (match && match.length > 1) {
        extractedString = match[1];
      }
      // 答题链接特殊处理
      if (extractedString === 'open/share/exercise') {
        return Promise.reject(new Error(`${error}` || 'Error'));
      }
      window.location.href = '/';
    }

    return res;
  },
  (error) => {
    if (error.code === 'ERR_CANCELED') {
      return Message.success('取消上传成功');
    }

    Message({
      message: error.message,
      type: 'error',
      duration: 3 * 1000,
    });

    return Promise.reject(error);
  },
);

/**
 * 得到必需的请求参数
 * @returns {object} 返回必需的请求参数
 * */
function getRequestParams() {
  const token = getToken();

  return {
    AccessToken: token?.access_token ?? '',
    UserCode: token?.user_code ?? '',
    UserType: token?.user_type ?? '',
    SessionID: token?.session_id ?? '',
  };
}

/**
 * @description http 请求封装
 */
export const http = {
  /**
   * @param {String} url 请求地址
   * @param {object} config 请求配置
   */
  get: (url, config) => service.get(url, config),
  /**
   * @param {string} url 请求地址
   * @param {object} data 请求数据
   * @param {object} config 请求配置
   */
  post: (url, data = {}, config = {}) => {
    config.params = {
      ...config.params,
      ...getRequestParams(),
    };
    return service.post(url, data, config);
  },
  postForm: (url, data = {}, config = {}) => {
    config.params = {
      ...config.params,
      ...getRequestParams(),
    };
    return service.postForm(url, data, config);
  },
  put: (url, data, config) => service.put(url, data, config),
  delete: (url, data, config) => service.delete(url, data, config),
};
