<template>
    <ion-page>
        <ion-header>
            <ion-toolbar>
                <ion-buttons slot="start">
                    <ion-back-button text="" default-href="#" @click="$router.back()"></ion-back-button>
                </ion-buttons>
                <ion-title v-if="curEpInfo && curEpInfo.episodeNum">{{
                    $t('video.index', { num: curEpInfo.episodeNum })
                }}</ion-title>
            </ion-toolbar>
        </ion-header>
        <ion-content class="view van-safe-area-bottom">
            <!-- <div class="video-content">
                <video
                    ref="videoRef"
                    :controls="false"
                    muted
                    playsinline="true"
                    webkit-playsinline="true"
                    class="video"
                    :src="curEpInfo.playUrl"
                    :poster="poster"
                ></video>
                <div class="video-box"></div>
            </div> -->
            <video-player
                ref="videoRef"
                :playUrl="curEpInfo.playUrl"
                :poster="poster"
                :isPre="isPre"
                :isNext="isNext"
                @videoEnded="videoEnded"
                @changeSide="changeSide"
            ></video-player>

            <div class="right-fixed">
                <div class="right-btn share" @click="share">
                    <img class="w-[38px] h-[26px]" src="@/assets/icon_fenxiang.png" alt="" />
                    <div>{{ $t('work') }}</div>
                </div>
                <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 ? $t('collected') : $t('collect') }}</div>
                </div>
            </div>

            <div class="view-bottom flex justify-between z-20 items-center van-safe-area-bottom px-[18px]">
                <span class="text-base text-white"
                    >{{ seriesInfo.title }}-{{ $t('video.number', { num: curEpInfo.episodeNum }) }}</span
                >
                <van-button
                    type="primary"
                    class="btn"
                    :icon="moreImg"
                    icon-position="right"
                    size="mini"
                    round
                    @click="showVideoHistory"
                    >{{ $t('video.choose') }}</van-button
                >
            </div>

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

            <video-buy
                ref="videoBuyRef"
                @videopause="videopause"
                @playVideo="playVideo"
                :seriesInfo="seriesInfo"
                :buyEpInfo="buyEpInfo"
            ></video-buy>

            <poster-page
                ref="posterRef"
                pageType="video"
                :title="seriesInfo.title"
                :poster="poster"
                :episode-num="curEpInfo.episodeNum"
            ></poster-page>
        </ion-content>
    </ion-page>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { ref, computed, reactive, onUnmounted, onMounted } from 'vue'
import moreImg from '@/assets/icon_inter_white.png'
import VideoHistory from '../components/VideoHistory.vue'
import VideoBuy from '../components/VideoBuy.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 resolveUrl from 'resolve-url'
import { nextTick } from 'vue'
import toast from '@/utils/toast'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { useI18n } from 'vue-i18n'
import PosterPage from '@/components/PosterPage.vue'

const { t } = useI18n()
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)
    }
}

const buyEpInfo = ref({})
const videoBuyRef = ref(null)
async function play(curEpId = 0, duration = 0) {
    toast.loading(t('loading'))
    await http
        .get('/api/episodes/' + curEpId)
        .then(res => {
            toast.dismiss()
            if (Number(res.price) > 0 && !res.playUrl) {
                buyEpInfo.value = res
                videoBuyRef.value.init()
            } else {
                curEpInfo.value = res
                nextTick(() => {
                    videoRef.value.setCurrent(duration)
                    videoRef.value.play()
                    videoRef.value.changeMuted()
                })
            }

            // poster.value = resolveUrl(fileURL, res.cover)
        })
        .catch(e => {
            toast.dismiss()
        })
}

function videopause(pause = true) {
    if (pause) {
        videoRef.value.pause()
    } else {
        videoRef.value.play()
    }
}

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

const isCollected = ref(false)
const collectImgRef = ref(null)
function collect() {
    toast.loading(t('loading'))
    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 => {
            toast.success(t('cancelSuc'))
            isCollected.value = false
        })
    } else {
        http.post(
            '/api/collections',
            {
                seriesId: seriesId.value,
                curEpId: curEpInfo.value.id
            },
            {
                body: 'json'
            }
        ).then(res => {
            toast.success(t('collectSuc'))
            isCollected.value = true
        })
    }
}

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

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

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

function videoEnded() {
    if (curEpInfo.value.episodeNum !== seriesInfo.value.playCount) {
        getEpisodes(curEpInfo.value.episodeNum + 1).then(() => {
            saveHistories(videoRef.value.getCurrent())
        })
    }
}

function playVideo(num) {
    getEpisodes(num, 0)
}

function changeSide(side) {
    if (side === 'next') {
        videoEnded()
    } else if (curEpInfo.value.episodeNum > 1) {
        getEpisodes(curEpInfo.value.episodeNum - 1).then(() => {
            saveHistories(videoRef.value.getCurrent())
        })
    }
}

const isPre = computed(() => {
    return curEpInfo.value.episodeNum > 1
})
const isNext = computed(() => {
    return curEpInfo.value.episodeNum !== seriesInfo.value.playCount
})

const posterRef = ref(null)
function share() {
    posterRef.value.onOpenInviteModal()
}
</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;
    height: calc(env(safe-area-inset-bottom) + 49px);
    height: calc(constant(safe-area-inset-bottom) + 49px);
    box-sizing: border-box;

    .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));
    bottom: calc(90px + constant(safe-area-inset-bottom));
    z-index: 30;
    .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);
        }
    }
}

.share {
    margin-bottom: 20px;
    div {
        font-size: 12px;
        font-weight: 600;
        color: #ffd33f;
        line-height: 18px;
        text-shadow: 0px 1px 0px rgba(0, 0, 0, 0.1);
        background: linear-gradient(180deg, #fffffd 0%, #ffa400 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
    }
}
</style>
