// 判断工具函数

import { cloneDeep } from "./cloneDeep";

const toString = Object.prototype.toString;

/**
 * 判断对应基础类型
 * @param val 值  
 * @param type 基础类型
 */
export function is(val: unknown, type: string) {
    return toString.call(val) === `[object ${type}]`
}

/**
 * 判断是否是数值类型
 */
export function isNumber(val: unknown): val is number {
    return is(val, 'Number');
}

/**
 * 判断是否是字符类型
 */
export function isString(val: unknown): val is number {
    return is(val, 'String');
}
export function isStrings(val: unknown): val is string {
    return is(val, 'String');
}

/**
 * 判断是否是Boolean类型
 */
export function isBoolean(val: unknown): val is Boolean {
    return is(val, 'Boolean');
}

/**
 * 判断是否为数组
 */
export function isArray(val: any): val is Array<any> {
    return val && Array.isArray(val);
}

// 判断是否为UUID
export function isUUIDv4(str) {
    // 判断字符串是否为 UUID 格式的字符串
    const regex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
    return regex.test(str)
}

/**
 * 判断是否为对象
 */
export function isObject(val) {
    return is(val, 'Object');
}

/**
 * 判断对象是否为 File 文件
 * @param obj 
 * @returns 
 */
export function isFile(obj) {
    return obj instanceof File;
}

/**
 * 判断是否支持Blob
 * @returns 
 */
export function isBlobSupported() {
    return typeof Blob !== 'undefined';
}

/**
 * 判断对象是否有key值
 */
export function isObjectKeys(row: Recordable) {
    // if (row._self) {
    //     console.log(row._self.refs, ":row");
    // }
    if (!isObject(row)) return false
    const obj = cloneDeep(row)
    // console.log(obj, ":obj");
    const isFlag = Object.keys(row).map(item => row[item]).some(item2 => item2)
    return !isFlag
}

/**
 * 判断是否为数组且length大于0
 */
export function isArrayLength(arr: Recordable): arr is Array<Recordable> {
    return arr && Array.isArray(arr) && arr.length > 0;
}

/**
 * 判断是否为正整数，且包裹0
 */
export function isNonNegativeInteger(num) {
    return Number.isInteger(num) && num >= 0;
}

export function format(str, splitor = ',') {
    if (str == '' || str == null) return ''
    var arr = str.split(/,|，| |\r|\n/)
    if (arr.length > 0) {
        var newVal = ''
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == '') continue
            newVal += arr[i].trim() + splitor
        }
        return newVal
    } else {
        return ''
    }
}

/**
 * 判断是否为函数
 */
export function isFunction(val: unknown): val is Function {
    return typeof val === 'function';
}

/**
 * 四舍五入小数点后几位的值
 * @param {*} num
 * @param {*} decimals
 * @returns
 */
export function roundToDecimals(num, decimals) {
    const factor = Math.pow(10, decimals)
    return Math.round(num * factor) / factor
}