<template>
    <ele-modal
        :width="width"
        v-model="visible"
        :title="title"
        position="center"
        :body-style="{ padding: '0 20px 20px' }"
    >
        <!-- Search -->
        <div class="p-0">
            <el-form :inline="true" :model="searchForm" label-width="0px">
                <el-form-item>
                    <el-input
                        v-model="searchForm.bookName"
                        placeholder="请输入商品名称"
                        clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-input
                        v-model="searchForm.isbn"
                        placeholder="请输入ISBN"
                        clearable
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch"
                        >查询</el-button
                    >
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="flex justify-between items-end mb-4">
            <!-- Tabs -->
            <div class="flex space-x-6 border-b border-gray-200 w-64 mr-4">
                <div
                    class="cursor-pointer pb-2 px-2 whitespace-nowrap"
                    :class="
                        activeTab === 'all'
                            ? 'text-primary border-b-2 border-primary font-medium'
                            : 'text-gray-600'
                    "
                    @click="activeTab = 'all'"
                    >全部</div
                >
                <div
                    class="cursor-pointer pb-2 px-2 whitespace-nowrap"
                    :class="
                        activeTab === 'selected'
                            ? 'text-primary border-b-2 border-primary font-medium'
                            : 'text-gray-600'
                    "
                    @click="activeTab = 'selected'"
                    >已选择 ({{ selectedCount }})</div
                >
            </div>

            <!-- Pagination -->
            <el-pagination
                v-if="activeTab === 'all'"
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="shrink-0"
            />
            <!-- Empty div to maintain flex-between layout when pagination is hidden -->
            <div v-else class="shrink-0"></div>
        </div>

        <!-- Table for All -->
        <el-table
            v-show="activeTab === 'all'"
            ref="tableRef"
            :data="tableData"
            row-key="isbn"
            v-loading="loading"
            @selection-change="handleSelectionChange"
            border
            height="400px"
        >
            <el-table-column
                type="selection"
                width="55"
                align="center"
                :reserve-selection="true"
            />
            <el-table-column label="图示" width="80" align="center">
                <template #default="{ row }">
                    <el-image
                        :src="row.cover"
                        class="w-10 h-10 object-cover"
                        :preview-src-list="[row.cover]"
                        preview-teleported
                    >
                        <template #error>
                            <div
                                class="w-10 h-10 bg-gray-100 flex items-center justify-center text-gray-400"
                            >
                                <el-icon><Picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column
                prop="isbn"
                label="ISBN"
                width="140"
                align="center"
            />
            <el-table-column
                prop="bookName"
                label="书名"
                min-width="200"
                show-overflow-tooltip
            />

            <template v-if="showDescription">
                <el-table-column label="商品描述" min-width="200">
                    <template #default="{ row }">
                        <div
                            v-if="!row._editingDesc"
                            class="cursor-pointer flex items-center"
                            @click="row._editingDesc = true"
                        >
                            <span
                                class="truncate flex-1"
                                :title="row.bookDesc || '点击输入描述'"
                                >{{ row.bookDesc || '点击输入描述' }}</span
                            >
                            <el-icon class="ml-1 text-gray-400"
                                ><Edit
                            /></el-icon>
                        </div>
                        <el-input
                            v-else
                            v-model="row.bookDesc"
                            placeholder="请输入商品描述"
                            size="small"
                            @blur="row._editingDesc = false"
                            @keyup.enter="row._editingDesc = false"
                            @input="(val) => updateSelectionDesc(row, val)"
                            autofocus
                        />
                    </template>
                </el-table-column>
            </template>
            <template v-else>
                <el-table-column
                    prop="author"
                    label="作者"
                    width="120"
                    show-overflow-tooltip
                />
                <el-table-column
                    prop="price"
                    label="价格"
                    width="100"
                    align="center"
                />
            </template>
        </el-table>

        <!-- Table for Selected -->
        <el-table
            v-show="activeTab === 'selected'"
            :data="currentSelections"
            row-key="isbn"
            border
            height="400px"
        >
            <el-table-column width="55" align="center">
                <template #header>
                    <el-checkbox
                        :model-value="true"
                        @change="handleClearAllSelections"
                    />
                </template>
                <template #default="{ row }">
                    <el-checkbox
                        :model-value="true"
                        @change="() => handleRemoveSelection(row)"
                    />
                </template>
            </el-table-column>
            <el-table-column label="图示" width="80" align="center">
                <template #default="{ row }">
                    <el-image
                        :src="row.cover"
                        class="w-10 h-10 object-cover"
                        :preview-src-list="[row.cover]"
                        preview-teleported
                    >
                        <template #error>
                            <div
                                class="w-10 h-10 bg-gray-100 flex items-center justify-center text-gray-400"
                            >
                                <el-icon><Picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </template>
            </el-table-column>
            <el-table-column
                prop="isbn"
                label="ISBN"
                width="140"
                align="center"
            />
            <el-table-column
                prop="bookName"
                label="书名"
                min-width="200"
                show-overflow-tooltip
            />

            <template v-if="showDescription">
                <el-table-column label="商品描述" min-width="200">
                    <template #default="{ row }">
                        <div
                            v-if="!row._editingDesc"
                            class="cursor-pointer flex items-center"
                            @click="row._editingDesc = true"
                        >
                            <span
                                class="truncate flex-1"
                                :title="row.bookDesc || '点击输入描述'"
                                >{{ row.bookDesc || '点击输入描述' }}</span
                            >
                            <el-icon class="ml-1 text-gray-400"
                                ><Edit
                            /></el-icon>
                        </div>
                        <el-input
                            v-else
                            v-model="row.bookDesc"
                            placeholder="请输入商品描述"
                            size="small"
                            @blur="row._editingDesc = false"
                            @keyup.enter="row._editingDesc = false"
                            @input="(val) => updateSelectionDesc(row, val)"
                            autofocus
                        />
                    </template>
                </el-table-column>
            </template>
            <template v-else>
                <el-table-column
                    prop="author"
                    label="作者"
                    width="120"
                    show-overflow-tooltip
                />
                <el-table-column
                    prop="price"
                    label="价格"
                    width="100"
                    align="center"
                />
            </template>
        </el-table>

        <template #footer>
            <div class="flex justify-end items-center">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleConfirm"
                    >确定</el-button
                >
            </div>
        </template>
    </ele-modal>
