<template>
  <el-tree
    :data="doneTreeProps.doneJson"
    :props="defaultProps"
    @node-click="handleNodeClick"
    :default-expand-all="true"
    :expand-on-click-node="false"
    :highlight-current="true"
    node-key="id"
    :current-node-key="current_node_key">
    <template #default="{ node, data }">
      <div class="flex justify-between w-9/10">
        <div>{{ node.label }}</div>
        <div class="flex items-center">
          <el-button
            text
            circle
            size="small"
            :disabled="!canMoveUp(data)"
            title="上移一层"
            @click.stop="moveLayer(data, 'up')">
            <el-icon :size="16">
              <ArrowUp />
            </el-icon>
          </el-button>
          <el-button
            text
            circle
            size="small"
            :disabled="!canMoveDown(data)"
            title="下移一层"
            @click.stop="moveLayer(data, 'down')">
            <el-icon :size="16">
              <ArrowDown />
            </el-icon>
          </el-button>
          <el-button text circle size="small" class="mr-10px">
            <el-icon :title="data.hide ? '隐藏' : '显示'" :size="20" @click.stop="changeHide(data)">
              <svg-analysis :name="data.hide ? 'view-hide' : 'view-show'" />
            </el-icon>
          </el-button>
        </div>
      </div>
    </template>
  </el-tree>
</template>

<script lang="ts" setup>
import { ElTree, ElButton, ElIcon } from 'element-plus'
import { ArrowDown, ArrowUp } from '@element-plus/icons-vue'
import { computed } from 'vue'
import type { IDoneJson } from '@/components/mt-edit/store/types'
import SvgAnalysis from '@/components/mt-edit/components/svg-analysis/index.vue'
type DoneTree = {
  doneJson: IDoneJson[]
  selectedItemsId: string[] //已选中组件的id
}
const doneTreeProps = withDefaults(defineProps<DoneTree>(), {})

const emits = defineEmits(['updateSelectedItemsId', 'updateSelectedIdHide', 'moveLayer'])

const current_node_key = computed(() => {
  return doneTreeProps.selectedItemsId.length == 1 ? doneTreeProps.selectedItemsId[0] : ''
})
const handleNodeClick = (data: IDoneJson) => {
  emits('updateSelectedItemsId', data.id)
}
const changeHide = (data: IDoneJson) => {
  emits('updateSelectedIdHide', data.id)
}
const getLayerIndex = (data: IDoneJson) => {
  return doneTreeProps.doneJson.findIndex((item) => item.id === data.id)
}
const canMoveUp = (data: IDoneJson) => {
  const index = getLayerIndex(data)
  return index >= 0 && index < doneTreeProps.doneJson.length - 1
}
const canMoveDown = (data: IDoneJson) => {
  return getLayerIndex(data) > 0
}
const moveLayer = (data: IDoneJson, direction: 'up' | 'down') => {
  emits('moveLayer', {
    id: data.id,
    direction
  })
}
const defaultProps = {
  children: 'nochildren',
  label: 'title'
}
</script>
