<template>
    <view class="container">
        
        <!-- #ifdef H5 -->
        <video 
            id="video" 
            object-fit="fill"
            style="width:100vw; height:100vh;"
            :show-center-play-btn="true"
            :show-fullscreen-btn="true" 
            :show-play-btn="false" 
            :show-mute-btn="true"
            :controls="false"
            :autoplay="true"
            :muted="false"
            >
        </video>
        <!-- #endif -->

        <!-- #ifdef MP-WEIXIN -->
        <live-player
            style="width: 100vw; height: 100vh; "
            object-fit="fillCrop"
            id="main"
            :src="roomInfo?.state == 1 ? roomInfo.pull_stream_url: ''"
            mode="live"
            :autoplay="true"
            @statechange="statechange"
        />
        <!-- #endif -->

        <!-- 房间信息 -->
        <view id="room-info">
            <view class="item tips" v-if="roomInfo?.state != 1" >还未开播</view>
            <view class="item title">{{ roomInfo.title }}</view>
            <view class="item introduce">{{ roomInfo.introduce }}</view>
        </view>

        <!-- 操作栏 -->
        <view id="action-bar" v-if="!(roomInfo?.state != 1)">
            <view class="item shopcarts" @click="shopCartIconClickEvent">
                <text class="zgf-iconfont icon-zgf-cloud-liveshangpin"></text>
            </view>
        </view>

        <!-- 购物车列表 -->
        <view id="shopcarts-box" v-if="isShowShopCart">
            <view class="close" @click="shopCartIconClickEvent">
                <u-icon name="close" size="28"></u-icon>
            </view>

            <view 
                class="item" 
                v-for="(item, index) in shopCarts" 
                :key="item.id"
                @click="shopCartItemClickEvent(item)">
                <view class="serial">{{ item.sort }}</view>
                <view class="thumb">
                    <image 
                        :src="img(item.thumb)" 
                        mode="heightFix">
                    </image>
                </view>
                <view class="info">
                    <view class="name">{{ item.name }}</view>
                    <view class="description">{{ item.description }}</view>
                </view>
                <view class="arrow-right">
                    <u-icon name="arrow-right" color="#ccc" size="16"></u-icon>
                </view>
            </view>

            <u-empty v-if="shopCarts.length <= 0"></u-empty>
        </view>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, watchEffect } from 'vue';
import { getRoomInfoData } from '@/addon/zgf_cloud_live/api/live_stream'
import { getRoomShopCartData } from '@/addon/zgf_cloud_live/api/room'
import { onLoad } from '@dcloudio/uni-app'
import { img, redirect } from '@/utils/common';


const roomId = ref<number>(0)
onLoad(async(e) => {
    if(e?.id) roomId.value = Number(e?.id);
});



// 是否显示购物车
const isShowShopCart = ref(false);
// 房间信息
const roomInfo = ref<AnyObject>({});
// 购物车列表
const shopCarts = ref<Array<AnyObject>>([]);
// 请求房间信息状态
const requestRoomInfoState = ref<boolean>(false);
// 房间信息定时器
let requestRoomInfoTimer:NodeJS.Timeout | null = null;

// 请求购物车状态
const requestRoomShopCartsState = ref<boolean>(false);
// 购物车定时器
let requestRoomShopCartTimer:NodeJS.Timeout | null = null;

watchEffect(() => {
    // 设置标签
    uni.setNavigationBarTitle({
        title: roomInfo?.value?.title || ''
    });

    // 启动定时器

    // 信息定时器
    if(requestRoomInfoTimer != null) clearInterval(requestRoomInfoTimer);
    requestRoomInfoTimer = setInterval(async () => {
        if(requestRoomInfoState.value) return;
        try {
            requestRoomInfoState.value = true;
            const roomInfoResult:AnyObject = await getRoomInfoData(roomId.value) as AnyObject;
            const { data } = roomInfoResult;
            if(!(JSON.stringify(roomInfo.value) === JSON.stringify(data))) {
                roomInfo.value = data;
            }
        } finally {
            requestRoomInfoState.value = false;
        }
    }, 1000 * 1);

    // 购物车定时器
    if(requestRoomShopCartTimer != null) clearInterval(requestRoomShopCartTimer);
    requestRoomShopCartTimer = setInterval(async () => {
        if(requestRoomShopCartsState.value) return;
        try {
            requestRoomShopCartsState.value = true;
            const roomShopCartResult:AnyObject = await getRoomShopCartData(roomId.value) as AnyObject;
            const { data } = roomShopCartResult;
            if(!(JSON.stringify(shopCarts.value) === JSON.stringify(data))) {
                shopCarts.value = data;
            }
        } finally {
            requestRoomShopCartsState.value = false;
        }
    }, 1000 * 1);    
})

async function loadRoomInfo(id: number) {
    try {
        // 获得基础信息
        const roomInfoResult:AnyObject = await getRoomInfoData(id) as AnyObject;
        roomInfo.value = roomInfoResult.data;
        
        // 购物车
        const roomShopCartResult:AnyObject = await getRoomShopCartData(id) as AnyObject;
        shopCarts.value = roomShopCartResult.data;
    } catch(e) {
        uni.showModal({
            content: '房间信息获取失败',
            showCancel: false
        })
    }
    // console.log('ss', roomInfoResult)
}