</template>

<script setup>
    import { ref, reactive, watch, computed, nextTick } from 'vue';
    import { Picture, Edit } from '@element-plus/icons-vue';
    import request from '@/utils/request';

    const props = defineProps({
        title: { type: String, default: '添加商品' },
        width: { type: String, default: '900px' },
        defaultSelected: { type: Array, default: () => [] },
        showDescription: { type: Boolean, default: false }
    });

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

    const visible = defineModel({ type: Boolean });
    const tableRef = ref(null);
    const searchForm = reactive({
        bookName: '',
        isbn: ''
    });

    const activeTab = ref('all');
    const currentSelections = ref([]);
    const selectedCount = computed(() => currentSelections.value.length);

    // Pagination for 'all'
    const tableData = ref([]);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const loading = ref(false);

    const handleSearch = async () => {
        if (activeTab.value === 'selected') {
            return;
        }

        loading.value = true;
        try {
            const params = {
                ...searchForm,
                pageNum: currentPage.value,
                pageSize: pageSize.value
            };
            console.log('Search params:', params);
            const res = await request.get('/book/bookInfo/list', { params });
            console.log('API response:', res);
            if (res.data.code === 200) {
                const data = res.data.data || res.data;
                const rows = data.rows || data;

                const updateRowDesc = (row) => {
                    const selectedItem = currentSelections.value.find(
                        (s) => s.isbn === row.isbn
                    );
                    if (selectedItem && selectedItem.bookDesc !== undefined) {
                        row.bookDesc = selectedItem.bookDesc;
                        return;
                    }
                    const defaultItem = props.defaultSelected.find(
                        (d) => d.isbn === row.isbn
                    );
                    if (defaultItem) {
                        row.bookDesc = defaultItem.bookDesc;
                    }
                };

                rows.forEach(updateRowDesc);
                tableData.value = rows;
                total.value = data.total || rows.length;
                console.log(
                    'Updated tableData:',
                    tableData.value.length,
                    'rows, total:',
                    total.value
                );

                // Sync selections to table
                nextTick(() => {
                    if (tableRef.value) {
                        tableRef.value.clearSelection();
                        rows.forEach((row) => {
                            const isSelected = currentSelections.value.some(
                                (s) => s.isbn === row.isbn
                            );
                            if (isSelected) {
                                tableRef.value.toggleRowSelection(row, true);
                            }
                        });
                    }
                });
            }
        } catch (e) {
            console.error('Search error:', e);
        } finally {
            loading.value = false;
        }
    };

    const handleSizeChange = (val) => {
        pageSize.value = val;
        handleSearch();
    };

    const handleCurrentChange = (val) => {
        currentPage.value = val;
        handleSearch();
    };

    const handleReset = () => {
        searchForm.bookName = '';
        searchForm.isbn = '';
        currentPage.value = 1;
        handleSearch();
    };

    const reset = () => {
        searchForm.bookName = '';
        searchForm.isbn = '';
        activeTab.value = 'all';
        currentSelections.value = [];
        currentPage.value = 1;
        if (tableRef.value) {
            tableRef.value.clearSelection();
        }
        handleSearch();
    };

    const handleSelectionChange = (rows) => {
        // Get all selected rows from the table (only current page)
        const currentPageSelectedIsbns = new Set(rows.map((row) => row.isbn));

        // Remove rows that are no longer selected on current page
        currentSelections.value = currentSelections.value.filter(
            (s) =>
                currentPageSelectedIsbns.has(s.isbn) ||
                !tableData.value.some((r) => r.isbn === s.isbn)
        );

        // Add newly selected rows from current page
        rows.forEach((row) => {
            if (!currentSelections.value.some((s) => s.isbn === row.isbn)) {
                currentSelections.value.push({ ...row });
            }
        });
    };

    const handleClearAllSelections = (val) => {
        if (!val) {
            // User clicked to uncheck
            currentSelections.value = [];
            if (tableRef.value) {
                tableRef.value.clearSelection();
            }
        }
    };

    const handleRemoveSelection = (row) => {
        const idx = currentSelections.value.findIndex(
            (s) => s.isbn === row.isbn
        );
        if (idx !== -1) {
            currentSelections.value.splice(idx, 1);
        }
        // Also untoggle in table if it's currently loaded
        if (tableRef.value) {
            const tableRow = tableData.value.find((r) => r.isbn === row.isbn);
            if (tableRow) {
                tableRef.value.toggleRowSelection(tableRow, false);
            }
        }
    };

    const updateSelectionDesc = (row, val) => {
        const selected = currentSelections.value.find(
            (s) => s.isbn === row.isbn
        );
        if (selected) {
            selected.bookDesc = val;
        }
        // Also update the row in tableData if it exists
        const tableRow = tableData.value.find((r) => r.isbn === row.isbn);
        if (tableRow) {
            tableRow.bookDesc = val;
        }
    };

    const handleCancel = () => {
        visible.value = false;
    };

    const handleConfirm = () => {
        emit('confirm', currentSelections.value);
        visible.value = false;
    };

    watch(visible, (val) => {
        if (val) {
            nextTick(() => {
                if (props.defaultSelected && props.defaultSelected.length > 0) {
                    currentSelections.value = JSON.parse(
                        JSON.stringify(props.defaultSelected)
                    );
                } else {
                    currentSelections.value = [];
                }
                currentPage.value = 1;
                handleSearch();
            });
        }
    });

    defineExpose({
        reset
    });
</script>
