<template>
    <view :style="warpCss" class="overflow-hidden relative" v-if="diyComponent && diyComponent.goods && Object.keys(diyComponent.goods).length">
        <!-- 自定义头部 -->
        <view class="flex items-center left-0 right-0 z-10 bg-transparent detail-head"
            :class="{ 'fixed': diyStore.mode != 'decorate', 'absolute': diyStore.mode == 'decorate' }"
            :style="navbarInnerStyle">
            <view class="flex items-center text-[24rpx] px-[10rpx] py-[12rpx] mr-[20rpx]" v-if="diyComponent.diyInfo.menu.content.indexOf('visitorsModule') != -1 && diyComponent.goods.view_num" :style="menuStyle">
                <view class="relative" v-if="diyStore.mode == 'decorate'">
                    <image class="w-[30rpx] h-[30rpx] mr-[6rpx]" :src="img('addon/pintuan/diy/goods_detail/browsed_01.png')" mode="aspectFill" />
                    <image class="absolute left-[16rpx] -top-[2rpx] w-[10rpx] h-[8rpx]" :src="img('addon/pintuan/diy/goods_detail/browsed_02.png')" mode="aspectFill" />
                </view>
                <view class="like-button-container" v-else>
                    <view class="hearts-container">
                        <view v-for="heart in hearts" :key="heart.id" class="heart-bubble">
                            <image :src="img('addon/pintuan/diy/goods_detail/browsed_02.png')" class="heart-img" mode="widthFix" />
                        </view>
                    </view>

                    <image :src="img('addon/pintuan/diy/goods_detail/browsed_01.png')" class="like-button" :class="{ shake: isShaking }" mode="widthFix" />
                </view>
                <text>浏览</text>
                <text class="text-[28rpx]" :style="{color: diyComponent.diyInfo.menu.numTextColor}">{{formatViewNum(diyComponent.goods.view_num)}}</text>
            
                <text>人</text>
            </view>
            <view class="flex items-center text-[24rpx] px-[20rpx] py-[12rpx]" v-if="diyComponent.diyInfo.menu.content.indexOf('pintuanModule') != -1 && diyComponent.goods.member_num" :style="menuStyle">
                <view class="mr-[6rpx] flex items-center">
                    <template v-for="(item, index) in diyComponent.goods.member_list.slice(0, 3)" :key="index">
                        <image v-if="item.member?.headimg" class="w-[32rpx] h-[32rpx] rounded-[50rpx] relative" :class="{'-ml-[16rpx]': index}" :src="img(item.member?.headimg)" @error="item.member.headimg = 'static/resource/images/default_headimg.png'" mode="aspectFill" />
                        <image v-else class="w-[32rpx] h-[32rpx] rounded-[50rpx] relative" :class="{'-ml-[16rpx]': index}" :src="img('static/resource/images/default_headimg.png')" mode="aspectFill" />
                    </template>
                </view>
                <text>已参与</text>
                <text class="text-[28rpx]" :style="{color: diyComponent.diyInfo.menu.numTextColor}">{{formatViewNum(diyComponent.goods.member_num)}}</text>
                <text>人</text>
            </view>
        </view>

        <view class="fixed  right-0 z-100 bg-[rgba(0,0,0,.5)] flex flex-col p-[20rpx] gap-[26rpx]  topcalc" :style="sideMenuStyle">
            <view class="flex flex-col items-center justify-center" v-if="diyComponent.diyInfo.sideMenu.content.indexOf('index') != -1" @click="redirect({url: '/addon/pintuan/pages/index', mode: 'reLaunch'})">
                <text class="text-[34rpx] nc-iconfont nc-icon-shouyeV6xx11"></text>
                <text class="text-[20rpx] whitespace-nowrap mt-[10rpx]">首页</text>
            </view>
            <!-- <view class="flex flex-col items-center justify-center" v-if="diyComponent.diyInfo.sideMenu.content.indexOf('member') != -1" @click="redirect({url: '/addon/pintuan/pages/member/index'})">
                <text class="text-[34rpx] nc-iconfont nc-icon-a-wodeV6xx-36"></text>
                <text class="text-[20rpx] whitespace-nowrap mt-[10rpx]">我的</text>
            </view> -->
            <view class="flex flex-col items-center justify-center" v-if="diyComponent.diyInfo.sideMenu.content.indexOf('mySpell') != -1" @click="redirect({url: '/addon/pintuan/pages/my_spell'})">
                <text class="text-[34rpx] iconfont iconpintuanV6xx1"></text>
                <text class="text-[20rpx] whitespace-nowrap mt-[10rpx]">拼单</text>
            </view>
            <view class="flex flex-col items-center justify-center" v-if="diyComponent.diyInfo.sideMenu.content.indexOf('poster') != -1">
                <text class="text-[36rpx] nc-iconfont nc-icon-fenxiangV6xx" @click="openShareFn"></text>
                <text class="text-[20rpx] whitespace-nowrap mt-[10rpx]">海报</text>
            </view>
            <view class="flex flex-col items-center justify-center" @click="servicesPopFn" v-if="diyComponent.diyInfo.sideMenu.content.indexOf('service') != -1">
                <text class="text-[36rpx] nc-iconfont nc-icon-kefuV6xx-1"></text>
                <text class="text-[20rpx] whitespace-nowrap mt-[10rpx]">客服</text>
            </view>
            <!-- <view class="flex flex-col items-center justify-center" v-if="diyComponent.diyInfo.sideMenu.content.indexOf('order') != -1" @click="redirect({url: '/addon/pintuan/pages/order/list'})">
                <text class="text-[34rpx] iconfont iconquanbudingdan"></text>
                <text class="text-[20rpx] whitespace-nowrap mt-[10rpx]">订单</text>
            </view> -->
        </view>
        <image :style="mediumCss" class="w-[100%] block" :src="img(diyComponent.banner)" @click="imgListPreview(diyComponent.banner)" />
        
        <!-- 弹幕 -->
        <barrage-container v-if="diyComponent.diyInfo.barrage.isShow && Object.keys(barrageData).length && diyStore.mode != 'decorate'" :play="diyComponent.barragePlay" :textColor="diyComponent.diyInfo.barrage.textColor" :bgColor="barrageBgColor" :rounded="diyComponent.diyInfo.barrage.rounded" :data="barrageData"/>
        <!-- 背景音乐 -->
        <music-container 
          v-if="diyComponent.diyInfo.music && diyComponent.diyInfo.music.isShow && diyComponent.bg_music_url" 
          :src="diyComponent.diyInfo.music && img(diyComponent.bg_music_url)" 
          :autoplay="true" 
          :loop="true"
          :discImage="diyComponent.diyInfo.music && diyComponent.diyInfo.music.discImage || ''"
          ref="musicRef"
          :defaultRounded = "diyComponent.diyInfo.music && diyComponent.diyInfo.music.rounded"
          :defaultBgColor = "musicBgColor"
          :defaultTextColor = "diyComponent.diyInfo.music && diyComponent.diyInfo.music.textColor"
        ></music-container>

        <!-- 特效 -->
         
        <special-effects
            ref="fireworkEffects"
            :no-trail="true"
            :red-packet-images="listimg"
            :red-packet-use-images="true"
            :red-packet-min-size="50"
            :red-packet-max-size="30"
            :red-packet-min-amount="1.0"
            :red-packet-max-amount="88.8"
            :red-packet-density="5"
            :red-packet-speed="2.0"
            :red-packet-clickable="false"
            v-if="diyComponent.diyInfo.specialEffects.isShow"
        ></special-effects>
 
        <!-- 装修时，防止点击 -->
        <view v-if="diyStore.mode == 'decorate'" class="absolute z-100 top-0 right-0 bottom-0 left-0"></view>
        <online-service ref="onlineServiceRef" :data="config"></online-service>
    </view>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted,onUnmounted, nextTick, getCurrentInstance } from 'vue';
