<template>
    <ele-page flex-table>
        <common-table
            ref="tableRef"
            :pageConfig="pageConfig"
            :columns="columns"
            :tools="false"
            :pagination="false"
            :datasource="fetchData"
        >
            <template #index="{ $index }">
                {{ $index + 1 }}
            </template>

            <template #image="{ row }">
                <el-image
                    :src="row.cover"
                    class="w-16 h-16 rounded"
                    fit="cover"
                    :preview-src-list="[row.cover]"
                    preview-teleported
                />
            </template>

            <template #info="{ row }">
                <div>
                    <div
                        class="font-bold text-blue-500 hover:underline cursor-pointer"
                        >{{ row.bookName }}</div
                    >
                    <div class="text-xs text-gray-500 mt-1"
                        >作者: {{ row.author }}</div
                    >
                    <div class="text-xs text-gray-500"
                        >ISBN: {{ row.isbn }}</div
                    >
                    <div class="text-xs text-gray-500"
                        >出版社: {{ row.publish }}</div
                    >
                </div>
            </template>

            <template #isOnSale="{ row }">
                <el-switch
                    :model-value="row.isOnSale === 1"
                    @change="(val) => handleStatusChange(row, val)"
                />
            </template>
        </common-table>
    </ele-page>
</template>

<script setup>
    import { ref, reactive, getCurrentInstance } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import { EleMessage } from 'ele-admin-plus/es';

    defineOptions({ name: 'TrendsRank' });

    const { proxy } = getCurrentInstance();
    const tableRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/shop/shopbook/getBestsellerList',
        fileName: '热搜榜单',
        cacheKey: 'trends-rank-list',
        params: {}
    });

    const columns = ref([
        { label: '排序', type: 'index', width: 80, align: 'center' },
        { label: '商品图', slot: 'image', width: 120, align: 'center' },
        { label: '商品信息', slot: 'info', minWidth: 250 },
        { label: '销量', prop: 'salesNum', align: 'center', minWidth: 100 },
        { label: '库存', prop: 'stock', align: 'center', minWidth: 100 },
        { label: '是否启用', slot: 'isOnSale', align: 'center', minWidth: 100 },
        {
            label: '更新时间',
            prop: 'updateTime',
            align: 'center',
            minWidth: 180
        }
    ]);

    const fetchData = async () => {
        try {
            const res = await proxy.$http.get(pageConfig.pageUrl, {
                params: pageConfig.params
            });
            if (res.data.code === 200) {
                return res.data.data || [];
            }
            return Promise.reject(new Error(res.data.msg || '获取数据失败'));
        } catch (e) {
            return Promise.reject(e);
        }
    };

    const reload = () => {
        tableRef.value?.reload();
    };

    const handleStatusChange = (row, val) => {
        const newStatus = val ? 1 : 0;
        proxy.$http
            .post('/shop/shopbook/setShelfStatus', {
                isbn: row.isbn,
                sellStatus: newStatus
            })
            .then((res) => {
                if (res.data.code === 200) {
                    EleMessage.success(
                        `${row.bookName} ${newStatus === 1 ? '已启用' : '已禁用'}`
                    );
                } else {
                    EleMessage.error(res.data.msg || '操作失败');
                }
            })
            .catch(() => {
                reload();
            });
    };
</script>
