<template>
    <div class="video-box">
        <video
            v-for="(i, index) in data"
            id="video"
            :key="index"
            class="video-item"
            x5-video-player-type="h5-page"
            controlslist="nodownload"
            disable-picture-in-picture
            webkit-playsinline=""
            x-webkit-airplay=""
            playsinline
            :controls="controls"
            autoplay
            :src="changeUrl(i.src)"
            @error="filesError"
        />
    </div>
</template>

<script lang="ts">
import { defineComponent, inject, nextTick, onMounted, ref } from 'vue'
import { buildProps } from '@kankan-components/utils'
import type { PropType } from 'vue'

const props = buildProps({
    controls: {
        type: Boolean,
        default: true,
    },
    metasHeight: {
        type: Number,
        default: null,
    },
    data: {
        type: Array as PropType<
            {
                src: string
            }[]
        >,
        default: () => [],
    },
})
const loading = ref(true)

export default defineComponent({
    name: 'UIMetasVideo',
    props,
    setup: () => {
        const filesError = () => {
            loading.value = false
        }
        const __sdk: any = inject('__sdk')
        function changeUrl(name: string, now?: string) {
            if (name.includes('http')) {
                return name
            } else {
                if ((typeof name === 'string' && name.slice(0, 4) == 'blob') || (typeof name === 'string' && name.slice(0, 10) == 'data:image')) {
                    return name
                } else {
                    return __sdk.resource.getUserResourceURL(name, false, now)
                }
            }
        }
        onMounted(() => {
            nextTick(() => {
                const myVideo: HTMLElement | null = document.querySelector('#video')
                if (myVideo) {
                    myVideo.oncanplay = function () {
                        loading.value = false
                    }
                }
            })
        })

        return {
            filesError,
            changeUrl,
        }
    },
})
</script>
