<script setup lang="ts">
import { getCheckboxIcon, state_checked } from '.'

const props = withDefaults(
  defineProps<{
    data: anyObj
    index?: number | null
    prop?: {
      label: string
      select: string
    }
    expands: string[]
  }>(),
  {
    data: () => ({}),
    expands: () => [],
    index: null,
  },
)

const emits = defineEmits(['select'])

function getIcon(item: any) {
  const state = item[props.prop?.select || 'select']
  return getCheckboxIcon(state)
}

function isChekced(item: any) {
  const state = item[props.prop?.select || 'select']
  console.log(state, item)
  return state === state_checked
}

const checkedMap = ref({} as any)

defineOptions({
  name: 'XTreeItem',
})

function onSelect(pData: anyObj, data?: anyObj) {
  emits('select', pData, data)
}

function change(pData: any, cData?: any) {}
</script>

<template>
  <el-collapse-item :name="data.id">
    <template #title>
      <Icon
        v-if="data.children?.length"
        class="arrow-icon"
        name="textbook_arrow_up"
        size="48"
        :rotate="expands.includes(data.id) ? 180 : 0"
      />
      <div class="title">
        <!-- <template v-if="index !== null"> {{ index! + 1 }}. </template> -->
        {{ data[prop?.label || 'label'] }}
      </div>
      <Icon class="select-icon" :name="getIcon(data)" size="48" @click.stop="onSelect(data)" />
    </template>
    <template v-if="data.children?.length">
      <div class="child-list">
        <template v-for="(item, idx) in data.children" :key="item.id">
          <XTreeItem
            v-if="item.children?.length"
            :index="idx"
            :data="item"
            :prop="prop"
            :expands="expands"
            @select="onSelect"
          />
          <template v-else>
            <div class="child-list-item" @click.stop="onSelect(data, item)">
              <div class="title">{{ item[prop?.label || 'label'] }}</div>
              <Icon class="select-icon" :name="getIcon(item)" size="48" />
            </div>
          </template>
        </template>
      </div>
    </template>
    <slot></slot>
  </el-collapse-item>
</template>
<style lang="scss" scoped>
:deep(.el-collapse-item) {
  margin-left: 72px;
  &:not(.is-active) {
    .arrow-icon {
      transform: rotate(0) !important;
    }
  }
  &.is-active {
    .arrow-icon {
      transform: rotate(180deg);
    }
  }
}
</style>
