// 日期格式化
export function parseTime(time: any, pattern?: string): string {
    if (arguments.length === 0 || !time) {
        return '';
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
            time = parseInt(time);
        } else if (typeof time === 'string') {
            time = time
                .replace(new RegExp(/-/gm), '/')
                .replace('T', ' ')
                .replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if (typeof time === 'number' && time.toString().length === 10) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj: { [key: string]: any } = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    return format.replace(/{(y|m|d|h|i|s|a)+}/g, (result: string, key: string) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value];
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
}

/**
 * 添加日期范围
 * @param params
 * @param dateRange
 * @param propName
 */
export const addDateRange = (params: any, dateRange: any[], propName?: string) => {
    const search = params;
    search.params = typeof search.params === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
    dateRange = Array.isArray(dateRange) ? dateRange : [];
    if (typeof propName === 'undefined') {
        search.params['beginTime'] = dateRange[0];
        search.params['endTime'] = dateRange[1];
    } else {
        search.params['begin' + propName] = dateRange[0];
        search.params['end' + propName] = dateRange[1];
    }
    return search;
};

// 回显数据字典
export const selectDictLabel = (datas: any, value: number | string) => {
    if (value === undefined) {
        return '';
    }
    const actions = [];
    Object.keys(datas).some((key) => {
        if (datas[key].value == '' + value) {
            actions.push(datas[key].label);
            return true;
        }
    });
    if (actions.length === 0) {
        actions.push(value);
    }
    return actions.join('');
};

// 回显数据字典（字符串数组）
export const selectDictLabels = (datas: any, value: any, separator: any) => {
    if (value === undefined || value.length === 0) {
        return '';
    }
    if (Array.isArray(value)) {
        value = value.join(',');
    }
    const actions: any[] = [];
    const currentSeparator = undefined === separator ? ',' : separator;
    const temp = value.split(currentSeparator);
    Object.keys(value.split(currentSeparator)).some((val) => {
        let match = false;
        Object.keys(datas).some((key) => {
            if (datas[key].value == '' + temp[val]) {
                actions.push(datas[key].label + currentSeparator);
                match = true;
            }
        });
        if (!match) {
            actions.push(temp[val] + currentSeparator);
        }
    });
    return actions.join('').substring(0, actions.join('').length - 1);
};

// 字符串格式化(%s )
export function sprintf(str: string) {
    if (arguments.length !== 0) {
        let flag = true,
            i = 1;
        str = str.replace(/%s/g, function () {
            const arg = arguments[i++];
            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    }
}

// 转换字符串，undefined,null等转化为""
export const parseStrEmpty = (str: any) => {
    if (!str || str == 'undefined' || str == 'null') {
        return '';
    }
    return str;
};

// 数据合并
export const mergeRecursive = (source: any, target: any) => {
    for (const p in target) {
        try {
            if (target[p].constructor == Object) {
                source[p] = mergeRecursive(source[p], target[p]);
            } else {
                source[p] = target[p];
            }
        } catch (e) {
            source[p] = target[p];
        }
    }
    return source;
};

/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export const handleTree = <T>(data: any[], id?: string, parentId?: string, children?: string): T[] => {
    const config: {
        id: string;
        parentId: string;
        childrenList: string;
    } = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
    };

    const childrenListMap: any = {};
    const nodeIds: any = {};
    const tree: T[] = [];

    for (const d of data) {
        const parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
            childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
    }

    for (const d of data) {
        const parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
            tree.push(d);
        }
    }
    const adaptToChildrenList = (o: any) => {
        if (childrenListMap[o[config.id]] !== null) {
            o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
            for (const c of o[config.childrenList]) {
                adaptToChildrenList(c);
            }
        }
    };

    for (const t of tree) {
        adaptToChildrenList(t);
    }

    return tree;
};


// 验证是否为blob格式
export const blobValidate = (data: any) => {
    return data.type !== 'application/json';
};
/**
 * 将字节转成B  KB MB GB
 * @param byte number
 * @returns string
 */
export const changeByte = (byte: number) => {
    let size = '';
    if (byte < 0.1 * 1024) {
        // 小于0.1KB，则转化成B
        size = `${byte.toFixed(2)}B`;
    } else if (byte < 0.1 * 1024 * 1024) {
        // 小于0.1MB，则转化成KB
        size = `${(byte / 1024).toFixed(2)}KB`;
    } else if (byte < 0.1 * 1024 * 1024 * 1024) {
        // 小于0.1GB，则转化成MB
        size = `${(byte / (1024 * 1024)).toFixed(2)}MB`;
    } else {
        // 其他转化成GB
        size = `${(byte / (1024 * 1024 * 1024)).toFixed(2)}GB`;
    }

    const sizeStr = `${size}`; // 转成字符串
    const index = sizeStr.indexOf('.'); // 获取小数点处的索引
    const dou = sizeStr.substr(index + 1, 2); // 获取小数点后两位的值
    // eslint-disable-next-line eqeqeq
    if (dou == '00') {
        // 判断后两位是否为00，如果是则删除00
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
    }
    return size;
};
export function calculateTransparency(color: string, alpha: number): string {
    // 将颜色转换为RGBA或HSLA格式
    const colorType = color.startsWith('#') ? 'rgba' : 'hsla';
    const r = parseInt(color.substring(1, 3), 16);
    const g = parseInt(color.substring(3, 5), 16);
    const b = parseInt(color.substring(5, 7), 16);
    const a = alpha / 100; // 将百分比转换为小数

    if (colorType === 'rgba') {
        return `${colorType}(${r}, ${g}, ${b}, ${a})`;
    } else {
        // 假设颜色是六位数的HSLA格式
        const l = parseInt(color.substring(7, 9), 16);
        return `${colorType}(${r}, ${g}%, ${l}%, ${a})`;
    }
}

export const dataURLtoBlob = (base64Buf: string): Blob => {
    const arr = base64Buf.split(',');
    const typeItem = arr[0];
    const mime = typeItem.match(/:(.*?);/)![1];
    const bstr = atob(arr[1]);
    const u8arr = new Uint8Array(bstr.length);
    for (let i = 0; i < bstr.length; i++) {
        u8arr[i] = bstr.charCodeAt(i);
    }
    return new Blob([u8arr], { type: mime });
};
export const fileExt = (fileName: string) => {
    // 获取文件后缀， 从后面到第一个点取 不包括.
    return fileName.slice(fileName.lastIndexOf('.') + 1);
};

// 获取随机数
export const getRandomNumber = (min: number, max: number): number => {
    return Math.floor(Math.random() * (max - min + 1)) + min;
};
// 获取随机颜色
export const getRandomColor = (): string => {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
};

// 判断地址url是否是一个url连接
export const isUrl = (url: string): boolean => {
    const pattern = /^(?:https?:\/\/)?(?:www\.)?[^\s.]+\.[^\s]{2,}$/i;
    return pattern.test(url);
};

// 获取一个唯一的uuid共20位
export const getUuid = (): string => {
    return new Date().getTime().toString(16) + Math.random().toString(16).slice(2);
};

// 正整数阿拉伯数字转换成中文数字
export const numberToChinese = (num: number): string => {
    const chineseNums = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    const chineseUnits = ['', '十', '百', '千', '万', '亿'];

    if (num === 0) {
        return chineseNums[0];
    }

    let result = '';
    let count = 0;

    while (num > 0) {
        const digit = num % 10;
        if (digit !== 0) {
            result = chineseNums[digit] + chineseUnits[count] + result;
        } else if (result[0] !== chineseNums[0]) {
            result = chineseNums[digit] + result;
        }
        num = Math.floor(num / 10);
        count++;
    }

    return result;
};

export const getProperty = (obj: any, path: string) => {
    const properties = path.split('.');
    let value = obj;
    for (const prop of properties) {
        // eslint-disable-next-line no-prototype-builtins
        if (value && Object.prototype.hasOwnProperty.call(value, prop)) {
            value = value[prop];
        } else {
            return undefined;
        }
    }
    return value;
};
// 正整数生成7位数字多余前面补0
export const generateNumber = (num: number, lan = 7): string => {
    return num.toString().padStart(lan, '0');
};

// 获取文件后缀名
export const getFileSuffix = (fileName: string): string => {
    if (!fileName) return '';
    const lastDotIndex = fileName.lastIndexOf('.');
    return lastDotIndex !== -1 ? fileName.substring(lastDotIndex + 1) : '';
};
export const recursiveDecode = (input: string, maxDepth: number = 10): string => {
    if (typeof input !== 'string' || input.length === 0) return input;
    
    let prev: string = input;
    
    for (let i = 0; i < maxDepth; i++) {
        let decoded: string;
        try {
            // 先替换 '+' 为 ' '（常见 form 编码场景），再解码
            decoded = decodeURIComponent(prev.replace(/\+/g, ' '));
        } catch (e) {
            // 非法序列或无法解码，停止
            break;
        }
        if (decoded === prev) break;
        prev = decoded;
    }
    
    return prev;
};

// 递归解码对象的类型
type RecursiveDecodeResult<T> = T extends string 
    ? string 
    : T extends Array<infer U> 
        ? Array<RecursiveDecodeResult<U>> 
        : T extends object 
            ? { [K in keyof T]: RecursiveDecodeResult<T[K]> } 
            : T;

export const recursiveDecodeURIComponent = <T>(obj: T): RecursiveDecodeResult<T> => {
    if (typeof obj === 'string') {
        return recursiveDecode(obj) as RecursiveDecodeResult<T>;
    } else if (Array.isArray(obj)) {
        return obj.map((item) => recursiveDecodeURIComponent(item)) as RecursiveDecodeResult<T>;
    } else if (typeof obj === 'object' && obj !== null) {
        const decodedObj: Record<string, any> = {};
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                decodedObj[key] = recursiveDecodeURIComponent((obj as Record<string, any>)[key]);
            }
        }
        return decodedObj as RecursiveDecodeResult<T>;
    }
    return obj as RecursiveDecodeResult<T>;
};

