<template>
    <a-row :gutter="[24, 24]">
        <a-col :span="24" v-if="$scopedSlots.search">
            <slot name="search" />
        </a-col>
        <a-col :span="24">
            <a-table
                :dataSource="dataSource"
                :loading="loading"
                :pagination="pagination"
                @change="pageChange"
                v-bind="$attrs"
                rowKey="key"
            >
                <slot />
            </a-table>
        </a-col>
    </a-row>
</template>

<script>
const initQuery = {
    pageNum: 1,
    pageSize: 10,
    total: 0,
};

export default {
    props: {
        request: { type: Function, default: undefined },
        otherParams: { type: Object, default: () => ({}) },
        rowKey: String,
    },
    data() {
        return {
            loading: true,
            dataSource: [],
            params: {
                ...initQuery,
            },
        };
    },

    computed: {
        pagination() {
            return {
                current: this.params.pageNum,
                pageSize: this.params.pageSize,
                total: this.params.total,
                showQuickJumper: true,
            };
        },
    },

    watch: {
        otherParams: {
            handler() {
                this.refresh();
            },
            deep: true,
            immediate: true,
        },
    },

    mounted() {
        this.getList({ ...this.params, ...this.otherParams });
    },

    methods: {
        async getList(params) {
            if (!this.request) return;
            this.loading = true;
            const data = await this.request(params);
            const { records, total, pageNum } = data;
            const newData = records.map((i) => ({
                ...i,
                key: i[this.rowKey],
                editable: false,
            }));
            this.dataSource = newData;
            this.params = {
                ...this.params,
                total,
                pageNum,
            };
            this.loading = false;
        },
        refresh() {
            const params = {
                ...initQuery,
                ...this.otherParams,
            };
            this.getList(params);
        },
        pageChange(pagination) {
            const params = {
                ...this.params,
                ...this.otherParams,
                pageNum: pagination.current,
            };
            this.getList(params);
        },
        getTableData() {
            return this.dataSource;
        },
        setTableData(data) {
            this.dataSource = data;
        },
    },
};
</script>

