<template>
    <el-dialog v-model="dialogVisible" width="800px" :show-close="true" :close-on-click-modal="false"
        class="interactive-reward-dialog">

        <div class="interactive-title">互动打赏</div>

        <div class="interactive-items-container">
            <div class="interactive-items">
                <div v-for="(item, index) in rewardItems" :key="index" class="reward-item" :class="{ active: item.active }"
                    @click="toggleItemSelection(index)">
                    <div class="item-header">
                        <img :src="item.image" :alt="item.title" class="item-icon" />
                        <div class="check-mark" v-if="item.active">
                            <el-icon>
                                <Check />
                            </el-icon>
                        </div>
                    </div>
                    <div class="item-body">
                        <div class="item-name">{{ item.title }} <span v-if="item.hot" class="hot-tag">HOT</span></div>
                        <div class="item-price">{{ item.integerPrice }}豆豆</div>
                        <div class="item-counter">
                            <el-button class="counter-btn minus" @click.stop="decreaseCount(index)"
                                :disabled="item.count <= 0">-</el-button>
                            <span class="count-value">{{ item.count }}</span>
                            <el-button class="counter-btn plus" @click.stop="increaseCount(index)">+</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="reward-footer">
            <el-button type="primary" class="submit-btn" @click="submitReward">打赏</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Check } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { orderApi } from '@/api/user';
import { useMainStore } from '@/store';

const store = useMainStore();

const props = defineProps({
    visible: {
        type: Boolean,
        default: false
    },
    bookId: {
        type: [String, Number],
        required: true
    }
});

const emit = defineEmits(['update:visible', 'reward-success']);

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

const loading = ref(false);

// 礼物列表
const rewardItems = ref([]);

// 获取礼物列表
const getGiftList = async () => {
    try {
        loading.value = true;
        const res = await orderApi.getInteractionGiftList({
            pageNo: 1,
            pageSize: 99999
        });
        
        if (res.result && res.result.records) {
            // 转换后端数据格式为前端所需格式
            rewardItems.value = res.result.records.map(item => ({
                id: item.id,
                title: item.title,
                image: item.image,
                integerPrice: item.integerPrice,
                count: 0,
                active: false,
                hot: item.hot || false
            }))
        }
    } catch (error) {
        console.error('获取礼物列表失败:', error);
        ElMessage.error('获取礼物列表失败');
    } finally {
        loading.value = false;
    }
};

// 获取默认图标
const getDefaultIcon = (id) => {
    return 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png';
};

// 组件挂载时获取礼物列表
onMounted(() => {
    getGiftList();
});

// 切换选中状态（支持多选）
const toggleItemSelection = (index) => {
    rewardItems.value[index].active = !rewardItems.value[index].active;
    
    // 如果取消选中，数量清零
    if (!rewardItems.value[index].active) {
        rewardItems.value[index].count = 0;
    } 
    // 如果选中且数量为0，设为1

    else if (rewardItems.value[index].count === 0) {
        rewardItems.value[index].count = 1;
    }
};

// 增加数量
const increaseCount = (index) => {
    rewardItems.value[index].count++;
    
    // 如果增加数量，自动选中该项
    if (rewardItems.value[index].count > 0 && !rewardItems.value[index].active) {
        rewardItems.value[index].active = true;
    }
};

// 减少数量
const decreaseCount = (index) => {
    if (rewardItems.value[index].count > 0) {
        rewardItems.value[index].count--;
        
        // 如果数量变为0，取消选中
        if (rewardItems.value[index].count === 0) {
            rewardItems.value[index].active = false;
        }
    }
};

