/**
 * 工具类
 * nh 2021.12.23
 */

export class toolUtils {
  /**
   * 拼接完整的http请求地址
   * @param baseUrl 根域名地址
   * @param interfaceUrl 接口地址
   * @returns string 完整的http请求地址
   */
  static getBaseHttpUrl(baseUrl: string, interfaceUrl: string) {
    baseUrl =
      baseUrl + (baseUrl.lastIndexOf("/") == baseUrl.length - 1 ? "" : "/");

    var _index = interfaceUrl.indexOf("/") == 0 ? 1 : 0;
    interfaceUrl = interfaceUrl.substring(_index);
    return baseUrl + interfaceUrl;
  }
  static returnNewObj(data, arr, val) {
    if (arr.length > 1) {
      let k = arr.shift();
      if (!data[k]) {
        data[k] = {};
      }
      this.returnNewObj(data[k], arr, val);
    } else {
      let curk = arr[0];
      data[curk] = val;
    }
  }
  static rKeyStrVal(key?, val?) {
    let nk = key,
      arr = [];
    if (val instanceof Object && !(val instanceof Array)) {
      // for(let k in )
      return nk + "." + this.rKeyStrVal();
    }
    return nk;
  }
  /**
   * @param data Object
   * @returns 将对象中 key 为a.b.c 转换为a:{b:{c:''}}
   */
  static formatData(data) {
    let newData = JSON.parse(JSON.stringify(data));
    for (let key in newData) {
      if (key.indexOf(".") > -1) {
        let arr = key.split(".");
        this.returnNewObj(newData, arr, newData[key]);
        delete newData[key];
      }
    }
    return newData;
  }
  /**
   * @param data {a:{b:{c:{}}}}
   *
   * @returns a.b.c
   *
   */
  static desFormatData = (data) => {
    let newData = {};
    for (let key in data) {
      if (data[key] instanceof Object && !(data[key] instanceof Array)) {
        for (let childK in data[key]) {
          let nk = `${key}.${childK}`;
          newData[nk] = data[key][childK];
        }
      } else {
        newData[key] = data[key];
      }
    }
    return newData;
  };

  /**
   * 把object对象中的属性转为url中的参数字符串。比如：{a:1,b:2}转为a=1&b=2
   */
  static objectKeyToUrlParam(_obj: any) {
    var paramStr = '';
    var keyArr = Object.keys(_obj || {});
    keyArr.forEach((_key, _index) => {
      paramStr = paramStr + _key + '=' + _obj[_key] + (_index == keyArr.length - 1 ? '' : '&');
    });
    return paramStr;
  };

  /**
   * 拼装返回给页面的接口调用结果
   * resultStr 结果字符串，成功时为success，否则为失败码
   * data 数据
   * reason 失败时的原因
   */
  static resultConstructor(resultStr, data, reason) {
    return {
      result: resultStr,
      data: data,
      message: reason
    };
  };
}
