import Axios from 'axios';
import { ElMessage, ElLoading } from 'element-plus';
import { getAppEnvConfig } from '../env';
import { AxiosCanceler } from './axiosCancel';
import { stringify } from 'qs';
import router from '@/router';
import { useUserStore } from '@/stores/modules/user';
import { LOGIN_URL } from '@/config';
import { saveAs } from 'file-saver';
const envs = getAppEnvConfig();
const defaultConfig = {
  baseURL: envs.VITE_GLOB_API_URL_PREFIX,
  timeout: 600000,
  // 数组格式参数序列化（https://github.com/axios/axios/issues/5142）
  paramsSerializer: {
    serialize: stringify,
  },
};

let loadingRequestCount = 0;
let loadingInstance;
const showLoading = () => {
  if (loadingRequestCount === 0) {
    loadingInstance = ElLoading.service({ target: '#app' });
  }
  loadingRequestCount += 1;
};
const hideLoading = () => {
  if (loadingRequestCount <= 0) return;
  loadingRequestCount -= 1;
  if (loadingRequestCount === 0) {
    // nextTick(() => {
    loadingInstance.close();
    // })
  }
};

const axiosCanceler = new AxiosCanceler();

class RequestClient {
  constructor(config = {}) {
    this.instance = Axios.create(Object.assign(defaultConfig, config));

    this.instance.interceptors.request.use(
      (config) => {
        if (window.location.href.includes('data-screen')) {
        } else {
          showLoading();
        }
        if (config.cancel == null) {
          config.cancel = true;
        }
        config.cancel && axiosCanceler.addPending(config);
        const { tenant } = useUserStore();
        // 设置调解中心请求头
        config.headers['tenantId'] = tenant?.id;

        if (config.method.toLocaleUpperCase() == 'GET') {
          config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        }
        console.log('request-----', config);
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    this.instance.interceptors.response.use(
      (response) => {
        if (window.location.href.includes('data-screen')) {
        } else {
          hideLoading();
        }
        const { data, config } = response;
        axiosCanceler.removePending(config);
        const userStore = useUserStore();
        if (data.code === 500 && data.message.includes('token')) {
          // if (data.code === 200) {
          userStore.logoutPass();
          window.location.href = LOGIN_URL;
          ElMessage({
            message: '登录失效，请重新登录',
            type: 'error',
            plain: true,
          });
          return Promise.reject(data);
        }
        // 登录失效
        if (data.code === 404) {
          userStore.logoutPass();
          window.location.href = LOGIN_URL;
          ElMessage({
            message: '登录失效，请重新登录',
            type: 'error',
            plain: true,
          });
          return Promise.reject(data);
        }

        // 全局拦截请求错误信息
        if (data.code && data.code !== 200) {
          ElMessage({
            message: data.message,
            type: 'error',
            plain: true,
          });
          return Promise.reject(data);
        }

        return data;
      },
      (error) => {
        if (window.location.href.includes('data-screen')) {
        } else {
          hideLoading();
        }
        const { response } = error;
        // 请求超时 && 网络错误单独判断，没有 response
        if (error.message.indexOf('timeout') !== -1)
          ElMessage.error({ message: '请求超时！请您稍后重试', plain: true });
        if (error.message.indexOf('Network Error') !== -1)
          ElMessage.error({ message: '网络错误！请您稍后重试', plain: true });
        // 根据服务器响应的错误状态码，做不同的处理
        if (response) checkStatus(response.status);
        // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) router.replace('/500');
      }
    );
  }

  get(url, params, _object = {}) {
    return this.instance.get(url, { params, ..._object });
  }
  post(url, data, _object = {}) {
    return this.instance.post(url, data, _object);
  }
  put(url, data, _object = {}) {
    return this.instance.put(url, data, _object);
  }
  delete(url, params, _object = {}) {
    return this.instance.delete(url, { params, ..._object });
  }
  download(url, params, _object = {}) {
    return this.instance.post(url, params, { ..._object, responseType: 'blob' });
  }
}

/**
 * @description: 校验网络请求状态码
 * @param {Number} status
 * @return void
 */
export const checkStatus = (status) => {
  switch (status) {
    case 400:
      ElMessage.error({ message: '请求失败！请您稍后重试', plain: true });
      break;
    case 401:
      ElMessage.error({ message: '登录失效！请您重新登录', plain: true });
      break;
    case 403:
      ElMessage.error({ message: '当前账号无权限访问！', plain: true });
      break;
    case 404:
      ElMessage.error({ message: '你所访问的资源不存在！', plain: true });
      break;
    case 405:
      ElMessage.error({ message: '请求方式错误！请您稍后重试', plain: true });
      break;
    case 408:
      ElMessage.error({ message: '请求超时！请您稍后重试', plain: true });
      break;
    case 500:
      ElMessage.error({ message: '服务异常！', plain: true });
      break;
    case 502:
      ElMessage.error({ message: '网关错误！', plain: true });
      break;
    case 503:
      ElMessage.error({ message: '服务不可用！', plain: true });
      break;
    case 504:
      ElMessage.error({ message: '网关超时！', plain: true });
      break;
    default:
      ElMessage.error({ message: '请求失败！', plain: true });
  }
};

// 通用下载方法
export function download(url, params, filename) {
  const downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  return new RequestClient()
    .get(url, params, {
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
    })
    .then(async (data) => {
      const blob = new Blob([data]);
      saveAs(blob, filename);
      downloadLoadingInstance.close();
    })
    .catch((r) => {
      console.error(r);
      ElMessage.error('下载文件出现错误，请联系管理员！');
      downloadLoadingInstance.close();
    });
}

export default new RequestClient();