// 提交打赏
const submitReward = async () => {
    const selectedItems = rewardItems.value.filter(item => item.active && item.count > 0);
    
    if (selectedItems.length === 0) {
        ElMessage.warning('请选择至少一项打赏内容');
        return;
    }

    if(store.user.integral < selectedItems.reduce((sum, item) => sum + item.integerPrice * item.count, 0)){
        ElMessage.warning('您的豆豆不足，请先充值');
        router.push('/user/recharge');
        return;
    }
    
    try {
        loading.value = true;
        
        // 逐个发送打赏请求
        for (const item of selectedItems) {
            await orderApi.giveGift({
                bookId: props.bookId,
                giftId: item.id,
                num: item.count
            });
        }
        
        ElMessage.success('打赏成功！感谢您的支持！');
        emit('reward-success', {
            bookId: props.bookId,
            items: selectedItems.map(item => ({
                id: item.id,
                count: item.count
            }))
        });

        // 更新用户积分信息
        await store.fetchLatestUserInfo();
        
        // 重置并关闭弹窗
        rewardItems.value.forEach(item => {
            item.count = 0;
            item.active = false;
        });
        dialogVisible.value = false;
    } catch (error) {
        console.error('打赏失败:', error);
        ElMessage.error('打赏失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};
</script>

<style lang="scss" scoped>
.interactive-reward-dialog {
    :deep(.el-dialog) {
        background: linear-gradient(to bottom, #F1E4FE, #F3F9FF) !important;
    }

    :deep(.el-dialog__header) {
        text-align: center;
        margin-bottom: 10px;

        .el-dialog__title {
            font-size: 18px;
            font-weight: bold;
        }
    }
    
    .interactive-title{
        font-size: 22px;
        font-weight: bold;
        margin-bottom: 25px;
        text-align: center;
    }

    .interactive-items-container {
        max-height: 600px;
        overflow-y: auto;
        padding: 5px;
        margin-bottom: 20px;

        &::-webkit-scrollbar {
            width: 6px;
        }
        
        &::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        
        &::-webkit-scrollbar-thumb {
            background: #0A2463;
            border-radius: 3px;
        }
    }

    .interactive-items {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
        
        .reward-item {
            aspect-ratio: 1 / 1;
            border: 1.5px solid #ebebeb;
            border-radius: 12px;
            padding: 15px;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            flex-direction: column;
            position: relative;
            background-color: white;

            &.active {
                border-color: #0A2463;
                background-color: rgba(10, 36, 99, 0.05);
                box-shadow: 0 2px 8px rgba(10, 36, 99, 0.1);
            }

            .item-header {
                flex: 1;
                display: flex;
                justify-content: center;
                align-items: center;
                position: relative;
                margin-bottom: 12px;

                .item-icon {
                    width: 60px;
                    height: 60px;
                    object-fit: contain;
                }

                .check-mark {
                    position: absolute;
                    top: -8px;
                    right: -8px;
                    width: 24px;
                    height: 24px;
                    background-color: #0A2463;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: white;
                    font-size: 14px;
                }
            }

            .item-body {
                display: flex;
                flex-direction: column;
                align-items: center;
                margin-top: 10px;

                .item-name {
                    font-size: 16px;
                    font-weight: 500;
                    margin-bottom: 6px;
                    display: flex;
                    align-items: center;

                    .hot-tag {
                        background-color: #FF7C6A;
                        color: white;
                        font-size: 12px;
                        padding: 1px 5px;
                        border-radius: 4px;
                        margin-left: 6px;
                    }
                }

                .item-price {
                    font-size: 14px;
                    color: #999;
                    margin-bottom: 12px;
                }

                .item-counter {
                    display: flex;
                    align-items: center;
                    margin-top: 5px;

                    .counter-btn {
                        width: 28px;
                        height: 28px;
                        padding: 0;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border: 1px solid #ddd;
                        font-size: 16px;

                        &.minus {
                            border-radius: 4px 0 0 4px;
                        }

                        &.plus {
                            border-radius: 0 4px 4px 0;
                        }
                    }

                    .count-value {
                        width: 40px;
                        height: 28px;
                        line-height: 28px;
                        text-align: center;
                        border-top: 1px solid #ddd;
                        border-bottom: 1px solid #ddd;
                        font-size: 16px;
                    }
                }
            }
        }
    }

    .reward-footer {
        text-align: center;
        margin-top: 15px;

        .submit-btn {
            width: 80%;
            height: 40px;
            background-color: #0A2463;
            border: none;
            border-radius: 20px;
            font-size: 16px;
        }
    }
}
</style>