import {  onHide, onShow } from '@dcloudio/uni-app'
import { redirect, img, timeTurnTimeStamp } from '@/utils/common';
import useDiyStore from '@/app/stores/diy';
import useSystemStore from '@/stores/system'
import { getPintuanBuyerInfo, getPintuanConfig } from '@/addon/pintuan/api/pintuan'
import usePintuanGoodsDetailStore from '@/addon/pintuan/stores/goodsDetail';
import BarrageContainer from '@/components/barrage/container.vue';
import MusicContainer from '@/components/music/music-container.vue';
import SpecialEffects from '@/components/firework-effect/firework-effect.vue';
import onlineService from '@/components/online-service/online-service'
const listimg = ref<string[]>([])
const props = defineProps(['component', 'index', 'value', 'global']);
const diyStore = useDiyStore();
const emits = defineEmits(['loadingFn', 'update:componentIsShow']); //商品数据加载完成之后触发
const switchMedia: any = ref('img');
const videoContext: any = ref(null)
const swiperImageHeight = ref('100vw') // 轮播图高度
const musicRef = ref(null); // 音乐组件引用
const fireworkEffects = ref(null);

const diyComponent = computed(() => {
    if (diyStore.mode == 'decorate') {
        const obj = {
            member_num: 100,
            views: 1000,
            banner: img('static/resource/images/diy/shop_default.jpg'),
            goods:{
                pintuan_price: '100.00',
                member_num: '100',
                view_num: '100',
                member_list: [
                    { member: { headimg:'' } },
                    { member: { headimg:'' } },
                    { member: { headimg:'' } }
                ]
            },
            // 添加默認音樂配置
            music: {
                isShow: true,
                src: 'https://www.runoob.com/try/demo_source/horse.mp3', // 默認音樂，需要替換為實際音樂
                autoplay: true,
                loop: true
            }
        }
        emits('update:componentIsShow', true)
        return Object.assign({}, {diyInfo:  diyStore.value[props.index]}, obj);
    } else {
        emits('update:componentIsShow', true)
        return Object.assign({}, {diyInfo: props.component}, usePintuanGoodsDetailStore().goodsDetail);
    }
})

