<template>
    <div class="app-table">
        <table class="app-table__body" cellspacing="0" cellpadding="0">
            <thead>
                <Draggable class="app-table__row" :list="columns" tag="tr" item-key="key">
                    <template #header v-if="$slots.expand">
                        <th class="app-table__cell expand"></th>
                    </template>
                    <template #item="{ element }">
                        <th class="app-table__cell">{{ element.label }}</th>
                    </template>
                </Draggable>
            </thead>
            <tbody>
                <template v-for="(row, i) in dataList" :key="i">
                    <tr class="app-table__row" @click="rowClick(i)">
                        <td class="app-table__cell expand" v-if="$slots.expand">
                            <Icon name="arrow-down" v-if="selectedIndex === i" />
                            <Icon name="arrow" v-else />
                        </td>
                        <td class="app-table__cell" :class="column.className" v-for="(column, n) in columns"
                            :key="i + n.toString()">
                            <slot :name="column.prop" :value="row[column.prop]" :row="row">{{ row[column.prop] }}</slot>
                        </td>
                    </tr>
                    <!-- expand -->
                    <tr class="app-table__row expand" v-show="selectedIndex === i" v-if="$slots.expand">
                        <td class="app-table__cell" :colspan="columns.length + 1">
                            <slot name="expandRow" :row="row"></slot>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>
</template>

<script lang="ts" setup>
import { PropType, ref } from 'vue'
import { Icon } from 'vant'
import { TableColumn } from './interface'
import Draggable from 'vuedraggable'

const emit = defineEmits(['rowClick'])

const props = defineProps({
    // 数据列表
    dataList: {
        type: Array,
        default: () => ([]),
    },
    columns: {
        type: Array as PropType<TableColumn[]>,
        default: () => ([]),
    },
})

const selectedIndex = ref(-1);

const rowClick = (index: number) => {
    if (selectedIndex.value === index) {
        selectedIndex.value = -1;
    } else {
        selectedIndex.value = index;
    }
    emit('rowClick', index, props.dataList[index]);
}
</script>

<style lang="less" scoped>
@import './index.less';
</style>