<template>
  <div
    class="w-full flex items-center justify-between group/item"
    :class="{
      'selected-tree-node': projectStore.activeWidgets.map((item) => item.id).includes(data.id)
    }"
  >
    <div class="flex-1 flex items-center gap-8px">
      <LuPanelsTopLeft size="14px" v-if="data.type === 'page'" />
      <!-- 展示控件图标 -->
      <img
        v-else-if="widgetIcon"
        class="w-14px h-14px object-contain shrink-0"
        :src="widgetIcon"
        draggable="false"
      />
      <LuBox size="14px" v-else />
      <span>{{ data.name }}</span>
    </div>
    <div
      v-if="Object.hasOwn(data, 'locked')"
      class="flex items-center gap-4px pr-12px invisible group-hover/item:visible"
    >
      <el-tooltip v-if="isBind" content="解除绑定">
        <span @click.capture.stop="unbind"><LuUnlink size="14px" /></span>
      </el-tooltip>
      <el-tooltip v-if="data.type !== 'page' && !data.locked" content="删除">
        <span @click.capture.stop="deleteWidget(data)"><LuTrash2 size="14px" /></span>
      </el-tooltip>
      <el-tooltip content="隐藏/显示">
        <span @click.capture.stop="data.hidden = !data.hidden">
          <LuEye size="14px" v-if="!data.hidden" />
          <LuEyeOff size="14px" v-else />
        </span>
      </el-tooltip>
      <el-tooltip :content="data.locked ? '解锁' : '锁定'">
        <span @click.capture.stop="data.locked = !data.locked">
          <LuLock size="14px" v-if="data.locked" />
          <LuUnlock size="14px" v-else />
        </span>
      </el-tooltip>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { RenderContentContext } from 'element-plus'
import type { BaseWidget } from '@/types/baseWidget'

import { computed } from 'vue'
import {
  LuTrash2,
  LuLock,
  LuUnlock,
  LuEye,
  LuEyeOff,
  LuPanelsTopLeft,
  LuBox,
  LuUnlink
} from 'vue-icons-plus/lu'
import { useProjectStore } from '@/store/modules/project'
import { useActionStore } from '@/store/modules/action'
import componentMap from '@/lvgl-widgets'

const props = defineProps<{
  node: RenderContentContext['node']
  data: BaseWidget
}>()

const projectStore = useProjectStore()
const actionStore = useActionStore()

const widgetIcon = computed(() => {
  if (props.data.type === 'page') return ''
  return componentMap[props.data.type]?.icon || ''
})

const isBind = computed(() => {
  return actionStore.isWidgetBoundById(props.data.id)
})

// 删除控件
const deleteWidget = (data: BaseWidget) => {
  if (data.locked) return
  actionStore.onDeleteById(data.id)
}

// 解除绑定
const unbind = () => {
  actionStore.onUnbind([props.data.id])
}
</script>

<style lang="less">
.el-tree-node__content:has(.selected-tree-node) {
  background: var(--el-color-primary-light-9) !important;
}
</style>
