import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
import { LocalStorage, Notify } from 'quasar';
import { Pagination } from 'src/api/class';
// import { Router, useRouter } from 'vue-router';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

class Request {
  // axios 实例
  instance: AxiosInstance;
  // 基础配置，url和超时时间
  baseConfig: AxiosRequestConfig = {
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 60000,
    headers: {
      'Content-type': 'application/json;charset="utf-8"'
    }
  };
  constructor() {
    // 使用axios.create创建axios实例
    this.instance = axios.create(this.baseConfig);

    // 请求拦截器
    this.instance.interceptors.request.use(
      (config: AxiosRequestConfig) => {
        // 一般会请求拦截里面加token
        config.headers['token'] = LocalStorage.getItem('token');
        return config;
      },
      (err: unknown) => {
        return Promise.reject(err);
      }
    );

    // 响应拦截器
    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        if (res.config.responseType == 'blob') {
          return Promise.resolve(res);
        }
        if (res.data.isSuccess) {
          if (res.data.message) {
            Notify.create({
              progress: true,
              type: 'positive',
              icon: 'feedback',
              position: 'top',
              message: res.data.message
            });
          }
          return res.data.content;
        } else {
          if (res.data.errorCode === 'needLogin') {
            LocalStorage.remove('token');
            Notify.create({
              progress: true,
              type: 'warning',
              position: 'top',
              icon: 'warning',
              message: '登录超时，请重新登录！'
            });
            window.location.href = '/#/loginIndex';
            // window.location.href = '/#/scannerzebra'; // PDA端
            // const userRouter = useRouter();
            // userRouter.push({ name: 'loginIndex' });
          } else {
            Notify.create({
              progress: true,
              type: 'negative',
              icon: 'feedback',
              position: 'top',
              message: res.data.message
                ? res.data.message
                : '操作错误，请重试或联系管理员！'
            });
            return Promise.reject(res.data.content);
          }
        }
      },
      (err: AxiosResponse) => {
        // 这里用来处理http常见错误，进行全局提示
        let message = '';
        switch (err.status) {
          case 400:
            message = '请求错误(400)';
            break;
          case 401:
            message = '未授权，请重新登录(401)';
            break;
          case 403:
            message = '拒绝访问(403)';
            break;
          case 404:
            message = '请求出错(404)';
            break;
          case 408:
            message = '请求超时(408)';
            break;
          case 500:
            message = '服务器错误(500)';
            break;
          case 501:
            message = '服务未实现(501)';
            break;
          case 502:
            message = '网络错误(502)';
            break;
          case 503:
            message = '服务不可用(503)';
            break;
          case 504:
            message = '网络超时(504)';
            break;
          case 505:
            message = 'HTTP版本不受支持(505)';
            break;
          default:
            message = `连接出错${
              err.status === undefined ? '' : `(${err.status})`
            }!`;
        }
        Notify.create({
          progress: true,
          position: 'top',
          type: 'negative',
          message: message
        });
        return Promise.reject(err.data);
      }
    );
  }

  // 定义请求方法
  public request<T>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config);
  }

  public get<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.get(url, config);
  }

  public postForPage<T>(
    url: string,
    data?: Pagination<T>,
    config?: AxiosRequestConfig
  ): Promise<Common.pageResult<any>> {
    return this.instance.post(url, data, config);
  }

  public post<T>(
    url: string,
    data?: T,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.post(url, data, config);
  }

  public put<T>(
    url: string,
    data?: T,
    config?: AxiosRequestConfig
  ): Promise<T> {
    return this.instance.put(url, data, config);
  }

  public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
    return this.instance.delete(url, config);
  }
}

const request = new Request();

export { request };
