import { debounce } from "lodash-es";
import { createDiscreteApi } from "naive-ui";
import { customRef, type Ref } from "vue";

export const { message, notification, dialog, loadingBar, modal } =
  createDiscreteApi([
    "message",
    "dialog",
    "notification",
    "loadingBar",
    "modal",
  ]);

/**
 * 判断是否是外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

/**
 * 一个防抖的ref
 * @param value 初始值
 * @param delay 延迟时间
 * @returns 响应式对象
 */
export const debounceRef = <T>(value: T, delay = 1000): Ref<T> => {
  return customRef((track, trigger) => {
    let timer: number;
    return {
      get() {
        // 收集依赖
        track();
        return value;
      },
      set(newValue) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          value = newValue;
          // 触发更新
          trigger();
        }, delay);
      },
    };
  });
};
