<script lang="ts" setup>
import { ref, watch } from 'vue';
import DissectionTree from './DissectionTree.vue';
import {
  CaretDownOutlined,
  CaretRightOutlined,
  MinusOutlined,
} from '@ant-design/icons-vue';

const props = defineProps({
  id: {
    type: String,
    required: true,
  },
  node: {
    type: Object,
    required: true,
  },
  select: {
    type: Function,
    required: true,
  },
  selected: {
    type: Object,
    required: true,
  },
});
const emit = defineEmits(['update:selected']);

const open = ref(false);

watch(
  () => props.selected,
  () => {
    if (!open.value) {
      open.value = props.selected.id.startsWith(props.id + '-');
    }
  },
  { immediate: true }
);

const toggle = () => {
  if (open.value && props.selected.id.startsWith(props.id + '-')) {
    const NO_SELECTION = { id: '', idx: 0, start: 0, length: 0 };
    emit('update:selected', NO_SELECTION);
    if (typeof props.select === 'function') {
      props.select(NO_SELECTION);
    }
  }
  open.value = !open.value;
};

const handleClick = () => {
  if (props.node.length > 0) {
    const select = {
      id: props.id,
      idx: props.node.data_source_idx,
      start: props.node.start,
      length: props.node.length,
    };
    emit('update:selected', select);
    if (typeof props.select === 'function') {
      props.select(select);
    }
  }
};
</script>

<template>
  <div :class="{ 'tree-sub': true, 'tree-sub_hl': id === selected.id }">
    <component
      :is="
        node.tree && node.tree.length > 0
          ? open
            ? CaretDownOutlined
            : CaretRightOutlined
          : MinusOutlined
      "
      class="tree-sub_icon"
      @click="toggle"
    />
    <span @click="handleClick" @dblclick="toggle" class="tree-sub_text">
      {{ node.label }}
    </span>
  </div>
  <DissectionTree
    v-if="node.tree && node.tree.length > 0 && open"
    :id="id"
    :tree="node.tree"
    :select="select"
    :selected="selected"
    sub
  />
</template>

<style lang="css" scoped>
.tree-sub {
  display: inline-flex;
  width: 100%;
  align-items: center;
  cursor: pointer;
}
.tree-sub_hl {
  color: #ffffff;
  background-color: #4b5563;
}
.tree-sub_icon {
  color: #6b7280;
  width: 1rem;
  height: 1rem;
}
.tree-sub_text {
  width: 100%;
  margin-left: 0.25rem;
}
</style>
