<template>
	<!-- 必须是真正的 <div>（vue 文件根标签），AliPlayer 内部用 querySelector + innerHTML 操作 -->
	<div class="prism-player" :id="playerId" :style="playStyle"></div>
</template>

<script>
/**
 * AliPlayer H5 容器（仿 MLLive onerizelive-player.vue / SellioRizeLive wanl-player.vue）
 *
 * 重要：本文件必须是 .vue 而不是 .nvue，否则 H5 编译后根节点变成 <uni-view>，
 * AliPlayer 在自定义元素上的 innerHTML / DOM 操作会异常，画面出不来。
 */
export default {
	name: 'PrismHost',
	props: {
		source: { type: String, default: '' },
		height: { type: String, default: '320px' },
		width: { type: String, default: '100%' },
		videoWidth: { type: String, default: '100%' },
		videoHeight: { type: String, default: '320px' },
		preload: { type: Boolean, default: true },
		cover: { type: String, default: '' },
		isLive: { type: Boolean, default: false },
		autoplay: { type: Boolean, default: true },
		rePlay: { type: Boolean, default: false },
		useH5Prism: { type: Boolean, default: true },
		playsinline: { type: Boolean, default: true },
		showBuffer: { type: Boolean, default: true },
		skinLayout: {
			type: [Array, Boolean],
			default: function() { return [] }
		},
		controlBarVisibility: { type: String, default: 'hover' },
		format: { type: String, default: 'm3u8' },
		mediaType: { type: String, default: 'video' },
		language: { type: String, default: 'zh-cn' },
		useHlsPluginForSafari: { type: Boolean, default: false },
		enableStashBufferForFlv: { type: Boolean, default: false },
		stashInitialSizeForFlv: { type: Number, default: 10 },
		loadDataTimeout: { type: Number, default: 20 },
		waitingTimeout: { type: Number, default: 60 },
		diagnosisButtonVisible: { type: Boolean, default: false },
		vodRetry: { type: Number, default: 3 },
		liveRetry: { type: Number, default: 5 },
		playStyle: { type: String, default: '' },
		aliplayerSdkPath: {
			type: String,
			default: '//g.alicdn.com/de/prismplayer/2.9.3/aliplayer-h5-min.js'
		}
	},
	data() {
		return {
			playerId: 'aliplayer_' + Math.random().toString(36).substr(2),
			scriptTagStatus: 0,
			instance: null
		}
	},
	created() {
		if (typeof window === 'undefined') return
		if (window.Aliplayer !== undefined) {
			this.scriptTagStatus = 2
			this.initAliplayer()
		} else {
			this.insertScriptTag()
		}
	},
	mounted() {
		if (typeof window === 'undefined') return
		if (window.Aliplayer !== undefined) {
			this.scriptTagStatus = 2
			this.initAliplayer()
		} else {
			this.insertScriptTag()
		}
	},
	beforeDestroy() {
		if (this.instance) {
			try { this.instance.dispose() } catch (_) {}
			this.instance = null
		}
	},
	watch: {
		source(next, prev) {
			console.log('[PrismHost] source changed', { prev, next })
			if (!next) return
			// AliPlayer 的 loadByUrl 不支持跨格式切换（m3u8 ↔ flv），
			// 父组件已经通过 :key 强制重挂；这里兜底做完整 dispose+reinit。
			if (this.instance) {
				try { this.instance.dispose() } catch (_) {}
				this.instance = null
			}
			this._mutedDone = false
			this.initAliplayer()
		}
	},
	methods: {
		insertScriptTag() {
			const _this = this
			let tag = document.getElementById('aliplayerScriptTag')
			if (tag === null) {
				tag = document.createElement('script')
				tag.type = 'text/javascript'
				tag.src = this.aliplayerSdkPath
				tag.id = 'aliplayerScriptTag'
				document.getElementsByTagName('head')[0].appendChild(tag)
			}
			if (tag.loaded) {
				_this.scriptTagStatus++
				_this.initAliplayer()
			} else {
				tag.addEventListener('load', () => {
					_this.scriptTagStatus++
					tag.loaded = true
					_this.initAliplayer()
				})
			}
			_this.initAliplayer()
		},
		initAliplayer() {
			const _this = this
			if (_this.scriptTagStatus < 2) return
			if (_this.instance) return
			if (!window.Aliplayer) return
			console.log('[PrismHost] initAliplayer', { id: _this.playerId, source: _this.source })

			_this.$nextTick(() => {
				const mount = document.querySelector('#' + _this.playerId)
				if (!mount) {
					console.error('[PrismHost] mount node not found')
					return
				}
				mount.innerHTML = ''
				try {
					_this.instance = window.Aliplayer({
						id: _this.playerId,
						source: _this.source,
						width: _this.width,
						height: _this.height,
						videoWidth: _this.videoWidth,
						videoHeight: _this.videoHeight,
						preload: _this.preload,
						cover: _this.cover,
						isLive: _this.isLive,
						autoplay: _this.autoplay,
						rePlay: _this.rePlay,
						useH5Prism: _this.useH5Prism,
						playsinline: _this.playsinline,
						showBuffer: _this.showBuffer,
						skinLayout: _this.skinLayout,
						controlBarVisibility: _this.controlBarVisibility,
						format: _this.format,
						mediaType: _this.mediaType,
						language: _this.language,
						useHlsPluginForSafari: _this.useHlsPluginForSafari,
						enableStashBufferForFlv: _this.enableStashBufferForFlv,
						stashInitialSizeForFlv: _this.stashInitialSizeForFlv,
						loadDataTimeout: _this.loadDataTimeout,
						waitingTimeout: _this.waitingTimeout,
						diagnosisButtonVisible: _this.diagnosisButtonVisible,
						vodRetry: _this.vodRetry,
						liveRetry: _this.liveRetry
					})

					_this.instance.on('ready', () => {
						console.log('[PrismHost] AliPlayer ready')
						_this.$emit('ready', _this.instance)
						_this.applyMutedAutoplay()
					})
					_this.instance.on('play', () => {
						console.log('[PrismHost] AliPlayer play')
						_this.$emit('play', _this.instance)
					})
					_this.instance.on('pause', () => _this.$emit('pause', _this.instance))
					_this.instance.on('ended', () => _this.$emit('ended', _this.instance))
					_this.instance.on('liveStreamStop', () => {
						console.log('[PrismHost] AliPlayer liveStreamStop')
						_this.$emit('liveStreamStop', _this.instance)
					})
					_this.instance.on('m3u8Retry', () => _this.$emit('m3u8Retry', _this.instance))
					_this.instance.on('waiting', () => console.log('[PrismHost] AliPlayer waiting'))
					_this.instance.on('error', (e) => {
						console.error('[PrismHost] AliPlayer ERROR', e)
						_this.$emit('error', e)
					})

					setTimeout(() => _this.applyMutedAutoplay(), 600)
				} catch (err) {
					console.error('[PrismHost] AliPlayer init FAILED', err && (err.stack || err.message || err))
				}
			})
		},
		applyMutedAutoplay() {
			if (this._mutedDone) return
			const mount = document.querySelector('#' + this.playerId)
			const vid = mount && mount.querySelector && mount.querySelector('video')
			if (!vid) return
			this._mutedDone = true
			try {
				vid.muted = true
				vid.defaultMuted = true
				vid.setAttribute('muted', 'muted')
				vid.setAttribute('playsinline', 'true')
				vid.setAttribute('webkit-playsinline', 'true')
				vid.setAttribute('x5-playsinline', 'true')
				const p = vid.play()
				if (p && p.catch) p.catch((e) => console.warn('[PrismHost] play() rejected', e && e.message))
			} catch (e) {
				console.warn('[PrismHost] muted autoplay failed', e)
			}
			const unmute = () => {
				try { vid.muted = false } catch (_) {}
				document.removeEventListener('click', unmute)
				document.removeEventListener('touchend', unmute)
			}
			document.addEventListener('click', unmute, { once: true })
			document.addEventListener('touchend', unmute, { once: true })
		}
	}
}
</script>

<style>
@import url(//g.alicdn.com/de/prismplayer/2.9.3/skins/default/aliplayer-min.css);

.prism-player {
	width: 100%;
	height: 100%;
	overflow: hidden;
	background-color: #000;
}
.prism-player video {
	width: 100% !important;
	height: 100% !important;
	object-fit: contain;
}
</style>