const warpCss = computed(() => {
    let style = '';
    style += 'position:relative;';
    if (diyComponent.value.diyInfo.componentStartBgColor && diyComponent.value.diyInfo.componentEndBgColor) style += `background:linear-gradient(${diyComponent.value.diyInfo.componentGradientAngle},${diyComponent.value.diyInfo.componentStartBgColor},${diyComponent.value.diyInfo.componentEndBgColor});`;
    else style += 'background-color:' + (diyComponent.value.diyInfo.componentStartBgColor || diyComponent.value.diyInfo.componentEndBgColor) + ';';

    if (diyComponent.value.diyInfo.componentBgUrl) {
        style += `background-image:url('${img(diyComponent.value.diyInfo.componentBgUrl)}');`;
        style += 'background-size: cover;background-repeat: no-repeat;';
    }

    if (diyComponent.value.diyInfo.topRounded) style += 'border-top-left-radius:' + diyComponent.value.diyInfo.topRounded * 2 + 'rpx;';
    if (diyComponent.value.diyInfo.topRounded) style += 'border-top-right-radius:' + diyComponent.value.diyInfo.topRounded * 2 + 'rpx;';
    if (diyComponent.value.diyInfo.bottomRounded) style += 'border-bottom-left-radius:' + diyComponent.value.diyInfo.bottomRounded * 2 + 'rpx;';
    if (diyComponent.value.diyInfo.bottomRounded) style += 'border-bottom-right-radius:' + diyComponent.value.diyInfo.bottomRounded * 2 + 'rpx;';
    return style;
})

