<script setup>
import { ref, computed } from 'vue'
import useSlotConfig from '../hooks/useSlotConfig'
import VRender from '../VRender/index.vue'
import { isFunction } from '../utils/assist.js'

defineOptions({
  name: 'TableColumn'
})

const props = defineProps({
  item: {
    type: Object,
    required: true
  },
  slots: Object
})

const slotConfig = useSlotConfig(props.item)

const itemTitle = computed(() => {
  if (isFunction(props.item.title)) {
    return ''
  }
  return props.item.title
})

const attrs = computed(() => {
  const { children = [], title, key, ...rest } = props.item || {}
  return rest
})
</script>

<template>
  <el-table-column :prop="props.item.key" :label="itemTitle" v-bind="attrs">
    <!-- 嵌套表头 -->
    <template v-if="item.children && item.children.length">
      <TableColumn
        v-for="(childItem, childIndex) in item.children"
        :key="`table-column-${childIndex}`"
        :item="childItem"
        :slots="slots"
      >
        <template v-for="key in Object.keys(props.slots)" :key="key" v-slot:[key]="scope">
          <slot :name="key" v-bind="scope"></slot>
        </template>
      </TableColumn>
    </template>
    <!-- cell 插槽 -->
    <template
      v-if="slotConfig && props.slots[slotConfig.default] && !item.children"
      #default="scope"
    >
      <slot :name="slotConfig.default" v-bind="scope"></slot
    ></template>
    <template
      v-else-if="props.item.render && isFunction(props.item.render)"
      #default="{ $index, cellIndex, column, row }"
    >
      <VRender
        :render="props.item.render"
        :data="{ rowIndex: $index, cellIndex, column, row }"
      ></VRender>
    </template>
    <!-- 表头插槽 -->
    <template v-if="slotConfig && props.slots[slotConfig.header]" #header="scope">
      <slot :name="slotConfig.header" v-bind="scope"></slot>
    </template>
    <template v-else-if="isFunction(props.item.title)" #header="scope">
      <VRender :render="props.item.title"></VRender>
    </template>
  </el-table-column>
</template>

<style></style>
