<template>
    <goods-select-dialog
        ref="goodsSelectRef"
        v-model="visible"
        :default-selected="selectedBooks"
        :show-description="true"
        title="绑定图书"
        @confirm="handleConfirm"
    />
</template>

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

    const emit = defineEmits(['success']);

    const visible = ref(false);
    const selectedBooks = ref([]);
    const originalIsbns = ref([]);
    const originalBooksMap = ref({});
    const currentId = ref(null);
    const goodsSelectRef = ref(null);

    const handleOpen = async (row) => {
        currentId.value = row.id;
        selectedBooks.value = [];
        originalIsbns.value = [];
        originalBooksMap.value = {};

        // Reset dialog state
        if (goodsSelectRef.value?.reset) {
            goodsSelectRef.value.reset();
        }

        await loadBoundBooks(row.id);
        visible.value = true;
    };

    const loadBoundBooks = async (id) => {
        try {
            const res = await request.get('/book/showIndex/queryBindBook', {
                params: { showCateId: id, type: 1, pageNum: 1, pageSize: 1000 }
            });
            const list = res.data?.rows || res.data || [];

            // Map bookIsbn to isbn to match GoodsSelectDialog rowKey
            const mappedList = (Array.isArray(list) ? list : []).map(
                (item) => ({
                    ...item,
                    isbn: item.bookIsbn || item.isbn,
                    bookDesc: item.bookDesc || ''
                })
            );

            selectedBooks.value = mappedList;
            originalIsbns.value = mappedList.map((b) => b.isbn);
            mappedList.forEach((b) => {
                originalBooksMap.value[b.isbn] = b;
            });
        } catch (e) {}
    };

    const handleConfirm = async (rows) => {
        if (!currentId.value) return;

        const loading = EleMessage.loading('正在保存...');
        try {
            const currentIsbns = rows.map((b) => b.isbn);

            const toAdd = rows.filter((b) => {
                if (!originalIsbns.value.includes(b.isbn)) {
                    return true;
                }
                // Check if description changed
                const orig = originalBooksMap.value[b.isbn];
                if (orig && (orig.bookDesc || '') !== (b.bookDesc || '')) {
                    return true;
                }
                return false;
            });

            const toRemove = originalIsbns.value.filter(
                (isbn) => !currentIsbns.includes(isbn)
            );

            const promises = [];

            if (toAdd.length > 0) {
                const bindBookList = toAdd.map((b) => ({
                    bookIsbn: b.isbn,
                    bookDesc: b.bookDesc || ''
                }));
                const bookIsbnList = toAdd.map((b) => b.isbn);

                promises.push(
                    request.post('/book/showIndex/bindBook', {
                        showCateId: currentId.value,
                        bookIsbnList: bookIsbnList,
                        bindBookList: bindBookList
                    })
                );
            }

            if (toRemove.length > 0) {
                promises.push(
                    request.post('/book/showIndex/unBindBook', {
                        showCateId: currentId.value,
                        bookIsbnList: toRemove
                    })
                );
            }

            await Promise.all(promises);

            loading.close();
            EleMessage.success('绑定成功');
            visible.value = false;
            emit('success');
        } catch (e) {
            loading.close();
            console.error(e);
            EleMessage.error(e.message || '操作失败');
        }
    };

    defineExpose({
        handleOpen
    });
</script>