/************ 自定义头部-start ****************/
const systemStore = useSystemStore()

// 导航栏内部盒子的样式
const navbarInnerStyle = computed(() => {
    let style = '';
    // 导航栏宽度，如果在小程序下，导航栏宽度为胶囊的左边到屏幕左边的距离
    // #ifdef MP
    let rightButtonWidth = systemStore.menuButtonInfo.width ? systemStore.menuButtonInfo.width * 2 + 'rpx' : '70rpx';
    style += 'height:' + systemStore.menuButtonInfo.height + 'px;';
    style += 'padding-right:calc(' + rightButtonWidth + ' + 30rpx);';
    style += 'padding-left: 30rpx;';
    style += 'padding-top:' + systemStore.menuButtonInfo.top + 'px;';
    style += 'padding-bottom: 8px;';
    // #endif

    // #ifdef H5
    style += 'height: 100rpx;';
    style += 'padding-right: 30rpx;';
    style += 'padding-left: 30rpx;';
    // #endif
    return style;
})
/************ 自定义头部-end ****************/

/************* 分享海报-start **************/
const openShareFn = () => {
    usePintuanGoodsDetailStore().setGoodsDetail({ isOpenSharePoster: true });
}
/************* 分享海报-end **************/

/************* 客服-start **************/
const onlineServiceRef = ref()
const servicesPopFn = ()=>{
    onlineServiceRef.value?.open()
}
const config = ref({})
const getPintuanConfigFn = () => {
    getPintuanConfig().then((res: any) => {
        config.value = res.data
    })
}
/************* 客服-end **************/
const mediumCss = computed(() => {
    let style = "";
    style += `height:${swiperImageHeight.value};`;
    return style;
})

//预览图片
const imgListPreview = (item: any) => {
    if (item === '') return false
    var urlList = []
    urlList.push(img(item))  //push中的参数为 :src="item.img_url" 中的图片地址
    uni.previewImage({
        indicator: "number",
        loop: true,
        urls: urlList
    })
}

const barrageData = ref<any[]>([])
const getBarrageInfoFn = () => {
    getPintuanBuyerInfo({
        pintuan_id: diyComponent.value.id || '',
        limit: diyComponent.value.diyInfo.barrage.num || 10
    }).then((res: any) => {
        barrageData.value = []
        if(res.data.data && res.data.data.length){
            barrageData.value = res.data.data.map((item: any) => {
                let obj = {}
                obj.time = item.create_time ? (timeTurnTimeStamp(item.create_time) * 1000) : 0
                obj.id = item.member_id
                obj.nickname = item.member.nickname
                obj.headimg = item.member.headimg
                return obj
            })
        }
    })
}

