<template>
    <div ref="playerContainer" class="hk-video-player">
        <div id="play_window"></div>
        <div v-if="showWdn || showFull" class="play-control">
            <el-popover class="box-item" placement="top" width="180px">
                <div class="flex-center flex-gap-10">
                    <i
                        class="fvue-icon fvue-icon-yifenping"
                        title="1x1"
                        @click="onChangeWdnNum(1)"
                    ></i>
                    <i
                        class="fvue-icon fvue-icon-sifenping"
                        title="2x2"
                        @click="onChangeWdnNum(2)"
                    ></i>
                    <i
                        class="fvue-icon fvue-icon-jiufenping"
                        title="3x3"
                        @click="onChangeWdnNum(3)"
                    ></i>
                    <i
                        class="fvue-icon fvue-icon-shiliufenping"
                        title="4x4"
                        @click="onChangeWdnNum(4)"
                    ></i>
                </div>
                <template #reference>
                    <i v-if="showWdn" class="fvue-icon fvue-icon-fenping"></i>
                </template>
            </el-popover>
            <i
                v-if="showFull"
                class="fvue-icon fvue-icon-quanping"
                title="全屏"
                @click="onSetFull"
            ></i>
        </div>
    </div>
</template>
<script lang="ts" name="HKH5Player" setup>
import {
    computed,
    defineEmits,
    defineExpose,
    defineProps,
    onBeforeUnmount,
    onMounted,
    ref
} from 'vue'

const props = defineProps({
    split: {
        type: Number,
        default: 2
    },
    showWdn: {
        type: Boolean,
        default: true
    },
    showFull: {
        type: Boolean,
        default: true
    }
})

const player = ref<any>(null)
const playerContainer = ref<HTMLElement>()
const mode = 'mse' // 可选值:  mse: 普通模式 | decoder: 高级模式
const token = ''
let resizeObserver: ResizeObserver | null = null

onMounted(() => {
    initPlayer()
    setupResizeObserver()
})

onBeforeUnmount(() => {
    stopAllPlay()
    resizeObserver?.disconnect()
    resizeObserver = null
})

const emit = defineEmits(['update:split'])

defineExpose({
    realplay,
    stopPlay,
    stopAllPlay
})

const splitNum = computed({
    get: () => props.split,
    set: (val: number) => {
        emit('update:split', val)
    }
})

function initPlayer() {
    player.value = new JSPlugin({
        szId: 'play_window', //父窗口id，需要英文字母开头 必填
        szBasePath: './dist', // 必填,与h5player.min.js的引用目录一致
        openDebug: true,
        mseWorkerEnable: true, //是否开启多线程解码，分辨率大于1080P建议开启，否则可能卡顿
        bSupporDoubleClickFull: true, //是否支持双击全屏，true-双击是全屏；false-双击无响
        // 当容器div#play_window有固定宽高时，可不传iWidth和iHeight，窗口大小将自适应容器宽高
        // iWidth: 600,
        // iHeight: 400,
        // 分屏播放，默认最大分屏4*4
        iMaxSplit: 4,
        iCurrentSplit: props.split,
        oStyle: {
            borderSelect: '#43a1ff'
        }
    })
}

const onChangeWdnNum = (num: number) => {
    // 避免重置不了回原本布局
    // if (splitNum.value !== num) {
    splitNum.value = num
    player.value?.JS_ArrangeWindow(num).then(
        () => {
            console.log(`arrangeWindow to ${num}x${num} success`)
        },
        (e) => {
            console.error(e)
        }
    )
    // }
}
const onSetFull = () => {
    player.value?.JS_FullScreenDisplay(true).then(
        () => {
            console.log(`wholeFullScreen success`)
        },
        (e) => {
            console.error(e)
        }
    )
}

function realplay(playURL: string, playerIndex?: number) {
    const index = playerIndex !== undefined ? playerIndex : player.value?.currentWindowIndex || 0

    player.value?.JS_SetTraceId(index, true)
    player.value?.JS_Play(playURL, { playURL, mode, keepDecoder: 0, token }, index).then(
        () => {
            console.log('realplay success')
            player.value?.JS_GetTraceId(index).then((id) => {
                console.log('traceid:', id)
            })
        },
        (e) => {
            console.error(e)
        }
    )
}

function stopAllPlay() {
    player.value?.JS_StopRealPlayAll().then(
        () => {
            console.log('stopAllPlay success')
        },
        (e) => {
            console.error(e)
        }
    )
}

function stopPlay(playerIndex?: number) {
    const index = playerIndex !== undefined ? playerIndex : player.value?.currentWindowIndex || 0
    player.value?.JS_Stop(index).then(
        () => {
            console.log('stop realplay success')
        },
        (e) => {
            console.error(e)
        }
    )
}

function setupResizeObserver() {
    if (!playerContainer.value) return

    resizeObserver = new ResizeObserver((entries) => {
        for (const entry of entries) {
            const { width, height } = entry.contentRect
            console.log(`容器尺寸变化: ${width}x${height}`)
            // 防抖处理，避免频繁调用
            if (player.value) {
                player.value.JS_Resize()
            }
        }
    })
    resizeObserver.observe(playerContainer.value)
}
</script>

<style lang="scss" scoped>
.hk-video-player {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}

#play_window {
    width: 100% !important;
    height: calc(100% - 50px);
    box-sizing: border-box;
}

.play-control {
    width: 100%;
    height: 50px;
    box-sizing: border-box;
    background-color: mix(rgb(48, 47, 47), var(--theme-system-bg), 2%);
    box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 0 20px;
    column-gap: 10px;

    .fvue-icon {
        font-size: 20px;
    }
}
</style>
