Files
huangguo_h5/src/views/shortVideo/short-drama/DramaPlayPage.vue
T
2026-09-15 22:40:55 +07:00

717 lines
20 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="drama-play-page" :class="{ 'is-peek': isPeekOpen, 'is-pure': isPureMode }">
<button type="button" class="back-btn" @click="goBack">
<SvgIcon name="back_white" class="back-icon" />
</button>
<button
v-if="!isLoading && series && episodes.length > 0"
type="button"
class="speed-btn no-swipe"
@click="showSpeedPopup = true"
>
<img
class="speed-icon"
src="@/assets/images/png/short-drama/drama-speed-stopwatch.svg"
width="18"
height="18"
alt=""
/>
<span class="speed-text">{{ dramaPlaybackRateLabel(playbackRate) }}</span>
</button>
<template v-if="!isLoading && series && episodes.length > 0">
<div class="play-pane">
<div class="player-stage">
<div class="swiper drama-play-swiper" ref="swiperElRef">
<div class="swiper-wrapper">
<div class="swiper-slide" v-for="(ep, index) in episodes" :key="ep.id">
<DramaPlaySlide
v-if="Math.abs(index - currentIndex) <= nearbySlides"
:ref="(el) => setSlideRef(index, el)"
:series="series"
:episode="ep"
:is-active="currentIndex === index && isPageActive"
:is-pure-mode="isPureMode"
:compact="isPeekOpen"
:playback-rate="playbackRate"
:paywall="currentIndex === index ? paywall : null"
:balance-text="paywallBalanceText"
:player-warm-delay="currentIndex === index ? 0 : getShortVideoPlayerWarmDelay(Math.abs(index - currentIndex))"
@timeupdate="onTimeUpdate"
@ended="onVideoEnded"
@seek="onSeek"
@open-detail="openEpisodeSheet"
@toggle-pure="togglePureMode"
@unlock-gold="handleUnlockGold"
@open-vip="showDramaCardPayPopup = true"
/>
<div v-else class="slide-ph" aria-hidden="true" />
</div>
</div>
</div>
</div>
<div class="peek-dismiss" v-if="isPeekOpen" @click="closePeek" />
<div class="bottom-dock" v-show="!isPeekOpen">
<DramaPlayBottomBar
:total-episodes="series.totalEpisodes"
:variant="isPureMode ? 'pure' : 'full'"
:show-countdown="autoNextSec > 0"
:countdown-sec="autoNextSec"
@open-episode="openEpisodeSheet"
/>
</div>
</div>
<div class="sheet-pane" v-show="isEpisodeSheetOpen">
<DramaEpisodeSheet
:visible="isEpisodeSheetOpen"
:series="series"
:episodes="episodes"
:current-episode-number="currentEpisodeNumber"
@close="isEpisodeSheetOpen = false"
@select="onSelectEpisode"
/>
</div>
<CommentBox
ref="commentRef"
:is-open="isCommentPopup"
:obj-type="LikeType.DRAMA"
commentType="short"
:overlay-transparent="true"
@close="isCommentPopup = false"
@addComment="onAddComment"
/>
<PaymentStatusPopup
:show="showDramaCardPayPopup"
source-page="DRAMA_PAYWALL"
:vip-card-id="shortDramaCardId"
:video-id="dramaMediaId"
:media-id="dramaMediaId"
:content-id="dramaContentId"
@close="showDramaCardPayPopup = false"
@pay-success="onDramaCardPaySuccess"
/>
<CoinVideoPayPopup
:is-open="showCoinPayPopup"
:video-info="coinPayVideoInfo"
source-page="DRAMA_PAYWALL"
:media-id="dramaMediaId"
:content-id="dramaContentId"
defer-unlock
@close="showCoinPayPopup = false"
@buySuccess="onCoinPaySuccess"
/>
<DramaSpeedPopup
v-model="playbackRate"
:show="showSpeedPopup"
@close="showSpeedPopup = false"
/>
</template>
<div v-else-if="isLoading" class="boot-state">
<Loading />
</div>
<div class="empty" v-else>
<p>{{ hasError ? '加载失败,请稍后重试' : '暂无短剧内容' }}</p>
<button v-if="hasError" type="button" class="retry-btn" @click="fetchDetail">重新加载</button>
</div>
</div>
</template>
<script lang="ts">
export default {
name: 'shortDramaPlay',
};
</script>
<script setup lang="ts">
import {
computed,
defineAsyncComponent,
nextTick,
onActivated,
onBeforeUnmount,
onDeactivated,
onMounted,
provide,
ref,
watch,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';
import Swiper from 'swiper';
import 'swiper/swiper.min.css';
import { useUserStore } from '@/stores/user';
import { useConfigStore } from '@/stores/config';
import { LikeType } from '@/enums/app';
import { createShortVideoSwiperOptions } from '@/utils/shortVideoSwiper';
import { SHORT_VIDEO_NEARBY_SLIDES, getShortVideoPlayerWarmDelay } from '@/utils/shortVideoFeedAds';
import DramaPlaySlide from './components/DramaPlaySlide.vue';
import DramaPlayBottomBar from './components/DramaPlayBottomBar.vue';
import DramaEpisodeSheet from './components/DramaEpisodeSheet.vue';
import ShortDramaApi from '@/service/short-drama';
import { useDramaPlayDetail } from './hooks/useDramaPlayDetail';
import {
DEFAULT_DRAMA_PLAYBACK_RATE,
dramaPlaybackRateLabel,
type DramaPlaybackRate,
} from './utils/dramaPlaybackRate';
const PaymentStatusPopup = defineAsyncComponent(() => import('@/components/paymentStatusPopup/index.vue'));
const CoinVideoPayPopup = defineAsyncComponent(() => import('@/components/CoinVideoPayPopup/index.vue'));
const DramaSpeedPopup = defineAsyncComponent(() => import('./components/DramaSpeedPopup.vue'));
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const configStore = useConfigStore();
/** Ping 下发的默认短剧卡;未配置或列表不可见时由弹窗走长视频原有选卡优先级 */
const shortDramaCardId = computed(() => String(configStore.appConfig?.shortDramaCardId || ''));
const seriesId = String(route.query.id || '');
const fromQueryEpisode = route.query.episode != null && String(route.query.episode) !== '';
const initialEpisode = Number(route.query.episode || 1) || 1;
const {
isLoading,
hasError,
series,
episodes,
currentEpisode,
currentEpisodeNumber,
isPureMode,
isEpisodeSheetOpen,
isLocked,
autoNextSec,
paywall,
fetchDetail,
selectEpisode,
unlockCurrentEpisode,
refreshAfterCardPurchase,
togglePureMode,
startAutoNext,
clearAutoNext,
syncAutoNextByProgress,
getNextEpisode,
goAutoNextEpisode,
updatePlayProgress,
persistCurrentProgress,
} = useDramaPlayDetail(seriesId, initialEpisode, { fromQueryEpisode });
const goBack = async () => {
// 落连播进度到本地(历史/我的);返回刷剧不换集、不按此进度续播
await persistCurrentProgress();
if (window.history.length > 1) {
router.back();
return;
}
router.replace({ path: '/shortVideo', query: { type: '4' } });
};
const nearbySlides = SHORT_VIDEO_NEARBY_SLIDES;
/** keep-alive 缓存期间置 false,暂停播放器,避免跳明细等二级页时后台继续播 */
const isPageActive = ref(true);
const showDramaCardPayPopup = ref(false);
const showCoinPayPopup = ref(false);
const showSpeedPopup = ref(false);
const playbackRate = ref<DramaPlaybackRate>(DEFAULT_DRAMA_PLAYBACK_RATE);
const isCommentPopup = ref(false);
const commentRef = ref();
const swiperElRef = ref<HTMLElement>();
const slideRefs = ref<Record<number, { reloadPlayer?: () => void } | null>>({});
let dramaCommentEpisode: Types.ShortDrama.DramaEpisode | null = null;
let lastPersistAt = 0;
let swiperInstance: InstanceType<typeof Swiper> | null = null;
/** 程序化 slideTo,避免与 swipe 回调互相触发 */
let programmaticSlide = false;
const currentIndex = computed(() => {
const idx = episodes.value.findIndex((ep) => ep.episodeNumber === currentEpisodeNumber.value);
return idx >= 0 ? idx : 0;
});
/** 选集 / 评论弹窗:顶部全宽露播放(对齐抖音评论,不做等比缩小) */
const isPeekOpen = computed(() => isEpisodeSheetOpen.value || isCommentPopup.value);
const setSlideRef = (index: number, el: unknown) => {
slideRefs.value[index] = (el as { reloadPlayer?: () => void } | null) || null;
};
const balanceValue = computed(() => {
return ((userStore.walletInfo.amount || 0) * 100 + (userStore.walletInfo.income || 0) * 100) / 100;
});
const balanceText = computed(() => (balanceValue.value === 0 ? '0' : balanceValue.value.toFixed(1)));
const paywallBalanceText = computed(() => {
if (paywall.value && typeof paywall.value.coinBalance === 'number') {
return String(paywall.value.coinBalance);
}
return balanceText.value;
});
const coinPayVideoInfo = computed<Types.Video.VInfosItem>(() => {
const ep = currentEpisode.value;
const coins = paywall.value?.unlockCoin || ep?.unlockCoins || 0;
return {
id: ep?.id || seriesId,
title: series.value?.title || '',
coins,
originCoins: coins,
cover: ep?.coverUrl || series.value?.coverUrl || '',
} as Types.Video.VInfosItem;
});
/** 短剧整部 ID:优先分集上的 mediaId,否则路由剧 ID */
const dramaMediaId = computed(() => String(currentEpisode.value?.mediaId || seriesId || ''));
/** 当前播放子集 ID */
const dramaContentId = computed(() => String(currentEpisode.value?.id || ''));
const openCommentPopup = (
videoInfo: Types.Video.VInfosItem,
_objType = LikeType.DRAMA,
syncEpisode?: Types.ShortDrama.DramaEpisode,
) => {
dramaCommentEpisode = syncEpisode || null;
commentRef.value.state.videoInfo = videoInfo;
commentRef.value.moreParams.error = false;
commentRef.value.moreParams.loading = true;
nextTick(() => {
commentRef.value?.getCommentList();
isCommentPopup.value = true;
});
};
const onAddComment = () => {
if (series.value) {
series.value.commentCount = (series.value.commentCount || 0) + 1;
}
if (dramaCommentEpisode) {
dramaCommentEpisode.commentCount = (dramaCommentEpisode.commentCount || 0) + 1;
} else if (currentEpisode.value) {
currentEpisode.value.commentCount = (currentEpisode.value.commentCount || 0) + 1;
}
};
provide('openCommentPopup', openCommentPopup);
const openEpisodeSheet = () => {
isEpisodeSheetOpen.value = true;
};
const closePeek = () => {
isEpisodeSheetOpen.value = false;
isCommentPopup.value = false;
};
const slideToEpisode = async (episode: Types.ShortDrama.DramaEpisode, speed = 0) => {
const idx = episodes.value.findIndex((ep) => ep.id === episode.id);
if (idx < 0 || !swiperInstance) return;
if (swiperInstance.activeIndex === idx) return;
programmaticSlide = true;
swiperInstance.slideTo(idx, speed, false);
await nextTick();
programmaticSlide = false;
};
const onSelectEpisode = async (episode: Types.ShortDrama.DramaEpisode) => {
clearAutoNext();
await selectEpisode(episode);
await slideToEpisode(episode, 0);
};
const onTimeUpdate = (sec: number) => {
if (!currentEpisode.value) return;
currentEpisode.value.currentTimeSec = Math.max(0, Math.floor(sec || 0));
// 必须在 3s 落盘节流之前:片尾 5 秒倒计时依赖每次进度
syncAutoNextByProgress(sec);
const now = Date.now();
if (now - lastPersistAt < 3000) return;
lastPersistAt = now;
updatePlayProgress(currentEpisode.value.currentTimeSec);
};
const onSeek = (sec: number) => {
if (!currentEpisode.value) return;
currentEpisode.value.currentTimeSec = Math.max(0, Math.floor(sec || 0));
// 拖动可能进入/离开片尾窗口,统一走进度同步(离开则清倒计时)
syncAutoNextByProgress(sec);
updatePlayProgress(currentEpisode.value.currentTimeSec);
};
const onVideoEnded = () => {
updatePlayProgress(currentEpisode.value?.durationSec || currentEpisode.value?.currentTimeSec || 0);
if (isLocked.value) return;
const next = getNextEpisode();
if (!next) return;
// 片尾进度已在倒计时:直接切集;否则(无 duration)用 ended 后 5 秒兜底
if (autoNextSec.value > 0) {
goAutoNextEpisode(next);
return;
}
startAutoNext(5);
};
const onSwipeToIndex = async (index: number) => {
// 过渡结束回调滞后时,以当前 activeIndex 为准,避免把页面拉回上一集
if (swiperInstance && swiperInstance.activeIndex !== index) return;
const ep = episodes.value[index];
if (!ep) return;
if (ep.episodeNumber === currentEpisodeNumber.value) return;
clearAutoNext();
await selectEpisode(ep);
};
const destroySwiper = () => {
if (!swiperInstance) return;
try {
swiperInstance.destroy(true, true);
} catch (e) {
console.log(e);
}
swiperInstance = null;
};
const initSwiper = () => {
const el = swiperElRef.value;
if (!el || episodes.value.length === 0) return;
destroySwiper();
swiperInstance = new Swiper(
el,
createShortVideoSwiperOptions({
onSlideChangeTransitionEnd: (swiper) => {
if (programmaticSlide) return;
void onSwipeToIndex(swiper.activeIndex);
},
}),
);
const startIdx = currentIndex.value;
if (startIdx > 0) {
programmaticSlide = true;
swiperInstance.slideTo(startIdx, 0, false);
programmaticSlide = false;
}
};
const tryUnlockEpisode = async () => {
try {
await unlockCurrentEpisode();
showToast('解锁成功');
await nextTick();
slideRefs.value[currentIndex.value]?.reloadPlayer?.();
return true;
} catch (error) {
if (String(error).includes('PLAY_URL_PENDING')) {
showToast('解锁成功,资源加载中请稍后重试');
await nextTick();
slideRefs.value[currentIndex.value]?.reloadPlayer?.();
return true;
}
const code = ShortDramaApi.getBuyErrorCode(error);
if (code === '8005' && currentEpisode.value) {
// 同集权益刷新:保留当前进度,勿当成页内切集从头播
await selectEpisode(currentEpisode.value, { startFromZero: false });
return true;
}
if (code === '8000') {
showCoinPayPopup.value = true;
return false;
}
if (code === '4001') {
showToast('购买参数异常,请稍后重试');
}
return false;
}
};
const getUnlockCoinPrice = () => {
return Number(paywall.value?.unlockCoin || currentEpisode.value?.unlockCoins || 0);
};
/** 金币解锁:余额不足先打开充值弹窗,足够再下单(对齐长视频 VideoPermissionMask) */
const handleUnlockGold = async () => {
try {
await userStore.updateWallet();
} catch {
// 余额刷新失败时仍用本地缓存继续判断
}
const price = getUnlockCoinPrice();
if (price > 0 && balanceValue.value < price) {
showCoinPayPopup.value = true;
return;
}
await tryUnlockEpisode();
};
const onCoinPaySuccess = async () => {
showCoinPayPopup.value = false;
await userStore.updateWallet();
await tryUnlockEpisode();
};
const onDramaCardPaySuccess = async () => {
showDramaCardPayPopup.value = false;
try {
await userStore.updateUserInfo();
} catch {
// 用户信息刷新失败不阻断解锁态刷新
}
try {
const result = await refreshAfterCardPurchase();
await nextTick();
if (result === 'unlocked') {
slideRefs.value[currentIndex.value]?.reloadPlayer?.();
return;
}
if (result === 'play_url_pending') {
showToast('短剧权益已生效,资源加载中请稍后重试');
slideRefs.value[currentIndex.value]?.reloadPlayer?.();
return;
}
// 买的可能是普通会员卡,并不含本集短剧解锁权益
showToast('购买成功,该卡暂无法解锁本集短剧');
} catch {
showToast('购买成功,解锁状态刷新失败请重进本集');
}
};
watch(isLocked, (locked) => {
if (locked) clearAutoNext();
});
/** 选集/评论打开:锁定竖滑,并刷新尺寸 */
watch(isPeekOpen, async (open) => {
if (!swiperInstance) return;
swiperInstance.allowTouchMove = !open;
await nextTick();
try {
swiperInstance.update();
} catch (e) {
console.log(e);
}
});
/** 倒计时 / 选集切集后同步滑到对应页(仅纠偏,不做 300ms 动画,避免与手势抢滑) */
watch(currentEpisodeNumber, async (num, prev) => {
if (prev == null || num === prev || !swiperInstance) return;
const idx = episodes.value.findIndex((ep) => ep.episodeNumber === num);
if (idx < 0 || swiperInstance.activeIndex === idx) return;
programmaticSlide = true;
swiperInstance.slideTo(idx, 0, false);
await nextTick();
programmaticSlide = false;
});
watch(
() => episodes.value.length,
async (len) => {
if (len === 0) {
destroySwiper();
return;
}
await nextTick();
initSwiper();
},
);
onMounted(async () => {
await fetchDetail();
await nextTick();
initSwiper();
});
onActivated(() => {
isPageActive.value = true;
});
onDeactivated(() => {
isPageActive.value = false;
clearAutoNext();
void persistCurrentProgress();
});
onBeforeUnmount(() => {
destroySwiper();
});
</script>
<style scoped lang="scss">
.drama-play-page {
--drama-bottom-dock-h: calc(58px + env(safe-area-inset-bottom));
/* 与 CommentBox.is-peek-video 70dvh 对齐,避免评论盖住顶部视频 */
--drama-peek-h: 30dvh;
--drama-sheet-h: 70dvh;
position: relative;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
overflow: hidden;
background: #05000e;
color: #fff;
.player-stage {
position: absolute;
left: 0;
right: 0;
top: 0;
/* 正常播放:画面停在底栏上方,避免「视频偏下」被底栏裁切观感 */
bottom: var(--drama-bottom-dock-h);
z-index: 1;
}
.play-pane {
position: relative;
flex: 1 1 auto;
min-height: 0;
width: 100%;
overflow: hidden;
transition: flex-basis 0.28s ease, height 0.28s ease, max-height 0.28s ease;
}
&.is-peek {
.play-pane {
flex: 0 0 var(--drama-peek-h);
height: var(--drama-peek-h);
max-height: var(--drama-peek-h);
}
.player-stage {
bottom: 0;
}
}
.drama-play-swiper,
.swiper {
width: 100%;
height: 100%;
}
.swiper-slide {
width: 100%;
height: 100%;
}
.slide-ph {
width: 100%;
height: 100%;
background: #05000e;
}
.back-btn {
position: absolute;
left: 8px;
top: 8px;
z-index: 40;
width: 44px;
height: 44px;
padding: 0;
border: 0;
background: transparent;
display: flex;
align-items: center;
justify-content: center;
-webkit-tap-highlight-color: transparent;
.back-icon {
width: 24px;
height: 24px;
}
}
.speed-btn {
position: absolute;
right: 16px;
top: 12px;
z-index: 40;
height: 36px;
padding: 0;
border: 0;
background: transparent;
display: flex;
align-items: center;
gap: 4px;
color: #fff;
-webkit-tap-highlight-color: transparent;
.speed-icon {
display: block;
width: 18px;
height: 18px;
flex-shrink: 0;
}
.speed-text {
font-size: 12px;
font-weight: 500;
line-height: 18px;
white-space: nowrap;
}
}
.boot-state {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
}
.peek-dismiss {
position: absolute;
inset: 0;
z-index: 35;
}
.bottom-dock {
position: absolute;
left: 0;
right: 0;
bottom: 0;
/* 高于 slide 内叠层,清屏时仍可点选集 */
z-index: 60;
box-sizing: border-box;
min-height: var(--drama-bottom-dock-h);
padding: 6px 16px calc(6px + env(safe-area-inset-bottom));
background: #0f0f0f;
display: flex;
align-items: center;
}
.sheet-pane {
flex: 0 0 var(--drama-sheet-h);
height: var(--drama-sheet-h);
max-height: var(--drama-sheet-h);
width: 100%;
overflow: hidden;
z-index: 50;
background: #0f0f0f;
}
.empty {
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 16px;
color: rgba(255, 255, 255, 0.55);
font-size: 14px;
padding: 0 24px;
.retry-btn {
padding: 8px 20px;
border: 0;
border-radius: 6px;
background: #f68804;
color: #fff;
font-size: 14px;
}
}
}
</style>