const initFn = () => {
    if (diyComponent.value?.goods_video != '') {
        switchMedia.value = 'video'
        videoContext.value = uni.createVideoContext('goodsVideo');
    }

    // 轮播图高度
    const screenWidth = uni.getSystemInfoSync().screenWidth
    swiperImageHeight.value = (screenWidth * diyComponent.value.banner_size.height / diyComponent.value.banner_size.width) * 2 + 'rpx'
// console.log(diyComponent.value,'???kk1')
//     // 特效 - 检查是否应该展示
//     const shouldShowSpecialEffect = () => {
//         if (!diyComponent.value.diyInfo.specialEffects.isShow) {
//             return false;
//         }

//         const pintuanId = diyComponent.value.id;
//         const maxShowTimes = diyComponent.value.diyInfo.specialEffects.num || 1;

//         if (!pintuanId) {
//             return false;
//         }

//         // 获取当前商品的特效展示次数记录
//         const storageKey = `pintuan_effect_count_${pintuanId}`;
//         const currentCount = uni.getStorageSync(storageKey) || 0;

//         if (currentCount >= maxShowTimes) {
//             return false;
//         }

//         // 增加展示次数
//         uni.setStorageSync(storageKey, currentCount + 1);
//         return true;
//     };

//     if (!shouldShowSpecialEffect()) {
//         return;
//     }
// diyInfo
 
    // 特效
    // if(diyComponent.value.bg_effect_child_type == 'firecrackers' && diyComponent.value.diyInfo.specialEffects.isShow){
    //     // 启动烟花特效
    //     console.log('🎆 启动烟花特效');
    //     if (fireworkEffects.value && typeof (fireworkEffects.value as any).handleShowEffect === 'function') {
    //         try {
    //             (fireworkEffects.value as any).handleShowEffect({
    //                 type: 'simple-firework',
    //                 duration: 10*1000 // 10秒烟花
    //             });
    //             console.log('🎆 烟花特效启动成功');
    //         } catch (error) {
    //             console.error('🎆 烟花特效启动失败:', error);
    //         }
    //     } else {0
    //         console.warn('🎆 特效组件未准备好');
    //     }
    // }else if(diyComponent.value.diyInfo.specialEffects.isShow && diyComponent.value.bg_effect_child_type){
    //     console.log('🎆 特效组件已准备就绪');
    //     if(diyComponent.value.bg_effect_child_type=='red_packet'){
    //         listimg.value =[
    //             img('/addon/pintuan/dtai/hongbao.png')
    //         ]
    //     }else if(diyComponent.value.bg_effect_child_type=='gift_box'){
    //         listimg.value =[
    //             img('/addon/pintuan/dtai/lihe.png')
    //         ]
    //     }else if(diyComponent.value.bg_effect_child_type=='big_wing'){
    //         listimg.value =[
    //             img('/addon/pintuan/dtai/yuangbao.png')
    //         ]
    //     }else if(diyComponent.value.bg_effect_child_type=='blessing'){
    //         listimg.value =[
    //             img('/addon/pintuan/dtai/huaban.png')
    //         ]
    //     }else if(diyComponent.value.bg_effect_child_type=='kongmin_light'){
    //         listimg.value =[
    //             img('/addon/pintuan/dtai/kmd.png')
    //         ]
    //     }else if(diyComponent.value.bg_effect_child_type=='i_love_you'){
    //         listimg.value =[
    //             img('/addon/pintuan/dtai/aixin.png')
    //         ]
    //     }

        

    //     // 启动红包雨特效
    //     setTimeout(() => {
    //         if (fireworkEffects.value && typeof (fireworkEffects.value as any).handleShowEffect === 'function') {
    //             try {
    //                 (fireworkEffects.value as any).handleShowEffect({
    //                     type: 'red-packet-rain',
    //                     duration:  5*1000, // 15秒红包雨
    //                 });
    //             } catch (error) {
    //                 console.error('🧧 红包雨特效启动失败:', error);
    //             }
    //         } else {
    //             console.warn('🧧 特效组件未准备好');
    //         }
    //     }, 1000);
    // }
    specialEffectsFunction()
}
// 特效定时器管理
const effectTimers = ref<any[]>([]) // 存储所有特效定时器ID
const isPageVisible = ref(true) // 页面是否可见

