<template>
	<view class="ext-wrap" :style="frameStyle">
		<!--
			APP-PLUS 直播渲染器：基于 wrs-uts-videoplayer 的 IjkPlayer 内核。
			绕过 HBuilderX 5.08+ <video> 切到 ExoPlayer/AVPlayer 不支持 RTMP 的问题。

			只在 nvue/uvue 中可用（标签由 UTS 原生组件提供）。
		-->
		<wrs-uts-videoplayer
			v-if="hasPlugin && hasSource"
			ref="wrsVideo"
			class="ext-canvas"
			:style="frameStyle"
			:params="paramsStr"
			@onEvent="onWrsEvent"
		/>
		<view v-else-if="!hasPlugin" class="ext-notice">
			<text class="ext-notice-text">{{ noticeText }}</text>
		</view>
		<view v-if="busy" class="ext-loading">
			<text class="ext-loading-text">{{ busyText }}</text>
		</view>
		<view v-if="errorText" class="ext-error">
			<text class="ext-error-text">{{ errorText }}</text>
		</view>
	</view>
</template>

<script>
import { hasWrsVideoPlayer } from '@/features/livestream/external-player-detect'

const TAG = '[STREAM-PLAYER:EXT]'

export default {
	name: 'StreamPlayerExternal',
	props: {
		source: { type: String, default: '' },
		frameWidth: { type: Number, default: 0 },
		frameHeight: { type: Number, default: 0 },
		phase: { type: String, default: 'onair' },
		muted: { type: Boolean, default: false },
		autoplay: { type: Boolean, default: true }
	},
	data() {
		return {
			busy: true,
			busyText: '正在连接直播流…',
			errorText: ''
		}
	},
	computed: {
		hasPlugin() {
			return hasWrsVideoPlayer
		},
		hasSource() {
			return !!this.source
		},
		frameStyle() {
			const w = this.frameWidth ? `${this.frameWidth}px` : '100%'
			const h = this.frameHeight ? `${this.frameHeight}px` : '100%'
			return { width: w, height: h }
		},
		// 选择 IjkPlayer 内核（这是 RTMP 救急的关键）
		playerCore() {
			return 'IjkPlayer'
		},
		paramsStr() {
			const businessArray = [
				{
					business: 'setUrl',
					params: {
						url: this.source,
						playerCore: this.playerCore,
						autoPlay: !!this.autoplay,
						scaleMode: 'default'
					}
				}
			]
			if (this.muted) {
				businessArray.push({ business: 'setVolume', params: { volume: 0 } })
			}
			return JSON.stringify({ businessArray })
		},
		noticeText() {
			return [
				'未检测到 wrs-uts-videoplayer 插件。',
				'请在插件市场安装（id=16312），并打自定义调试基座。',
				'集成步骤详见 features/livestream/RESCUE.md。'
			].join('\n')
		}
	},
	watch: {
		source(next, prev) {
			console.log(TAG, 'source changed', { prev, next })
			if (next && next !== prev) {
				this.busy = true
				this.busyText = '正在切换流地址…'
				this.errorText = ''
			}
		}
	},
	mounted() {
		console.log(TAG, 'mounted', {
			hasPlugin: this.hasPlugin,
			source: this.source,
			playerCore: this.playerCore
		})
		if (!this.hasPlugin) {
			this.busy = false
			this.errorText = '未安装 wrs-uts-videoplayer 插件'
		}
	},
	beforeDestroy() {
		console.log(TAG, 'beforeDestroy')
	},
	methods: {
		onWrsEvent(e) {
			const detail = (e && e.detail) || {}
			const opt = detail.opt || ''
			console.log(TAG, 'wrs event', opt, detail)

			switch (opt) {
				case 'onReadyToPlay':
					this.busy = false
					this.errorText = ''
					this.$emit('play', e)
					break
				case 'onProgress':
					// 播放进度心跳；表示流仍在播
					this.busy = false
					break
				case 'onError':
					this.errorText = '直播流错误（请检查推流是否在线）'
					this.busy = false
					this.$emit('error', e)
					break
				case 'onComplete':
					this.errorText = '直播流已结束'
					this.busy = false
					this.$emit('ended', e)
					break
				default:
					break
			}
		}
	}
}
</script>

<style>
.ext-wrap {
	position: absolute;
	top: 0;
	left: 0;
	overflow: hidden;
	background-color: #000000;
}
.ext-canvas {
	position: absolute;
	top: 0;
	left: 0;
}
.ext-notice {
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	justify-content: center;
	align-items: center;
	padding: 0 40rpx;
}
.ext-notice-text {
	color: #ffd66b;
	font-size: 24rpx;
	text-align: center;
	line-height: 40rpx;
}
.ext-loading {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	justify-content: center;
	align-items: center;
}
.ext-loading-text {
	color: #ffffff;
	font-size: 28rpx;
}
.ext-error {
	position: absolute;
	left: 0;
	right: 0;
	bottom: 80rpx;
	padding: 0 40rpx;
	justify-content: center;
	align-items: center;
}
.ext-error-text {
	color: #ffd66b;
	font-size: 26rpx;
	text-align: center;
}
</style>
