<script setup lang="ts">
import type { NodeProps } from '@vue-flow/core'
import { useVueFlow } from '@vue-flow/core'
import { Delete } from '@element-plus/icons-vue'

interface Props {
  node: NodeProps
}

const props = defineProps<Props>()

const { findNode, removeNodes, nodesDraggable } = useVueFlow()

const formInput = ref<null | HTMLInputElement>(null)
const form = reactive({
  label: ''
})
watchEffect(() => {
  form.label = props.node.label as string
})

function onBlur() {
  const node = findNode(props.node.id)
  if (node) {
    node.label = form.label
  }
}

// 删除
function onRemove() {
  const node = findNode(props.node.id)
  if (node) removeNodes([node])
}
</script>
<template>
  <div class="node-text">
    <el-input
      type="text"
      :readonly="!nodesDraggable"
      v-model="form.label"
      :maxlength="20"
      ref="formInput"
      @blur="onBlur" />
    <p>{{ form.label }}</p>
    <el-icon v-if="nodesDraggable" size="14" @click="onRemove"><Delete /></el-icon>
  </div>
</template>

<style lang="scss">
.node-text {
  display: flex;
  align-items: center;
  justify-content: center;
  p {
    min-width: 100px;
    font-size: var(--el-font-size-base);
    line-height: 30px;
    color: var(--el-input-text-color, var(--el-text-color-regular));
    text-align: center;
  }
  .el-input {
    width: 100px;
    display: none;
  }
  .el-input__wrapper {
    padding: 0 5px;
    border-radius: 0;
    box-shadow: none;
  }
  .el-input__inner {
    text-align: center;
  }
  .el-icon {
    opacity: 0;
  }
}
.vue-flow__node {
  &.selected {
    .node-text {
      p {
        display: none;
      }
      .el-input {
        display: block;
      }
      .el-input__wrapper {
        border-bottom: 1px solid var(--el-input-border-color);
      }
      .el-icon {
        opacity: 1;
      }
    }
  }
}
</style>