const specialEffectsFunction = () => { 
    // 特效 - 检查是否应该展示（注释保留根据goodsId判断的功能）
    // const shouldShowSpecialEffect = () => {
    //     if (!diyComponent.value.diyInfo.specialEffects.isShow) {
    //         return false;
    //     }

    //     const pintuanId = diyComponent.value.id;
    //     const maxShowTimes = diyComponent.value.diyInfo.specialEffects.num || 1;

    //     if (!pintuanId) {
    //         return false;
    //     }

    //     // 获取当前商品的特效展示次数记录
    //     const storageKey = `pintuan_effect_count_${pintuanId}`;
    //     const currentCount = uni.getStorageSync(storageKey) || 0;

    //     console.log(`🎆 商品${pintuanId}特效展示次数: ${currentCount}/${maxShowTimes}`);

    //     if (currentCount >= maxShowTimes) {
    //         console.log(`🎆 商品${pintuanId}特效已达到最大展示次数${maxShowTimes}，不再展示`);
    //         return false;
    //     }

    //     // 增加展示次数
    //     uni.setStorageSync(storageKey, currentCount + 1);
    //     console.log(`🎆 商品${pintuanId}特效展示次数更新为: ${currentCount + 1}`);

    //     return true;
    // };

    // if (!shouldShowSpecialEffect()) {
    //     return;
    // }

    // 检查特效是否开启
    if (!diyComponent.value.diyInfo.specialEffects.isShow) {
        return;
    }


    // 根据 diyComponent.value.specialEffects.num 来循环特效次数
    // console.log(diyComponent.value.diyInfo )
    const effectNum = diyComponent.value.diyInfo.specialEffects.num || 1;
    console.log(`🎆 特效将执行 ${effectNum} 次`);

    // 设置特效图片
    if(diyComponent.value.bg_effect_child_type){
         if(diyComponent.value.bg_effect_child_type=='red_packet'){
            listimg.value =[
                img('/addon/pintuan/dtai/hongbao.png')
            ]
        }else if(diyComponent.value.bg_effect_child_type=='gift_box'){
            listimg.value =[
                img('/addon/pintuan/dtai/lihe.png')
            ]
        }else if(diyComponent.value.bg_effect_child_type=='big_wing'){
            listimg.value =[
                img('/addon/pintuan/dtai/yuangbao.png')
            ]
        }else if(diyComponent.value.bg_effect_child_type=='blessing'){
            listimg.value =[
                img('/addon/pintuan/dtai/huaban.png')
            ]
        }else if(diyComponent.value.bg_effect_child_type=='kongmin_light'){
            listimg.value =[
                img('/addon/pintuan/dtai/kmd.png')
            ]
        }else if(diyComponent.value.bg_effect_child_type=='i_love_you'){
            listimg.value =[
                img('/addon/pintuan/dtai/aixin.png')
            ]
        }
        console.log(listimg.value,'特效图片列表')
    }

    // 如果是烟花特效，保持原有间隔
    if(diyComponent.value.bg_effect_child_type == 'firecrackers'){
        for (let i = 0; i < effectNum; i++) {
            const timerId = setTimeout(() => {
                executeEffect(i);
            }, i * 12000); // 烟花每12秒执行一次
            effectTimers.value.push(timerId);
        }
    } else {
        // 红包雨特效使用更短的间隔，让效果更连续
        for (let i = 0; i < effectNum; i++) {
            const timerId = setTimeout(() => {
                executeEffect(i);
            }, i * 6000); // 红包雨每6秒执行一次，减少停顿感
            effectTimers.value.push(timerId);
        }
    }
}
 // 特效执行函数
 const executeEffect = (index: number) => {
        // 检查页面是否还可见，如果不可见则不执行特效
        if (!isPageVisible.value) {
            console.log(`🎆 页面不可见，跳过第 ${index + 1} 次特效`);
            return;
        }

        console.log(`🎆 执行第 ${index + 1} 次特效`);

        if(diyComponent.value.bg_effect_child_type == 'firecrackers'){
            // 启动烟花特效
            console.log('🎆 启动烟花特效');
            if (fireworkEffects.value && typeof (fireworkEffects.value as any).handleShowEffect === 'function') {
                try {
                    (fireworkEffects.value as any).handleShowEffect({
                        type: 'simple-firework',
                        duration: 10*1000 // 10秒烟花
                    });
                    console.log('🎆 烟花特效启动成功');
                } catch (error) {
                    console.error('🎆 烟花特效启动失败:', error);
                }
            } else {
                console.warn('🎆 特效组件未准备好');
            }
        }else if(diyComponent.value.bg_effect_child_type){
            // 启动红包雨特效
            console.log('🧧 启动红包雨特效');
            if (fireworkEffects.value && typeof (fireworkEffects.value as any).handleShowEffect === 'function') {
                try {
                    (fireworkEffects.value as any).handleShowEffect({
                        type: 'red-packet-rain',
                        duration: 8*1000, // 8秒红包雨，比间隔时间稍短避免重叠
                    });
                    console.log('🧧 红包雨特效启动成功');
                } catch (error) {
                    console.error('🧧 红包雨特效启动失败:', error);
                }
            } else {
                console.warn('🧧 特效组件未准备好');
            }
        }
    };
