<template>
  <Teleport to="body">
    <div class="custom-context-menu" ref="ContextMenu">
      <template v-for="item in list" :key="item.value">
        <div class="menu-item" @click="MenuClick(item)">
          {{ item.label }}
        </div>
      </template>
    </div>
  </Teleport>
</template>

<script lang="ts" setup>
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
const props = withDefaults(
  defineProps<{
    list?: any;
    el?: HTMLElement;
  }>(),
  {
    list: [
      {
        label: '删除',
        value: 'delete',
      },
    ],
  }
);
const emit = defineEmits(['change']);
const ContextMenu = ref();
const MenuClick = (item: any) => {
  emit('change', item);
};
// 鼠标右击事件
const ContextMenuFun = (e) => {
  //   阻止默认事件
  e.preventDefault();
  ContextMenu.value.style.display = 'block'; //点击右键菜单显示出来
  let X = e.clientX + 10;
  let Y = e.clientY + 10;
  ContextMenu.value.style.left = X + 'px';
  ContextMenu.value.style.top = Y + 'px';
};
// 全局点击事件
const GlobalClick = (event) => {
  // 后面改
  if (event.target.tagName == 'li') {
    return;
  }
  //如果点击菜单外的任意位置，菜单被隐藏
  if (ContextMenu.value) {
    ContextMenu.value.style.display = 'none';
  }
};
const CreateMenu = (el: HTMLElement) => {
  el.addEventListener('contextmenu', ContextMenuFun);
  window.addEventListener('click', GlobalClick);
};
onMounted(() => {
  nextTick(() => {
    // 创建一个自定义右键菜单
    if (props.el) {
      CreateMenu(props.el);
    }
  });
});

onBeforeUnmount(() => {
  // 销毁window点击事件
  window.removeEventListener('click', GlobalClick);
  //   销毁元素事件
  if (props.el) {
    props.el.removeEventListener('contextmenu', ContextMenuFun);
  }
});
</script>

<style lang="less">
.custom-context-menu {
  background: rgb(17, 18, 20);
  border-radius: 8px;
  display: none;
  position: fixed;
  cursor: pointer;
  padding: 12px;
  box-sizing: border-box;
  z-index: 1000;
  .menu-item {
    width: 188px;
    color: #ddd;
    height: 30px;
    display: flex;
    align-items: center;
    font-weight: 600;
  }
}
</style>
