/**
 * 基础类型判断
 */
export default {
  isFun(o) {
    return o && typeof o === 'function';
  },
  isNull(o) {
    return o === null || o === undefined;
  },
  isEmpty(s) {
    return this.isNull(s) || s === '';
  },
  isArray(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]'
  },
  isNumber(val) {
    return typeof val === 'number' && !isNaN(val) && isFinite(val);
  },
  isString(val) {
    return typeof val === 'string';
  },
  isBoolean(val) {
    return typeof val === 'boolean';
  },
  isObject(val) {
    return val !== null && typeof val === 'object';
  },
  isPromise(o) {
    return o && typeof o.then === 'function';
  },
  /**
   * 转换为字符串
   * @param {any} v 要转换的值 
   * @param {string} [defValue] 转换失败返回的默认值，默认为 ""
   * @param {boolean} [alert] 是否报错，默认false
   * @returns {string} 
   */
  toStr(v, defValue = '', alert) {
    if (typeof v === 'string') {
      return v;
    }
    if (this.isNull(v)) {
      return defValue;
    }
    try {
      return JSON.stringify(v);
    } catch (e) {
      if (alert) throw (e);
      console.warn('toStr fail', e, v);
      return defValue;
    }
  },

  /**
   * 字符串可重新包裹字符串
   */
  toString(v, defValue = '', alert) {
    if (typeof v === 'string') {
      return JSON.stringify(v);
    }
    return this.toStr(v, defValue, alert);
  },

  /**
   * 转换为数字
   * @param {any} v 要转换的值
   * @param {*} defValue 转换失败后返回的值，默认为0
   * @returns {number}
   */
  toNumber(v, defValue = 0, alert) {
    try {
      const res = Number(v);
      return !isNaN(res) ? res : defValue;
    } catch (e) {
      if (alert) throw (e);
      console.warn('toNumber fail', e, v);
      return defValue;
    }
  },
  /**
   * 转换为布尔值
   * @param {any} v 要转换的值
   * @param {boolean} [defValue] 转换失败后的结果，默认false
   * @param {boolean} [alert] 是否报错，默认false
   * @returns {boolean}
   */
  toBoolean(v, defValue = false, alert) {
    try {
      return !!JSON.parse(v);
    } catch (e) {
      if (alert) throw (e);
      console.warn('toBoolean fail', e, v);
      return !!v || defValue;
    }
  },
  /**
   * 转换为Object
   * @param {any} v 要转换的值
   * @param {Object} [defValue] 转换失败返回的默认值，默认为 null
   * @param {boolean} [alert] 是否报错，默认false
   * @returns {Object}
   */
  toObject(v, defValue = null, alert) {
    if (typeof v === 'object') {
      return v || defValue;
    }
    try {
      return JSON.parse(v);
    } catch (e) {
      if (alert) throw (e);
      return defValue;
    }
  },
};

