<template>
    <div v-bind="containerProps" style="height: 200px" class="sd-body">
        <div v-bind="wrapperProps">
            <div v-for="item in list"
                 :key="item.index"
                 class="row"
                 @click="rowClick(item)"
                 style="height: 23px">
                <template v-for="(he,heindex) in column">
                    <div class="cell" :style="{width: he.width +'px'}" :title="getTitle(item,he)">
                        <component :is="createTd(item,he)"/>
                    </div>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup name='SdTableBody' lang="tsx">
import {defineProps, ref, onMounted, getCurrentInstance} from 'vue'
import {useVirtualList} from "@vueuse/core";

const props = defineProps({
    data: {
        type: Array,
        default: []
    }
})

const {list, containerProps, wrapperProps, scrollTo} = useVirtualList(
    props.data,
    {
        itemHeight: 23,
    },
)

const column = ref([])

const createTd = ({data, index}, columnRow): any => {
    if (columnRow.slots) {
        if (data.$edit) {
            return <div>{columnRow.editCell(data, index)}</div>;
        } else {
            return <div>{columnRow.renderCell(data, index)}</div>;
        }
    } else {
        return <div>{data[columnRow.prop]}</div>
    }
}

const getTitle = ({data, index}, columnRow) => {
    try {
        return data[columnRow.prop];
    } catch {
        return '';
    }
}

let oldRow = {
    data: {$edit: false}
}
const rowClick = (item) => {
    oldRow.data.$edit = false
    item.data.$edit = true
    oldRow = item
}

onMounted(() => {
    const instance = getCurrentInstance()
    let parent = instance.parent
    column.value = parent.store.column

    containerProps.ref.value.addEventListener('scroll', () => {
        console.log(containerProps.ref.value.scrollTop);
        console.log(containerProps.ref.value.scrollLeft);
    })
})

</script>

<style lang="scss">
.sd-body {
  background-color: white;

  &::-webkit-scrollbar {
    height: 6px;
  }

  .row {
    height: 22px;
    display: flex;
    align-items: center;

    &:hover {
      background-color: #e0ecff;
    }

    .cell {
      overflow: hidden;
      display: flex;
      align-items: center;
      text-overflow: ellipsis;
      white-space: nowrap;
      height: 100%;
      flex-grow: 0;
      flex-shrink: 0;
      background-color: inherit;
      color: inherit;
      border-bottom: 1px solid #ebeef5;
    }
  }

}


</style>
