<template>
    <el-dialog
        v-model="visible"
        :title="title"
        width="600px"
        :close-on-click-modal="false"
        @open="handleOpen"
    >
        <div class="carousel-edit">
            <el-alert
                v-if="type === 'carousel'"
                title="建议尺寸 300x150, 最多添加 5 张"
                type="info"
                show-icon
                :closable="false"
                class="mb-4"
            />
            <el-alert
                v-else
                title="建议尺寸 150x150"
                type="info"
                show-icon
                :closable="false"
                class="mb-4"
            />

            <div
                v-for="(item, index) in items"
                :key="index"
                class="flex items-start gap-4 mb-4 p-3 border rounded bg-gray-50 relative group"
            >
                <div class="w-32 h-32 shrink-0">
                    <ImageUpload
                        v-model="item.imgUrl"
                        :limit="1"
                        :isShowTip="false"
                    />
                </div>

                <div class="flex-1 space-y-2">
                    <el-input
                        v-if="type === 'carousel'"
                        v-model="item.title"
                        placeholder="图片标题 (可选)"
                    />
                    <el-input v-model="item.jumpUrl" placeholder="跳转链接" />
                    <div class="text-xs text-gray-400">
                        支持 http/https 链接或内部路由路径
                    </div>
                </div>

                <el-button
                    v-if="!fixedNumber"
                    type="danger"
                    circle
                    size="small"
                    class="opacity-0 group-hover:opacity-100 transition-opacity absolute -top-2 -right-2"
                    @click="handleRemove(index)"
                >
                    <el-icon>
                        <Delete />
                    </el-icon>
                </el-button>
            </div>

            <el-button
                v-if="!fixedNumber && items.length < maxItems"
                class="w-full border-dashed"
                @click="handleAdd"
            >
                <el-icon class="mr-1">
                    <Plus />
                </el-icon>
                添加图片
            </el-button>
        </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>
    </el-dialog>
</template>

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

    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: '编辑'
        },
        type: {
            type: String,
            default: 'carousel' // carousel, banner
        },
        fixedNumber: {
            type: Number,
            default: 0
        },
        position: {
            type: String,
            default: ''
        }
    });

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

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

    const loading = ref(false);
    const maxItems = computed(() => (props.type === 'carousel' ? 5 : 1));

    const items = ref([{ title: '', imgUrl: '', jumpUrl: '' }]);

    // Initialize based on fixedNumber
    const initItems = () => {
        if (props.fixedNumber > 0) {
            items.value = Array.from({ length: props.fixedNumber }, () => ({
                title: '',
                imgUrl: '',
                jumpUrl: ''
            }));
        } else {
            items.value = [{ title: '', imgUrl: '', jumpUrl: '' }];
        }
    };

    initItems();

    const handleAdd = () => {
        if (items.value.length < maxItems.value) {
            items.value.push({ title: '', imgUrl: '', jumpUrl: '' });
        }
    };

    const handleRemove = (index) => {
        items.value.splice(index, 1);
    };

    const handleOpen = async () => {
        if (!props.position) {
            initItems();
            return;
        }

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

            if (list.length > 0) {
                // Fill existing data
                let newItems = list.map((item) => ({
                    title: item.title || '',
                    imgUrl: item.imgUrl || '',
                    jumpUrl: item.jumpUrl || '',
                    id: item.id
                }));

                // If fixedNumber is set, ensure length matches
                if (props.fixedNumber > 0) {
                    if (newItems.length < props.fixedNumber) {
                        const diff = props.fixedNumber - newItems.length;
                        newItems = [
                            ...newItems,
                            ...Array.from({ length: diff }, () => ({
                                title: '',
                                imgUrl: '',
                                jumpUrl: ''
                            }))
                        ];
                    } else if (newItems.length > props.fixedNumber) {
                        newItems = newItems.slice(0, props.fixedNumber);
                    }
                }
                items.value = newItems;
            } else {
                initItems();
            }
        } catch (e) {
            console.error(e);
            initItems();
        }
    };

    const handleConfirm = async () => {
        if (!props.position) {
            EleMessage.warning('未配置位置信息');
            return;
        }

        loading.value = true;
        try {
            const showIndexInfoList = items.value
                .filter((item) => item.imgUrl) // Only save items with images
                .map((item, index) => ({
                    imgUrl: item.imgUrl,
                    jumpUrl: item.jumpUrl,
                    title: item.title,
                    orderNum: index,
                    showCateId: 0 // Default to 0 as we don't select categories here
                }));

            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>
    .carousel-edit {
        max-height: 60vh;
        overflow-y: auto;
    }
</style>
