<script setup lang="ts">
import ImageEvo from '@/components/image-evo.vue'
import { unix } from 'dayjs'

const props = withDefaults(
  defineProps<{
    id: string | number
    url: string
    cover: string
  }>(),
  {},
)
const emits = defineEmits<{ play: [id: string | number]; ended: [id: string | number] }>()
const instance = getCurrentInstance()
const playing = ref(false)
const duration = ref(0)
const durationText = computed(() => unix(duration.value).format('mm:ss'))
const videoContext = ref<UniNamespace.VideoContext>()
const handlePlay = async () => {
  videoContext.value?.play()
  playing.value = true
  emits('play', props.id)
}
const handleLoadedMetaData = ({ detail }) => {
  duration.value = detail.duration
}
const handleEnded = () => {
  playing.value = false
  videoContext.value?.pause()
  emits('ended', props.id)
}
onMounted(async () => {
  videoContext.value = uni.createVideoContext(`video-${props.id}`, instance)
})
defineExpose({
  videoContext,
})
</script>
<template>
  <div class="w-full h-full relative">
    <div class="w-full h-full box-border pb-6">
      <video
        class="w-full h-full"
        :id="`video-${id}`"
        :src="url"
        :controls="'contimg'"
        :show-center-play-btn="false"
        :enable-progress-gesture="false"
        :loop="false"
        @ended="handleEnded"
        @loadedmetadata="handleLoadedMetaData"
      ></video>
    </div>
    <div v-if="!playing" class="absolute left-0 top-0 w-full h-full bg-black">
      <ImageEvo :src="cover"></ImageEvo>
    </div>
    <div
      v-if="!playing"
      class="w-[375px] h-[90px] bg-gradient-to-t from-black to-black/0 absolute left-0 bottom-0 w-full flex items-center"
    >
      <view class="mx-7">
        <wd-button
          plain
          custom-class="bg-transparent! text-white! w-20.5! min-w-20! h-8.25! border! border-solid! border-white!"
          @click="handlePlay()"
        >
          <div class="flex items-center">
            <wd-icon name="play" size="22px"></wd-icon>
            <div class="text-white text-[13px] font-['Gotham'] leading-[10.18px]">
              {{ durationText }}
            </div>
          </div>
        </wd-button>
      </view>
    </div>
  </div>
</template>
