<template>
  <!-- FIXED: 从 vue 3.1.5 升级到 3.2.1 时这里出错了，slot也要有key -->
  <a-button v-bind="newAttrs" :loading="inInterval" @click="insideClick">
    <template v-for="(_, slot) of $slots" #[slot]="scope" :key="slot">
      <slot v-bind="asAny(scope)" :key="slot" :name="asAny(slot)" />
    </template>
    <!-- <slot name="default" /> -->
  </a-button>
</template>

<script lang="ts">
export default {
  inheritAttrs: false,
};
</script>

<script setup lang="ts">
import { reactive, useAttrs, watch } from "vue";

// 默认loading一秒，以免重复点击
const { clickTimeout = 1000 } = defineProps<{ clickTimeout?: number }>();

const attrs = useAttrs();
let newAttrs: typeof attrs = reactive({});
Object.assign(newAttrs, attrs);
let parentOnClick = attrs.onClick as (e: Event) => void;
delete newAttrs["onClick"];
watch(
  () => attrs,
  () => {
    Object.assign(newAttrs, attrs);
  },
  { deep: true }
);
let inInterval = $ref(false);
const insideClick = (e: PointerEvent | MouseEvent) => {
  // console.log(e.pointerType);
  // 不允许键盘触发按钮事件，因为全局监听键盘事件的太多了
  if (e instanceof PointerEvent && e.pointerType === "") return;
  inInterval = true;
  // false warning
  // eslint-disable-next-line @typescript-eslint/no-unsafe-argument
  setTimeout(() => (inInterval = false), clickTimeout);
  parentOnClick(e);
  // 确保焦点不停留在此处，以免Enter键触发
  if (e.target instanceof HTMLElement) e.target.blur();
};

function asAny(input: any): any {
  return input;
}
</script>
