<template>
  <div class="vtj-actions" :class="[`is-${props.position}`]">
    <div class="vtj-actions__layers">
      <ElDropdown size="small" @command="handleCommand">
        <div><i class="vtj-icon-layers"></i>{{ props.title }}</div>
        <template #dropdown>
          <ElDropdownMenu v-if="path && path.length">
            <ElDropdownItem
              v-for="item in path"
              :key="item.id"
              :command="item"
              @mouseenter="handleMenuMouseEnter(item)">
              {{ item.name }}
              <i :class="`is-${getNodeType(item)}`">
                {{ getNodeType(item) }}
              </i></ElDropdownItem
            >
          </ElDropdownMenu>
        </template>
      </ElDropdown>
    </div>
    <div v-if="!isRoot && !node.lock" class="vtj-actions__tools">
      <i class="vtj-icon-arrow-up" title="向前移动" @click="handleMovePrev"></i>
      <i
        class="vtj-icon-arrow-down"
        title="向后移动"
        @click="handleMoveNext"></i>
      <i @click="handleCopy" class="vtj-icon-copy" title="复制"></i>
      <i @click="handleRemove" class="vtj-icon-remove" title="删除"></i>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, nextTick } from 'vue';
import {
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElMessageBox
} from 'element-plus';
import { Block, Node, INode, PAGE_NAME, BLOCK_NAME } from '@vtj/engine';

export interface Props {
  position: string; // 'left-top' | 'left-bottom' | 'inner' | 'right-bottom'| 'right-bottom';
  node: Block | Node;
  title: string;
  path: INode[];
}

const props = withDefaults(defineProps<Props>(), {
  position: 'left-top',
  path: () => []
});

const emit = defineEmits(['action', 'move']);

const isRoot = computed(() => props.node?.root === props.node);

function getNodeType(node: INode) {
  return [PAGE_NAME, BLOCK_NAME].includes(node.name) ? node.name : 'Node';
}

function handleRemove() {
  ElMessageBox.confirm('确定删除吗？', '提示', {
    type: 'warning'
  }).then(() => {
    props.node?.dispose();
    nextTick(() => {
      emit('action', { type: 'remove' });
    });
  });
}

function handleMoveNext() {
  props.node?.moveNext();
  nextTick(() => {
    emit('action', { type: 'move', next: true });
  });
}

function handleMovePrev() {
  props.node?.movePrev();
  nextTick(() => {
    emit('action', { type: 'move', prev: true });
  });
}

function handleCopy() {
  const node = props.node?.copy();
  nextTick(() => {
    emit('action', { type: 'copy', node });
  });
}

function handleMenuMouseEnter(node: INode) {
  emit('action', { type: 'hover', node });
}
function handleCommand(node: INode) {
  emit('action', { type: 'selected', node });
}
</script>
