/**
 * 比较常用的工具模块
 * @date 2022-03
 * @author 何华东
 */

import Axios from 'axios';
import { v4 as uuidv4 } from 'uuid';

/**
 * 延迟
 */
export function delay(ms?: number): Promise<void> {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

/**
 * 替换所有字符串
 * 
 * 不支持替换\\n
 */
export function replaceAll(value: string, searchValue: string, replaceValue: string) {
    if (!value || !searchValue || !replaceValue) return value;

    //replace(/'/g, "/'");
    return value.replace(new RegExp(searchValue, 'g'), replaceValue);
}

/**
 * uuidv4
 */
export function uuid() {
    return uuidv4();
}

/**
 * 拦截对象方法的调用
 * @param handler Reflect.apply(target, thisArg, argArray);
 */
export function interceptMethodCall(obj: object, handler: (target: any, p: string | symbol, thisArg: any, argArray: any[]) => Promise<any>) {
    return new Proxy(obj, {
        get(target, p, receiver) {
            if (typeof target[p] !== 'function')
                return Reflect.get(target, p, receiver);

            return new Proxy(target[p], {
                apply: async (target, thisArg, argArray) => {
                    return await handler(target, p, thisArg, argArray);
                }
            });
        }
    });
}

/**
  * 生成insert into sql语句
  */
export function generateInsertSql(tableName: string, entity: object) {
    let keys = Reflect.ownKeys(entity).filter(s => { return entity[s] !== undefined && entity[s] !== null; });

    return `INSERT INTO ${tableName}(${keys.join(',')}) VALUES (${keys.map(s => {
        return typeof entity[s] === 'number' ? entity[s] : `'${entity[s]}'`;
    }).join(',')})`;
}

/**
 * 生成replace into sql语句
 * 
 * 自动跳过syncTime
 */
export function generateReplaceSql(tableName: string, entity: object, excludeFields?: string[]) {
    let keys = Reflect.ownKeys(entity).filter(s => { return entity[s] !== undefined && entity[s] !== null && s !== 'syncTime' && !excludeFields?.includes(s.toString()); });

    return `REPLACE INTO ${tableName}(${keys.join(',')}) VALUES (${keys.map(s => {
        return typeof entity[s] === 'number' ? entity[s] : `'${entity[s]}'`;
    }).join(',')})`;
}

/**
 * 简单的节流器，单位时间内只执行一次
 * 
 * 参考Quasar
 * @param func 要执行的方法
 * @param ms 时间(毫秒),默认一分钟
 */
export function throttle1(func: (...args) => void, ms = 1000 * 60) {
    let wait = false;

    return function (this, ...args) {
        if (wait === false) {
            wait = true;
            setTimeout(() => { wait = false }, ms);
            func.apply(this, args);
        }
    }
}

/**
 * 下载图片并转base64字符串
 */
export async function downloadImg2Base64(imgUrl: string) {
    try {
        return (await Axios.get(imgUrl, { responseType: 'arraybuffer' })).data?.toString('base64');
    } catch (error) {
        return '';
    }
}