<template>
    <div class="hc-datav-table-main hc-full">
        <el-table
            ref="tableRef" class="top-table tablebox" :data="tableData" border :row-key="rowKey" :highlight-current-row="isCurrent"
            @mouseover="clearScroll" @mouseleave="createScroll" @row-click="rowClick"
        >
            <template v-for="item in tableColumn" :key="item.key">
                <el-table-column :align="item.align ?? 'center'" :label="item.name" :prop="item.key" :width="item.width">
                    <template v-if="item.isSlot" #default="scope">
                        <slot :index="scope.$index" :name="item.key" :row="scope.row" />
                    </template>
                </el-table-column>
            </template>
        </el-table>
    </div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, useSlots, watch } from 'vue'
import { getRandom, isNullES } from 'js-fast-way'

//参数
const props = defineProps({
    column: {
        type: Array,
        default: () => ([]),
    },
    datas: {
        type: Array,
        default: () => ([]),
    },
    rowKey: {
        type: String,
        default: 'id',
    },
    isCurrent: {
        type: Boolean,
        default: false,
    },
})

//事件
const emit = defineEmits(['rowClick'])

//表格表头
const tableColumn = ref(props.column)
watch(() => props.column, (data) => {
    tableColumn.value = data
    setIsSlots()
}, { deep: true })

//表格数据
const tableData = ref(props.datas)
watch(() => props.datas, (data) => {
    tableData.value = data
}, { deep: true })

//判断<slot>是否有传值
const slots = useSlots()

const setIsSlots = async () => {
    await getSlotKey(tableColumn.value)
}

const getSlotKey = async (arr) => {
    for (let i = 0; i < arr.length; i++) {
        if (isNullES(arr[i].key)) {
            arr[i].key = getRandom()
        }
        arr[i].isSlot = !!slots[arr[i].key]
    }
}

let timer = null
const tableRef = ref(null)

const clearScroll = () => {
    clearInterval(timer)
    timer = null
}
const createScroll = () => {
    clearScroll()
    // 拿到 table
    const table = tableRef.value.layout.table.refs
    // 拿到可以滚动的元素
    const wrapper = table.bodyWrapper.firstElementChild.firstElementChild

    timer = setInterval(() => {
        wrapper.scrollTop += 1
        // 判断是否滚动到底部，如果到底部了置为0（可视高度 + 距离顶部 = 整个高度）
        if (wrapper.clientHeight + wrapper.scrollTop === wrapper.scrollHeight) {
            wrapper.scrollTop = 0
        }
    }, 50)
}

//表格行被点击
const rowClick = (row, column, event) => {
    emit('rowClick', row, column, event)
}

onMounted(() => {
    setIsSlots()
    createScroll()
})
onUnmounted(() => {
    clearScroll()
})
</script>
