<template>
    <el-dialog
        v-model="visible"
        title="热销商品编辑"
        width="600px"
        :close-on-click-modal="false"
        @open="handleOpen"
    >
        <div class="hot-sales-edit">
            <el-alert
                title="请选择 2 个热销商品"
                type="info"
                show-icon
                :closable="false"
                class="mb-4"
            />

            <div
                v-for="(item, index) in items"
                :key="index"
                class="flex items-center gap-4 mb-4 p-3 border rounded bg-gray-50 relative group cursor-pointer hover:border-blue-500 transition-colors"
                @click="handleOpenSelect(index)"
            >
                <div
                    class="w-16 h-16 bg-gray-200 rounded flex items-center justify-center shrink-0"
                >
                    <el-icon
                        v-if="!item.imgUrl"
                        :size="20"
                        class="text-gray-400"
                    >
                        <Plus />
                    </el-icon>
                    <img
                        v-else
                        :src="item.imgUrl"
                        class="w-full h-full object-cover rounded"
                    />
                </div>

                <div class="flex-1">
                    <div v-if="!item.title" class="text-gray-400"
                        >点击选择商品</div
                    >
                    <div v-else>
                        <div class="font-medium truncate">{{ item.title }}</div>
                        <div v-if="item.price" class="text-red-500 mt-1"
                            >¥{{ item.price }}</div
                        >
                    </div>
                </div>

                <div
                    class="bg-blue-100 text-blue-600 text-xs px-2 py-1 rounded"
                >
                    位置 {{ index + 1 }}
                </div>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button
                    type="primary"
                    :loading="loading"
                    @click="handleConfirm"
                    >确定</el-button
                >
            </span>
        </template>

        <GoodsSelectDialog
            ref="goodsSelectRef"
            v-model="selectVisible"
            @confirm="handleSelectConfirm"
        />
    </el-dialog>
</template>

<script setup>
    import { computed, ref } from 'vue';
    import { Plus } from '@element-plus/icons-vue';
    import GoodsSelectDialog from '../../components/GoodsSelectDialog.vue';
    import request from '@/utils/request';
    import { EleMessage } from 'ele-admin-plus/es';

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false
        },
        position: {
            type: String,
            default: 'right_banner'
        }
    });

    const emit = defineEmits(['update:modelValue', 'success']);

    const visible = computed({
        get: () => props.modelValue,
        set: (val) => emit('update:modelValue', val)
    });

    const selectVisible = ref(false);
    const activeIndex = ref(0);
    const loading = ref(false);
    const goodsSelectRef = ref(null);

    // Fixed 2 items
    const items = ref([
        { id: '', title: '', imgUrl: '', price: '', jumpUrl: '' },
        { id: '', title: '', imgUrl: '', price: '', jumpUrl: '' }
    ]);

    const handleOpen = async () => {
        // Reset selection in dialog if needed
        if (goodsSelectRef.value?.reset) {
            goodsSelectRef.value.reset();
        }

        try {
            const res = await request.get('/book/showIndex/getInfoByPosition', {
                params: { position: props.position }
            });
            const list = res.data?.data || [];

            if (list.length > 0) {
                items.value = Array(2)
                    .fill(null)
                    .map((_, i) => {
                        const remote = list[i] || {};
                        return {
                            id: remote.showCateId || '', // Using showCateId to store product ID
                            title: remote.title || '',
                            imgUrl: remote.imgUrl || '',
                            jumpUrl: remote.jumpUrl || '',
                            price: '' // Backend doesn't return price, leave empty
                        };
                    });
            } else {
                items.value = [
                    { id: '', title: '', imgUrl: '', price: '', jumpUrl: '' },
                    { id: '', title: '', imgUrl: '', price: '', jumpUrl: '' }
                ];
            }
        } catch (e) {
            console.error(e);
        }
    };

    const handleOpenSelect = (index) => {
        activeIndex.value = index;
        selectVisible.value = true;
    };

    const handleSelectConfirm = (selected) => {
        if (selected && selected.length > 0) {
            // Only take the first selected item for the active slot
            const product = selected[0];
            console.log(product, 'xxxx');
            items.value[activeIndex.value] = {
                id: product.id, // Assuming product object has id
                title: product.bookName,
                imgUrl: product.cover,
                price: product.price,
                jumpUrl: `/pages-sell/pages/detail?isbn=${product.isbn}` // Construct jumpUrl
            };
        }
        selectVisible.value = false;
    };

    const handleConfirm = async () => {
        loading.value = true;
        try {
            const showIndexInfoList = items.value
                .filter((item) => item.imgUrl)
                .map((item, index) => ({
                    imgUrl: item.imgUrl,
                    jumpUrl: item.jumpUrl,
                    title: item.title,
                    showCateId: item.id || 0, // Store product ID
                    orderNum: index
                }));

            await request.post('/book/showIndex/updateIndex', {
                position: props.position,
                showIndexInfoList
            });

            EleMessage.success('保存成功');
            visible.value = false;
            emit('success');
        } catch (e) {
            console.error(e);
            EleMessage.error(e.message || '保存失败');
        } finally {
            loading.value = false;
        }
    };
</script>

<style scoped>
    .hot-sales-edit {
        max-height: 60vh;
        overflow-y: auto;
    }
</style>
