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

import _, { head } from 'lodash';
import { Util, Error } from 'naf-core';
// import { Indicator } from 'mint-ui';
import util from './user-util';

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

let currentRequests = 0;

export default class UniRequestWrapper {
  constructor({ baseUrl = '', unwrap = true } = {}) {
    this.baseUrl = baseUrl;
    this.unwrap = unwrap;
  }

  // 替换uri中的参数变量
  static merge(uri, query = {}) {
    const keys = Object.keys(query);
    if (keys.length > 0) uri = `${uri}?`;
    else return uri;
    const qarr = [];
    keys.forEach((key) => {
      if (!isNullOrUndefined(query[key])) {
        qarr.push(`${key}=${query[key]}`);
      }
    });
    uri = `${uri}${qarr.join('&')}`;
    return uri;
  }

  $get(uri, query, options) {
    return this.$request(uri, null, query, options);
  }

  $post(uri, data = {}, query, options) {
    return this.$request(uri, data, query, options);
  }
  $delete(uri, data = {}, router, query, options = {}) {
    options = { ...options, method: 'delete' };
    return this.$request(uri, data, query, options, router);
  }
  async $request(uri, data, query, options) {
    // TODO: 合并query和options
    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);
    const url = UniRequestWrapper.merge(uri, options.params);
    currentRequests += 1;
    // Indicator.open({
    //   spinnerType: 'fading-circle',
    // });

    try {
      const header = {};
      if(uni.getStorageSync('token')) {
        header.Authorization = uni.getStorageSync('token');
      }
      let [err, result] = await uni.request({
        method: isNullOrUndefined(data) ? 'get' : 'post',
        url: `${this.baseUrl}${url}`,
        data,
        responseType: 'json',
        ...options,
        header,
      });
      const { data: res } = result;
      const { errcode, errmsg, details } = res;
      if (errcode) {
        console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
        return res;
      }
      let ret = null;
      // unwrap data
      if (this.unwrap) {
        ret = _.omit(res, ['errmsg', 'details']);
        const keys = Object.keys(ret);
        if (keys.length === 1 && keys.includes('data')) {
          ret = res.data;
        }
      }
      return ret;
    } catch (err) {
      let errmsg = '接口请求失败，请稍后重试';
      if (err.response) {
        const { status } = err.response;
        if (status === 401) errmsg = '用户认证失败，请重新登录';
        if (status === 403) errmsg = '当前用户不允许执行该操作';
      }
      console.error(
        `[UniRequestWrapper] 接口请求失败: ${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();
      }
    }
  }
}
