/* eslint-disable no-console */
/* eslint-disable no-param-reassign */

import _ from 'lodash';
import Axios from 'axios';
import { Util, Error } from 'naf-core';
// import { Indicator } from 'mint-ui';
import type { IOptionsType, IQueryType, IRequestResult } from './types.util';

const { trimData, isNullOrUndefined } = Util;
const { ErrorCode } = Error;

let currentRequests = 0;

// // 参数类型设置
// type valueType = string | number | object | boolean | Array<any>;
// type queryType = string | number | boolean;

// export interface IQueryType {
//   [props: string]: queryType;
// }
// export interface IOptionsType {
//   [props: string]: valueType;
// }

// export interface IRequestResult {
//   errcode: string | number;
//   errmsg: string | number;
//   details?: string;
//   [props: string]: any;
// }

export class AxiosWrapper {
  constructor({ baseUrl = import.meta.env.VITE_REQUEST_BASE, unwrap = true } = {}) {
    this.baseUrl = baseUrl;
    this.unwrap = unwrap;
  }
  baseUrl: string;
  unwrap: boolean;

  // 替换uri中的参数变量
  static merge(uri: string, query: IQueryType) {
    if (!uri.includes(':')) {
      return uri;
    }
    const keys = [];
    const regexp = /\/:([a-z0-9_]+)/gi;
    let res;
    // eslint-disable-next-line no-cond-assign
    while ((res = regexp.exec(uri)) != null) {
      keys.push(res[1]);
    }
    keys.forEach((key) => {
      const val = _.get(query, key);
      if (!isNullOrUndefined(val)) {
        uri = uri.replace(`:${key}`, `${val}`);
      }
    });
    return uri;
  }

  $get(uri: string, query?: IQueryType, options?: IOptionsType) {
    return this.$request(uri, undefined, query, options);
  }

  $post(uri: string, data: object = {}, query?: IQueryType, options?: IOptionsType) {
    return this.$request(uri, data, query, options);
  }
  $delete(uri: string, data: object = {}, query?: IQueryType, options: IOptionsType = {}) {
    options = { ...options, method: 'delete' };
    return this.$request(uri, data, query, options);
  }
  async $request(uri: string, data?: object, query?: IQueryType, options?: IOptionsType) {
    if (query && _.isObject(query)) {
      const keys = Object.keys(query);
      for (const key of keys) {
        const val = _.get(query, key);
        if (val === '') {
          delete query[key];
        }
      }
    }
    if (_.isObject(query) && _.isObject(options)) {
      options = { ...options, params: query, method: 'get' };
    } else if (_.isObject(query) && !query.params) {
      options = { params: query };
    } else if (_.isObject(query) && query.params) {
      options = query;
    }
    if (!options) options = {};
    if (options.params) options.params = trimData(options.params, null, null);
    const params = _.get(options, 'params');
    const url = AxiosWrapper.merge(uri, params as IQueryType);
    currentRequests += 1;
    // Indicator.open({
    //   spinnerType: 'fading-circle',
    // });
    try {
      let returnData: any;
      const axios = Axios.create({
        baseURL: this.baseUrl,
      });
      // if (util.token && util.token !== null) axios.defaults.headers.common.Authorization = util.token;
      const token = localStorage.getItem('token');
      const apiToken = sessionStorage.getItem('apiToken');
      if (token) axios.defaults.headers.common['token'] = token;
      if (apiToken) axios.defaults.headers.common['api-token'] = apiToken;
      const res = await axios.request({
        method: isNullOrUndefined(data) ? 'get' : 'post',
        url,
        data,
        responseType: 'json',
        ...options,
      });
      const returnRes: IRequestResult = res.data;
      const { errcode, errmsg, details } = returnRes;
      if (errcode) {
        console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
        return returnRes;
      }
      // unwrap data
      if (this.unwrap) {
        returnData = returnRes;
      }
      // 处理apiToken
      const { apiToken: at, ...others } = returnData;
      if (at) sessionStorage.setItem('apiToken', at);
      return others;
    } catch (err: any) {
      let errmsg = '接口请求失败，请稍后重试';
      if (err.response) {
        const { status } = err.response;
        if (status === 401) errmsg = '用户认证失败，请重新登录';
        if (status === 403) errmsg = '当前用户不允许执行该操作';
      }
      console.error(
        `[AxiosWrapper] 接口请求失败: ${err.config && err.config.url} - 
        ${err.message}`
      );
      return { errcode: ErrorCode.SERVICE_FAULT, errmsg, details: err.message };
    } finally {
      /* eslint-disable */
      currentRequests -= 1;
      if (currentRequests <= 0) {
        currentRequests = 0;
        // Indicator.close();
      }
    }
  }
}