// 清理所有特效定时器
const clearAllEffectTimers = () => {
    console.log('🧹 清理所有特效定时器，共', effectTimers.value.length, '个');
    effectTimers.value.forEach(timerId => {
        clearTimeout(timerId);
    });
    effectTimers.value = [];
}

// 停止所有特效
const stopAllEffects = () => {
    console.log('🛑 停止所有特效');

    // 清理定时器
    clearAllEffectTimers();

    // 停止特效组件
    if (fireworkEffects.value) {
        try {
            // 使用新的停止所有特效方法
            if (typeof (fireworkEffects.value as any).stopAllEffects === 'function') {
                (fireworkEffects.value as any).stopAllEffects();
            } else {
                // 兼容旧版本，分别停止
                if (typeof (fireworkEffects.value as any).stopFireworks === 'function') {
                    (fireworkEffects.value as any).stopFireworks();
                }
                if (typeof (fireworkEffects.value as any).stopRedPacketRain === 'function') {
                    (fireworkEffects.value as any).stopRedPacketRain();
                }
            }
        } catch (error) {
            console.warn('🛑 停止特效时出错:', error);
        }
    }
}

// 页面显示时的处理
onShow(() => {
    console.log('📱 页面显示');
    isPageVisible.value = true;
});

// 页面隐藏时的处理
onHide(() => {
    console.log('📱 页面隐藏，停止所有特效');
    isPageVisible.value = false;
    stopAllEffects();
});

// 组件卸载时的处理
onUnmounted(() => {
    console.log('📱 组件卸载，清理所有资源');
    isPageVisible.value = false;
    stopAllEffects();
});
const hearts = ref([]);
let heartCounter = 0;

const popHearts = () => {
  for (let i = 0; i < 3; i++) {
    setTimeout(() => {
      const newHeart = { id: heartCounter++ };
      hearts.value.push(newHeart);

      setTimeout(() => {
        const index = hearts.value.findIndex(h => h.id === newHeart.id);
        if (index !== -1) {
          hearts.value.splice(index, 1);
        }
      }, 1600);
    }, i * 200);
  }
};

let intervalId = null;

const isShaking = ref(false);

const triggerShake = () => {
  isShaking.value = true;
  setTimeout(() => {
    isShaking.value = false;
  }, 600); // 动画时间
};

onUnmounted(() => {
  clearInterval(intervalId);
});
onMounted(() => {
    intervalId = setInterval(() => {
        popHearts();
        triggerShake(); // 摆动一次
    }, 2000);
    // 装修模式下刷新
    if (diyStore.mode == 'decorate') {
        barrageData.value = [{headimg:''},{headimg:''},{headimg:''},{headimg:''}]
    } else {
        initFn()
        getBarrageInfoFn()
        getPintuanConfigFn()
    }
});

