<template>
  <n-dropdown
    :show="showDropdown"
    :x="x"
    :y="y"
    :options="options"
    placement="bottom-start"
    trigger="manual"
    @select="handleSelect"
    @clickoutside="hide"
  />
</template>

<script setup lang="ts">
import { ref, computed, h } from 'vue';
import { NDropdown } from 'naive-ui';
import SolarTrashBinTrashLinear from '~icons/solar/trash-bin-trash-linear';
import SolarEyeOutline from '~icons/solar/eye-outline';
import SolarLayersMinimalisticLinear from '~icons/solar/layers-minimalistic-linear';

type ShowData = {
  eventElement: MouseEvent;
  showRename: boolean;
  /** 置于底层 回调 */
  editIndexBack?: () => void;
  /** 恢复问题 */
  renameCallBack?: () => void;
  /** 删除成功时回调 */
  deleteCallBack?: () => void;
};

const showDropdown = ref(false);
const x = ref(0);
const y = ref(0);
const currentCallbacks = ref<Partial<ShowData>>({});

const options = computed(() => {
  const opts = [
    {
      label: '置于底层',
      key: 'editIndex',
      icon: () => h(SolarLayersMinimalisticLinear)
    }
  ];

  if (currentCallbacks.value.showRename) {
    opts.push({
      label: '恢复问题',
      key: 'rename',
      icon: () => h(SolarEyeOutline),
      props: { class: 'text-red-500' }
    });
  }

  opts.push({
    label: '删除',
    key: 'delete',
    icon: () => h(SolarTrashBinTrashLinear),
    props: { class: 'text-red-500' }
  });

  return opts;
});

function show(data: ShowData) {
  showDropdown.value = true;
  x.value = data.eventElement.clientX;
  y.value = data.eventElement.clientY;
  currentCallbacks.value = data;
}

function hide() {
  showDropdown.value = false;
}

function handleSelect(key: string) {
  hide();
  switch (key) {
    case 'editIndex':
      currentCallbacks.value.editIndexBack?.();
      break;
    case 'rename':
      currentCallbacks.value.renameCallBack?.();
      break;
    case 'delete':
      currentCallbacks.value.deleteCallBack?.();
      break;
  }
}

defineExpose({
  show,
  hide
});
</script>
