<template>
	<view class="player">
		<div :id="videoId"></div>
		<view class="empty">{{tips}}</view>
	</view>
</template>

<script>
/* https://www.npmjs.com/package/flvplayer */
import {getImages} from '@/plugins/images'
import { uniqueId } from 'lodash'

let multipleDecoderJs = getImages('/assetsMobile/script/flvPlayer/flvplayer-decoder-multiple.js')
let baselineDecoderJs = getImages('/assetsMobile/script/flvPlayer/flvplayer-decoder-baseline.js')

export default {
	props: {
		videoUrl: {
			type: String,
			default: ''
		},
		control: {
			type: Boolean,
			default: true,
		}
	},
	watch: {
		videoUrl: {
			immediate: true,
			deep: true,
			handler(newVal,oldVal) {
				this.tips = '加载中'
				// console.log(newVal,'vv')
				if (!this.isNull(newVal)) {
					if(newVal.includes('failed')) {
						this.tips = '设备命令下发失败'
						return
					}
					this.playerDestroy();
					this.$nextTick(() => {
						this.createPlayer(`#${this.videoId}`, newVal);
					})	
				}
				
			}
		}
	},
	components: {
	
	},
	created() {
		
	},
	data() {
		return {
			flv: null,
			videoId:  uniqueId('flv_video_'),
			tips: '加载中',
		}
	},
	
	methods: {
		//创建播放器
		createPlayer(el,url) {
			
			if (!this.flv) {
				this.flv = new window.FlvPlayer({
					container: el,
					url,
					decoder: multipleDecoderJs,
					cache: false,
					muted: true,
					videoChunk: 128 * 128,
					live: true,
					autoPlay: true,
					hasAudio: false,
					debug: true,
					control: this.control
				})
			}
		},
		play() {
			if(this.flv) this.flv.play()
		},
		pause() {
			if(this.flv) this.flv.pause()
		},
		//销毁播放方法
		playerDestroy() {
			if (this.flv) {
				this.flv.pause && this.flv.pause();
				this.flv.destroy && this.flv.destroy();
				this.flv = null;
			}
		},
	},
	beforeDestroy() {
		this.playerDestroy();
	},
}
</script>

<style lang="scss" scoped>
.player {
	width: 100%;
	height: 100%;
	overflow: hidden;
	position: relative;
	.empty {
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 24rpx;
		color: #fff;
		width: 100%;
		height: 100%;
	}
}
</style>
