import type { RouteLocationNormalized, RouteRecordNormalized } from "vue-router";
import { isArrayLength } from "./is";

/**
 * 整理当前路由信息
 */
export function getRawRoute(route: RouteLocationNormalized): RouteLocationNormalized {
    if (!route) return route;
    const { matched, ...opt } = route;
    return {
        ...opt,
        matched: (matched
            ? matched.map((item) => ({
                meta: item.meta,
                name: item.name,
                path: item.path,
            }))
            : undefined) as RouteRecordNormalized[],
    };
}

/**
 * 创建新浏览器标签跳转
 * @param goUrl 跳转路由
 */
export function openUrl(goUrl: string, params = {}) {
    // 参数拼接
    const queryParams = Object.keys(params).length > 0 ? new URLSearchParams(params).toString() : ''
    const paramUrl = queryParams ? '?' + queryParams : ''
    // 前缀
    const hash = window.location.hash.includes('#') ? '/#' : ''
    // url
    const url = `${window.location.origin}${hash}/${goUrl}${paramUrl}`
    // window.open(url, '_blank');
    const targetWindow = window.open(url, "scrollbars=yes,resizable=1,modal=false,alwaysRaised=yes")
    return targetWindow
}

/**
 * 获取url中的参数
 */
export function getURLParams(url: string) {
    const params: Recordable = {};
    const urlWithoutQuery = url.split('?')[1];

    if (urlWithoutQuery) {
        const paramPairs = urlWithoutQuery.split('&');

        paramPairs.forEach(pair => {
            const [key, value] = pair.split('=');
            params[key] = value;
        });
    }

    return params;
}

/**
 * 扁平化菜单数据
 * @param arr 
 * @returns 
 */
export function flattenMenuArray<T = any>(arr: Recordable[]): T[] {
    if(!isArrayLength(arr)) return []
    let result: Recordable[] = [];
    arr.forEach(function (item: Recordable) {
        result.push({ value: item.id, label: item.name || item.label });
        if (item.children && item.children.length > 0) {
            result = result.concat(flattenMenuArray(item.children));
        }
    });
    return result as T[];
}

/**
 * 函数节流
 * @param {*} func
 * @param {*} delay
 * @returns
 */
export function defineThrottle(callback, delay) {
    let timeoutId
    let lastTriggerTime = 0
    return function () {
      const now = Date.now()
      if (now - lastTriggerTime >= delay) {
        lastTriggerTime = now
        callback()
      } else {
        clearTimeout(timeoutId)
        timeoutId = setTimeout(callback, delay)
      }
    }
  }