// #ifdef H5
import Hls from 'hls.js';
let hls = null;

watch(roomInfo, async (newValue, oldValue) => {
    if (newValue) {
        if(newValue.state == 1) {
            setPlay();
        } else {
            // 停止播放
            if(hls) {
                hls.destroy();
            }
        }
    }
})


onMounted((e) => {
    loadRoomInfo(roomId.value);
});


// 设置播放
function setPlay() {
    const videoDom: HTMLVideoElement | undefined = document.getElementById('video')?.getElementsByTagName('video')[0];
    if (videoDom && Hls.isSupported()) {
        hls = new Hls();
        hls.loadSource(roomInfo.value.pull_stream_url);
        hls.attachMedia(videoDom);
        hls.on(Hls.Events.MANIFEST_PARSED, function () {
            videoDom.play();
        });

        hls.on(Hls.Events.ERROR, (event, data) => {
            uin.showToast({
                title: '播放失败，请联系管理员',
                icon: 'none'
            });
            console.error('Error:', data);
        });
    } else if (videoDom && videoDom.canPlayType('application/vnd.apple.mpegurl')) {
        // 如果是支持 HLS 的浏览器 (如 Safari)
        videoDom.src = roomInfo.value.pull_stream_url;
        videoDom.addEventListener('loadedmetadata', () => {
            videoDom.play();
        });
    }
}
// #endif

/**
 * 购物车图标点击事件
 */
function shopCartIconClickEvent() {
    isShowShopCart.value = !isShowShopCart.value;
}

// 点击商品
function shopCartItemClickEvent(item) {
    
    // #ifdef H5
     window.open(item.link, '_blank');  // 也可以指定 URL 来打开特定的页面
    // #endif

    // <!-- #ifdef MP-WEIXIN -->
    switch(item.link_type) {
        case 1:
            redirect({
                url: `/addon/zgf_cloud_live/pages/live_stream/webview?url=${item.link}`,
                mode: 'navigateTo',
            } as redirectOptions);
            break;
        case 2:
            redirect({
                url: item.link,
                mode: 'navigateTo',
            } as redirectOptions);
            break;
    }
    // <!-- #endif -->
}
</script>
<style lang="scss" scoped>
    @import "@/addon/zgf_cloud_live/static/iconfont.css";

    .container{
        line-height:0rpx;
    }

    #room-info{
        // border:solid 1px red;
        z-index: 8888;
        width:400rpx;
        min-height:200rpx;
        max-height:350rpx;
        position:fixed;
        bottom:0rpx;
        color:#fff;
        padding:0rpx 20rpx;
        line-height:45rpx;
        overflow-y:scroll;

        &::-webkit-scrollbar{
            display:block;
            height:8rpx !important;
            width: 8rpx !important;
        }

        &::-webkit-scrollbar-thumb { 
            border-radius: 8px; 
            background-color: #fff;
        }

        .item{
            margin-bottom:10rpx;
        }

        .tips{
            color:rgb(184, 79, 79);
            font-size:32rpx;
        }

        .title{
            font-size:32rpx;
            font-weight: bold;
            color:#fff;

        }

        .introduce{
            font-size:26rpx;
            line-height:38rpx;
        }
    }

    #action-bar{
        z-index: 8888;
        position:fixed;
        right:20rpx;
        bottom:20rpx;
        color:#fff;
        padding:10rpx;

        .item{
            border-radius: 90rpx;
            text-align: center;
            width:90rpx;
            line-height:90rpx;
            height:90rpx;
            background:#fff;
            // border:solid 1px red;
            
            .zgf-iconfont{
                color:rgb(184, 79, 79);;
                font-size:40rpx;
            }
        }
    }

    #shopcarts-box{
        z-index: 9999;
        position:fixed;
        bottom:0rpx;
        border-top-left-radius: 20rpx;
        border-top-right-radius: 20rpx;
        right:0rpx;
        left:0rpx;
        min-height:300rpx;
        max-height:600rpx;
        background:#fff;
        padding:50rpx 25rpx 0rpx 25rpx;
        overflow-y:scroll;
        
        .close{
            top:20rpx;
            position: absolute;
            right:20rpx;
        }

        .item{
            border-bottom:solid 2rpx #ccc;
            min-height:120rpx;
            line-height:40rpx;
            display:flex;
            align-items: center;
            padding:25rpx 0rpx;

            .serial{
                font-size:32rpx;
                font-weight: bold;
                width:40rpx;
                display:flex;
                align-items: center;
                justify-content: center;
                padding:20rpx;
            }

            .thumb{
                overflow: hidden;
                width:120rpx;
                height:120rpx;
                border-radius: 10rpx;
                image{
                    border-radius: 10rpx;
                    width:100%;
                    height:100%;
                }
            }

            .info{
                margin:0rpx 6rpx 0rpx 20rpx;
                flex-basis:100rpx;
                flex-grow: 1;

                .name{
                    font-size:32rpx;
                    font-weight: 700;
                }

                .description{
                    text-align: left;
                    color:#666666;
                    margin-top:10rpx;
                    line-height:30rpx;
                    font-size: 26rpx;
                }
            }

            .arrow-right{
                display:flex;
                justify-content: center;
                align-items: center;
            }
        }
    }
</style>
