<template>
    <div class="view van-safe-area-bottom h-full">
        <van-sticky @change="changeSticky">
            <van-nav-bar
                :class="{ isFixed: isFixed }"
                :title="`第${curEpInfo.episodeNum}集`"
                left-text=""
                left-arrow
                @click-left="back"
            />
        </van-sticky>

        <!-- <van-image
            width="100%"
            height="calc(100vh - 95px - env(safe-area-inset-bottom) - env(safe-area-inset-top))"
            :src="poster"
            type="cover"
        /> -->

        <video ref="videoRef" controls muted class="video" :src="curEpInfo.playUrl" :poster="poster"></video>

        <div class="right-fixed">
            <div class="right-btn" @click="collect">
                <img
                    ref="collectImgRef"
                    class="w-[28px] h-[28px] animate__animated animate__faster"
                    :src="isCollected ? collectActiveImg : collectImg"
                    alt=""
                />
                <div>{{ isCollected ? '已追剧' : '追剧' }}</div>
            </div>
        </div>

        <div class="view-bottom flex justify-between z-20 items-center van-safe-area-bottom h-[49px] px-[18px]">
            <span class="text-base text-white">{{ seriesInfo.title }}-第{{ curEpInfo.episodeNum }}集</span>
            <van-button
                type="primary"
                class="btn"
                :icon="moreImg"
                icon-position="right"
                size="mini"
                round
                @click="showVideoHistory"
                >选集</van-button
            >
        </div>

        <video-history
            ref="videoHistoryRef"
            @playVideo="playVideo"
            :seriesInfo="seriesInfo"
            :curEpInfo="curEpInfo"
        ></video-history>
    </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, reactive, onUnmounted, onMounted } from 'vue'
import moreImg from '@/assets/icon_inter_white.png'
import VideoHistory from '../components/VideoHistory.vue'
import { http } from '@/plugins/http'
import { useRoute, onBeforeRouteLeave } from 'vue-router'
import '@/styles/animate.css'
import collectActiveImg from '@/assets/icon_dianliang.png'
import collectImg from '@/assets/icon_weidianliang.png'
import { showNotify } from 'vant'
import 'viplayer/dist/index.css'
import { videoPlay } from 'viplayer'
import resolveUrl from 'resolve-url'
import { nextTick } from 'vue'

const poster = ref('')

const router = useRouter()
function back() {
    router.back()
}

const isFixed = ref(false)
function changeSticky(fixed) {
    isFixed.value = fixed
}

const route = useRoute()
const seriesId = ref(0)
if (route.query.id) {
    seriesId.value = route.query.id
}

const seriesInfo = ref({})
const fileURL = import.meta.env.VITE_HTTP_FILE_URL
http.get('/api/series/' + seriesId.value).then(res => {
    seriesInfo.value = res
    // options.value.poster = re  solveUrl(fileURL, res.cover)
    poster.value = resolveUrl(fileURL, res.cover)
    console.log(poster.value)
})

http.get('/api/playHistories', {
    seriesId: seriesId.value
}).then(res => {
    if (res.data.length > 0) {
        getEpisodes(0, res.data[0].duration, res.data[0].episodeId)
    } else {
        getEpisodes()
    }
})

const curEpInfo = ref({})
async function getEpisodes(episodeNum = 1, duration = 0, episodeId = 0) {
    let data = {
        seriesId: seriesId.value,
        orderBy: 'episodeNum',
        order: 'episodeNum'
    }
    if (!episodeNum) {
        data.id = episodeId
    } else {
        data.episodeNum = episodeNum
    }
    const res = await http.get('/api/episodes', data)
    if (res.data.length > 0) {
        await play(res.data[0].id, duration)
    }
}

async function play(curEpId = 0, duration = 0) {
    await http.get('/api/episodes/' + curEpId).then(res => {
        curEpInfo.value = res
        nextTick(() => {
            videoRef.value.currentTime = duration
            videoRef.value.play()
        })
        // poster.value = resolveUrl(fileURL, res.cover)
    })
}

http.get('/api/collections/' + seriesId.value).then(res => {
    isCollected.value = true
})

const isCollected = ref(false)
const collectImgRef = ref(null)
function collect() {
    collectImgRef.value.className = collectImgRef.value.className + ' animate__pulse'
    setTimeout(() => {
        collectImgRef.value.className = collectImgRef.value.className.replace(/ animate__pulse/, '')
    }, 1000)

    if (isCollected.value) {
        http.delete('/api/collections/' + seriesId.value).then(res => {
            showNotify({ type: 'success', message: '取消成功' })
            isCollected.value = false
        })
    } else {
        http.post(
            '/api/collections',
            {
                seriesId: seriesId.value,
                curEpId: curEpInfo.value.id
            },
            {
                body: 'json'
            }
        ).then(res => {
            showNotify({ type: 'success', message: '追剧成功' })
            isCollected.value = true
        })
    }
}

const videoHistoryRef = ref(null)
function showVideoHistory() {
    videoHistoryRef.value.changeShow(true)
}

const videoRef = ref(null)
onBeforeRouteLeave((to, from, next) => {
    saveHistories(videoRef.value.currentTime).finally(() => {
        next()
    })
})

async function saveHistories(time) {
    await http.post(
        '/api/playHistories',
        {
            seriesId: seriesId.value,
            episodeId: curEpInfo.value.id,
            duration: time
        },
        { body: 'json' }
    )
}

onMounted(() => {
    nextTick(() => {
        videoRef.value.addEventListener('ended', () => {
            console.log('播放结束')
            getEpisodes(curEpInfo.value.episodeNum + 1).then(() => {
                saveHistories(videoRef.value.currentTime)
            })
        })
    })
})

function playVideo(num) {
    getEpisodes(num, 0)
}
</script>

<style lang="less" scoped>
.van-image {
    --van-image-placeholder-background: transparent;
}
.van-nav-bar {
    --van-nav-bar-background: transparent;
    --van-border-width: 0;
    --van-nav-bar-title-text-color: #fff;
    --van-nav-bar-icon-color: #fff;

    &.isFixed {
        --van-nav-bar-background: #11131e;
    }
}

.view-bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;

    .btn {
        --van-button-mini-font-size: 14px;
        --van-button-mini-padding: 0 12px;
        height: 26px;
    }
}

.right-fixed {
    position: fixed;
    right: 18px;
    bottom: calc(90px + env(safe-area-inset-bottom));
    .right-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 36px;

        div {
            font-size: 12px;
            font-weight: 500;
            color: #ffffff;
            line-height: 18px;
            text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.1);
        }
    }
}

.video {
    width: 100%;
    height: calc(100vh - 95px - env(safe-area-inset-bottom) - env(safe-area-inset-top));
}
</style>
