<template>
	<view class="box">
		<template v-for="item in lists">
			<view 
			:ref="item.doomId"
			class="box-item"
			:style="{top:item.top+'px', opacity: barrageOpacity / 100 }">
				<view
				:class="[item.self ? 'self': '']">
					<text :style="{color: `#${item.fc.substr(2)}`, fontSize: barrageFontSize + 'rpx'}">{{item.content}}</text>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
	const animation = uni.requireNativePlugin('animation')

	export default {
		name: "barrage",
		data() {
			return {
				lists: [],
				idx: 0,
			};
		},
		props: {
			playerHeight: {
				type: Number
			},
			barrageOpacity: {
				type: Number,
				default: 100
			},
			barrageFontSize: {
				type: Number,
				default: 18
			},
			barrageSpeed: {
				type: Number,
				default: 10000
			},
			barrageArea: {
				type: Number,
				default: 100
			}
		},
		methods: {
			//添加弹幕测试doomData = {text: '6666666'}
			add(doomData) {
				this.addNvue(doomData)
			},
			addNvue(doomData) {
				let that = this
				this.idx++
				let doomId = this.idx
				// todo 弹幕区域调整
				// let top = Math.ceil(Math.random() * this.playerHeight)
				let top = this.dealTop(this.playerHeight, this.barrageArea);
				doomData.doomId = doomId
				doomData.top = top
				// console.log("接收到的弹幕数据", doomData)
				this.lists.push(doomData)
				this.$nextTick(function(e) {
					setTimeout(function(e) {
						that.move(doomData)
					}, 200)
				})
			},
			dealTop (height, area) {
				let column = Math.ceil(area / 25);
				let randomColumn = Math.floor(Math.random() * column);
				return Math.ceil(height * randomColumn / 4);
			},
			//nvue原生页面弹幕移动
			move(doomData) {
				let that = this
				let doomId = doomData.doomId
				let el = this.$refs[doomId][0]
				// console.log("弹幕节点信息", el)
				animation.transition(el, {
					styles: {
						transform: 'translateX(-100%)',
					},
					duration: this.barrageSpeed, //ms
					timingFunction: 'linear', //匀速移动
					delay: 0 //ms
				}, () => {
					//删除对应的弹幕数据,实测会导致渲染闪烁，如有需要自行优化
					// that.lists.splice(that.lists.indexOf(doomData), 1)
					// console.log("弹幕移动结束")
				})
			},
			clean() {
				this.lists = [];
			}
		}

	}
</script>

<style lang="stylus" scoped>
	.box
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		white-space: nowap;
		.box-item
			position: absolute;
			right: -88rpx;
			width: 750px;
			margin-top: 20rpx;
			flex-direction: row;
			transform: 'translateX(100%)';
			transformOrigin: 'left';
			timingFunction: 'linear';
			.self
				padding: 10rpx;
				border-radius: 24rpx;
				border: 1rpx solid #FFFFFF;
				background-color: rgba(102, 102, 102, 0.3);
</style>