// 或者使用更简单的类型定义，保持函数简洁
export const recursiveDecodeURIComponentSimple = (obj: any): any => {
    if (typeof obj === 'string') {
        return recursiveDecode(obj);
    } else if (Array.isArray(obj)) {
        return obj.map((item) => recursiveDecodeURIComponentSimple(item));
    } else if (typeof obj === 'object' && obj !== null) {
        const decodedObj: Record<string, any> = {};
        for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                decodedObj[key] = recursiveDecodeURIComponentSimple(obj[key]);
            }
        }
        return decodedObj;
    }
    return obj;
};
// 将url提取参数
export const getUrlParams = (url: string): Record<string, string> => {
    if (!url || typeof url !== 'string') {
        return {};
    }
    const params: Record<string, string> = {};
    const queryString = url.split('?')[1];
    if (!queryString) {
        return params;
    }
    const pairs = queryString.split('&');
    for (const pair of pairs) {
        const [key, value] = pair.split('=');
        params[decodeURIComponent(key)] = decodeURIComponent(value || '');
    }
    return params;
}
// 预览图片方法
export const previewImage = (urls: string | string[], current?: string) => {
    const urlList = Array.isArray(urls) ? urls : [urls];
    uni.previewImage({
        urls: urlList,
        current: current || urlList[0],
    });
};

export const selectDictListClass = (datas: any, value: number | string) => {
    if (value === undefined) {
        return '';
    }
    let className = '';
    Object.keys(datas).some((key) => {
        if (datas[key].value == '' + value) {
            className = datas[key].elTagType || '';
            return true;
        }
    });
    return className;
}