// 弹幕背景颜色
const barrageBgColor = computed(() => {
    return `${diyComponent.value.diyInfo.barrage.bgColor}${opacityToHex(diyComponent.value.diyInfo.barrage.opacity/10)}`;
});
// 侧边栏菜单颜色 
const sideMenuStyle = computed(() => {
    let style = '';
    style += `background:${diyComponent.value.diyInfo.sideMenu.bgColor}${opacityToHex(diyComponent.value.diyInfo.sideMenu.opacity/10)};`;
    if(diyComponent.value.diyInfo.menu.textColor){ style += `color:${diyComponent.value.diyInfo.sideMenu.textColor};`; }

    if(diyComponent.value.diyInfo.sideMenu.rounded){ 
        style += `border-top-left-radius:${diyComponent.value.diyInfo.sideMenu.rounded * 2}rpx;`;
        style += `border-bottom-left-radius:${diyComponent.value.diyInfo.sideMenu.rounded * 2}rpx;`;
    }
    console.log("侧边栏",diyComponent.value.diyInfo.sideMenu.rounded,style)
    return style;
});
// 顶部菜单颜色
const menuStyle = computed(() => {
    let style = '';
    style += `background:${diyComponent.value.diyInfo.menu.bgColor}${opacityToHex(diyComponent.value.diyInfo.menu.opacity/10)};`;
    if(diyComponent.value.diyInfo.menu.textColor){ style += `color:${diyComponent.value.diyInfo.menu.textColor};`; }
    if(diyComponent.value.diyInfo.menu.rounded){ style += `border-radius:${diyComponent.value.diyInfo.menu.rounded * 2}rpx;`; }
    return style;
});
// 背景音乐颜色
const musicBgColor = computed(() => {
    let bgColor = ''
    if(diyComponent.value.diyInfo.music){
        bgColor=`${diyComponent.value.diyInfo.music.bgColor}${opacityToHex(diyComponent.value.diyInfo.music.opacity/10)}`
    }
    return bgColor;
});


const opacityToHex = (opacity:any) => {
    // 确保透明度在0-1范围内
    const clamped = Math.max(0, Math.min(1, opacity));
    // 转换为0-255的整数
    const decimal = Math.round(clamped * 255);
    // 转换为十六进制并确保两位
    const hex = decimal.toString(16).padStart(2, '0').toUpperCase();
    return hex;
}
const formatViewNum = (num: number|string) => {
    num = Number(num);
    if (num < 10000) return num;
    return (num / 10000).toFixed(num % 10000 === 0 ? 0 : 1) + '万';
}
</script>
<style lang="scss" scoped>
.arrow-left {
    background: rgba(153, 153, 153, 0.1);
    border: 1rpx solid rgba(221, 221, 221, 0.3);
}

/* 主容器 */
.like-button-container {
    margin-right: 10rpx;
  position: relative;
  display: inline-block;
//   overflow: hidden;
//   margin-top: 30rpx;
}

/* 点赞按钮的样式 */
.like-button {
  width: 30rpx;
  height: auto;
  transform-origin: bottom center;
}

/* 摆动动画 */
.shake {
  animation: shake-hand 0.6s ease-in-out 1; /* 播放一次 */
}

@keyframes shake-hand {
  0% { transform: rotate(0deg); }
  25% { transform: rotate(-10deg); }
  50% { transform: rotate(10deg); }
  75% { transform: rotate(-10deg); }
  100% { transform: rotate(0deg); }
}


/* 爱心容器 */
.hearts-container {
  position: absolute;
  bottom: 10rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 10rpx;
  height: 10rpx;
  pointer-events: none;
}

.heart-bubble {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform-origin: center bottom;
  animation: bubble-up 1.5s ease-out forwards;
}

.heart-img {
  width: 20rpx;
  height: auto;
}

@keyframes bubble-up {
  0% {
    transform: translateX(-50%) translateY(0) scale(0.3);
    opacity: 1;
  }
  20% {
    transform: translateX(-50%) translateY(-30rpx) scale(0.7);
  }
  100% {
    transform: translateX(-50%) translateY(-120rpx) scale(1.2);
    opacity: 0;
  }
}
.topcalc{
    top: calc(220rpx + var(--status-bar-height));
}
</style>
