<template>
	<view class="live column flex-1">
		<view class="videolist" v-if="upDown">
			<view class="vedio">
				<!-- <view class="p20 textscll">
					<u-notice-bar :icon="icon" :text="text1" mode="closable" bgColor='rgba(0,0,0,0.7)' color='#fff'
						style="border-radius: 10rpx;"></u-notice-bar>
				</view> -->
				<video id="myVideo" class="videotop" :src="path+livedata.videoUrl" :autoplay="autoplay"
					:controls='false' :poster='livedata.liveImgUrl' vslide-gesture-in-fullscreen='true'
					:show-center-play-btn="false"></video>
			</view>
			<view class="popup-video" v-if="!autoplay">
				<view class="fs36 bold" v-if="livedata.status==1">——直播还未开始——</view>
				<view class="fs36 bold" v-if="livedata.status==3">——直播已经结束——</view>
				<view class="fs28 mtb20">了解更多，点击下方联系老师</view>
				<view class="more" @click="showadd=!showadd">联系老师</view>
			</view>
		</view>
		<view class="justify-between align-center bgf" style="border-bottom: #dedede solid 2rpx;">
			<u-tabs :list="list1" @click="tabClick" inactiveStyle="color:#888"
				itemStyle='width:120rpx;height: 80rpx;'></u-tabs>
			<view class="justify-around flex-1 align-center">
				<view class="reflash" @click="getliving()">刷新</view>
				<image src='../../static/images/top.png' class="wh48" v-show="upDown" @click="upDown=!upDown"></image>
				<image src='../../static/images/up-down.png' class="wh48" v-show="!upDown" @click="upDown=!upDown">
				</image>
			</view>
		</view>
		<view class="talkbox column flex-1 hidden" style="height: 100%;" v-if="acttab==0">
			<!-- <u-notice-bar :icon="icon2" :text="text2" mode="closable" bgColor='rgba(254,253,235)' color='#FF5C03'
				style=" height: 30rpx;line-height: 40rpx;"></u-notice-bar> -->
			<scroll-view enable-flex scroll-y="true" class="talk p20 scrolly flex-1 column"
				style="width: calc(100% - 40rpx);height: calc(100% - 40rpx);" :scroll-into-view="scrollIntoView">
				<view class="list justify-start" v-for="(item,index) in talklist" :key="item.index"
					:id="`list_${index}`" v-show="item.cmd=='sendMsg'">
					<u-avatar :src="item.avatar" size='30'></u-avatar>
					<view class=" ml16">
						<view class="fs24">
							<text style="color: #3fc69b;
							transform: scale(0.8);display: inline-block; " 
							 v-if="item.userId==userinfo.userId&&item.cmd=='sendMsg'">[ 我 ]</text>
							 <text style="color: #c84e1e;
							 transform: scale(0.8);display: inline-block;" v-if="item.userType==1">
							 [ 管理员 ]</text>
							<text>{{item.nickName}}</text>
						</view>
						<view class="talktext bgf p20 mt12">
							<view class='fs24'>{{item.msg}}</view>
						</view>
					</view>
				</view>
				<view v-if="showWelcomeMessage" class="welcome-message">
					<view class="list justify-start" v-for="(item,index) in talklist" :key="item.index"
						:id="`list_${index}`" v-show="item.cmd=='entry'||item.cmd=='out'">
						<view class=" ml16">
							<view class="fs24">
								 <text style="color: #c84e1e;
								 transform: scale(0.8);display: inline-block;" v-if="item.userType==1">
								 [ 管理员 ]</text>
							</view>
							<view class="talktext bgf p20 mt12 justify-start">
								<text style="color: #9e5584;" class="fs24  ">{{item.nickName}} </text>
								<view class='fs24 flex-1'>{{item.msg}}直播间</view>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="pb90 mb20"></view>
			<view class="bot_talk bgf">
				<u-input :placeholder="placeholderText" border="none"
					customStyle='background:#f1f7f7;padding:12rpx;padding-left:40rpx' v-model="value" shape='circle'
					></u-input>
					<!-- :disabled='talkdisabled'></u-input> -->
				<view class="sent ml20" @click="sendMsg">发送</view>
			</view>
		</view>
		<!-- <view class="answerbox" v-if="acttab==1">
			问答
		</view> -->
		<view class="informationbox" v-if="acttab==1">
			<view class="p20 bgf m20 radius20">
				<view v-html="livedata.liveDesc"></view>
				<view v-show="!livedata.liveDesc">暂无资料</view>
			</view>
		</view>
		<view class="invite-member" @click="addwechat">
			<image src="../../static/images/wechat.png" class="wh80 weimg"></image>
			<view class="addwe">加微信</view>
		</view>
		<view class="">
			<u-popup :show="showadd" @close="close" @open="open" round='20rpx' bgColor='#fffee1'>
				<view class="addchat p20">
					<view class="u-flex-row-reverse u-flex">
						<u-icon name="close" size="18" @click="showadd=!showadd"></u-icon>
					</view>
					<view class="column align-center">
						<view class="fs36" style="color: #ff5c03;">扫码添加助教老师</view>
						<view class="fs28 color6">扫码添加助教老师</view>
						<view class="p10 mt40" style="border: #ff5c03 solid 2rpx;">
							<image :src="codeimg" class="wh180" @touchstart="longPress" @touchend="cancelLongPress">
							</image>
						</view>
						<view class="color6 mt20">长按识别二维码</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>
<script>
	import {
		getlive,
		gettextlist
	} from '@/api/home'
	
	// var wsUrl = "ws://live.ylrzcloud.com/socket/app/webSocket";
	var wsUrl = "ws://192.168.10.170:7114/app/webSocket";
	var pingpangTimes = null;
	var initTimes = null;
	var isSocketOpen = false;
	var socket = null;

	export default {
		data() {
			return {
				icon: '公告:',
				icon2: '广播:',
				text1: '组件功能丰富多端兼容让您快速集成开箱即用',
				text2: '丰富多端兼容让您快速集成开箱即用',
				srcAvatar: '',
				acttab: 0,
				value: '',
				talkdisabled: false, //是否禁用
				placeholderText: "请输入内容",
				showadd: false,
				autoplay: true, //自动播放
				userinfo: '', //用户信息
				path: 'http://192.168.10.170/dev-api',
				livedata: {},
				bufferRate: 0, // 缓冲时间
				playDuration: 0, //视频播放时间
				videoContext: '',
				thistime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
				codeimg: '',
				userid: '4',
				liveId: '5',
				upDown: true, //是否视频显示隐藏
				isLongPress: false, // 是否长按
				timeout: null, // 计时器
				list1: [{
						name: '讨论'
					},
					// {
					// 	name: '问答'
					// },
					{
						name: '资料'
					},
				],
				talklist: [],
				scrollIntoView: '',
				showWelcomeMessage: false,
				messageContent: ""
			}
		},
		mounted() {
			this.initSocket()
			var that = this;
			uni.$on('initSocket', () => {
				that.initSocket()
			})
			uni.$on('sendMsg', (item) => {
				that.sendMsg(item)
			})
			uni.$on('closeWebSocket', () => {
				that.closeWebSocket()
			})
			this.getEWechatSdk();

			this.userinfo = JSON.parse(uni.getStorageSync("userInfo"))
			this.getliving()
			this.gettalklist()
		},
		onReady: function(res) {
			this.videoContext = uni.createVideoContext('myVideo')
			// console.log(this.videoContext)
		},
		onLoad() {

		},
		methods: {
			gettalklist() {
				const param = {
					id: this.liveId
				}
				gettextlist(param).then(res => {
					if (res.code == 200) {
						this.talklist = res.data
						// console.log(res.data);
						this.$nextTick(() => {
							this.scrollIntoView = `list_${this.talklist.length-1}`
						})
					}
				})
			},
			longPress() {
				this.timeout = setTimeout(() => {
					this.isLongPress = true;
					// 执行保存图片的操作
					uni.saveImageToPhotosAlbum({
						filePath: this.livedata.qwQrCode, // 图片的本地路径或网络路径
						success: () => {
							uni.showToast({
								title: '保存成功'
							});
						},
						fail: () => {
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					});
				}, 500); // 设置长按的阈值时间，这里是500毫秒
			},
			cancelLongPress() {
				clearTimeout(this.timeout);
				this.isLongPress = false;
			},
			getliving() {
				this.gettalklist()
				const param = {
					id: this.liveId
				}
				getlive(param).then(res => {
					if (res.code == 200) {
						this.livedata = res.data
						this.codeimg = res.data.qwQrCode
						if (this.livedata.status == 2) {
							this.autoplay = true
							this.videoContext.seek(this.livedata.nowDuration)
							// console.log(this.autoplay)
						} else {
							this.autoplay = false
							this.placeholderText = "直播开始才能发言讨论"
							this.talkdisabled = true
						}
						// console.log(this.autoplay)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			addwechat() {
				this.showadd = !this.showadd
			},
			open() {

			},
			close() {
				this.showadd = !this.showadd
			},
			tabClick(e) {
				this.acttab = e.index
				if(e.index==0){
					this.$nextTick(() => {
						this.gettalklist()
					})
				}
			},
			getEWechatSdk() {
				let eWechatSdk = ''
				if (/(Android)/i.test(navigator.userAgent)) {
					eWechatSdk = 'jWeixin'
				} else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
					eWechatSdk = 'wx'
				} else {
					eWechatSdk = 'jWeixin'
				}
				uni.setStorageSync("wxSdk", eWechatSdk)
			},
			closeWebSocket() {
				if (socket != null) {
					uni.closeSocket();
				}
				clearInterval(pingpangTimes)
			},
			reConnect() {
				var that = this;
				try {
					uni.closeSocket();
				} catch (e) {

				}
				setTimeout(function() {
					that.initSocket();
				}, 10000);

			},
			initSocket() {
				var that = this;
				// console.log("initSocket")
				//创建一个socket连接
				socket = uni.connectSocket({
					// url: wsUrl+"?userId=40486&liveId=2",
					// url: wsUrl + "?userId=" + this.userid + "&liveId=" + 
					// this.liveId+"&AppToken="+'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI0IiwiaWF0IjoxNzQwNzIxMDQ1LCJleHAiOjE3NDEzMjU4NDV9.PgS83JTMSJgVFD6vGAhUsEPbS6Az4yMyX8wVug61TZNTB3092CtvANo-AB9ZG4NdSBLgLrf4litM3vvTk-FK0g',
					
					url: wsUrl + "?userId=666"+ "&liveId=777" +"&AppToken="+'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI2NjYiLCJpYXQiOjE3NTE4NzQ0NzEsImV4cCI6MTc4MzQxMDQ3MX0.3uxTTb0qXygmaY9ItovMclxJCNhNEi6kFEqmfLGg4lP2PYzCPODsVjW4PjXNu6EYsl5eYyESltHWcwBnaNkilQ&signature=ff21bfb41ddd5f2e31d6f5bf32ec565aab9c518614d139fa26727468ce701237&userType=0&timestamp=666',
					multiple: true,
					success: res => {
						//先确保清除了之前的心跳定时器
						clearInterval(pingpangTimes)
						uni.onSocketMessage((res) => {
							const redata = JSON.parse(res.data);
							// console.log(redata)
							// console.log(111,this.talklist)
							this.talklist.push(redata.data)
							this.$nextTick(() => {
								this.scrollIntoView = `list_${this.talklist.length-1}`
							})
							// console.log(222,this.talklist)
							// console.info(redata)
							if (redata.cmd == 'deleteId') {
								uni.$emit('deleteId');
							} else if (redata.cmd == 'init') {
								uni.$emit('init', redata.data);
							} else if (redata.cmd == 'reload') {
								uni.$emit('reload');
							} else if (redata.cmd == 'sendStatus') {
								uni.$emit('sendStatus', redata.data);
							}else if (redata.data.cmd == 'entry') {
								this.showWelcomeMessage=true
								uni.$emit('entry', redata.data);
								console.log(redata.data)
							}

						})
					},
					error: res => {
						uni.$emit('websocket', 0);
						// console.log(res)
					},
				})
				//监听socket打开
				uni.onSocketOpen(() => {
					isSocketOpen = true
					console.log('WebSocket连接已打开！!');
					// uni.$emit('websocket',1);
					uni.showToast({
						title: "插件已打开",
						icon: 'none',
					});
				})
				//监听socket关闭
				uni.onSocketClose(() => {
					isSocketOpen = false
					clearInterval(pingpangTimes)
					console.log('WebSocket连接已关闭！');
					// uni.$emit('websocket',0);
					uni.showToast({
						title: "插件离线",
						icon: 'none',
					});
					//重连
					that.reConnect()
				})
				//监听socket错误
				uni.onSocketError(() => {
					isSocketOpen = false
					clearInterval(pingpangTimes)
					console.log('WebSocket连接打开失败');
					// uni.$emit('websocket',0);
					uni.showToast({
						title: "插件离线",
						icon: 'none',
					});
					uni.showModal({
						content: '聊天连接失败是否重新尝试连接',
						success() {
							that.reConnect()
						}
					})
				})
			},
			sendMsg() {
				if (isSocketOpen) {
					const data = {
						liveId: this.livedata.liveId,
						userId: this.userinfo.userId,
						userType: 0,
						cmd: "sendMsg",
						msg: this.value,
						nickName: this.userinfo.nickName,
						avatar: this.userinfo.avatar
					}
					if(this.value==""){
						uni.showToast({
							title: "不能发送空消息",
							icon: 'none',
							
						});
					}else{
						socket.send({
							data: JSON.stringify(data),
							success: () => {
								// this.gettalklist()
								console.log("发送成功")
								this.value = ''
							},
							fail: () => {
								console.log("发送失败")
							}
						})
					}
				}
			},
			
		}
	}
</script>
<style lang="scss" scoped>
	.welcome-message {
	  position: fixed;
	  width: 100%;
	  bottom: 120rpx;
	  left: 50%;
	  transform: translateX(-50%);
	  color: #666;
	  padding: 10px 20px;
	  border-radius: 20px;
	  animation: fadeOut 1s ease 1s forwards; /* 1秒后开始淡出 */
	  z-index: 1000;
	}
	
	@keyframes fadeOut {
	  from { opacity: 1; }
	  to { opacity: 0; }
	}
	.live {
		height: 100%;
		overflow: hidden;
	}

	.list {
		width: 80%;
		margin-bottom: 20rpx;
		animation: xxxawdawd .2s;
	}

	@keyframes xxxawdawd {
		from {
			margin-top: 0rpx;
			opacity: 0;
		}

		to {
			margin-top: 20rpx;
			opacity: 1;
		}
	}

	.vedio {
		height: 500rpx;
		width: 100%;
		background-color: rgba(0, 0, 0, 0.6);
		position: relative;
	}

	.videotop {
		width: 100%;
		height: 100%;
	}

	.popup-video {
		position: absolute;
		top: 0;
		height: 500rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		width: 100%;
		color: #fff;
		background-color: rgba(0, 0, 0, 0.6);

		.more {
			background-color: #3280fe;
			border-radius: 80rpx;
			width: 280rpx;
			text-align: center;
			height: 60rpx;
			line-height: 60rpx;
		}
	}

	.textscll {
		position: absolute;
		top: 0;
		z-index: 999;
	}

	.reflash {
		border: 2rpx solid #888;
		border-radius: 80rpx;
		padding: 4rpx 16rpx;
		color: #888;
	}

	.talktext {
		border-radius: 8rpx;

		view {
			width: 100%;
		}
	}

	.bot_talk {
		width: calc(100% - 40rpx);
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: fixed;
		bottom: 0;
		padding: 20rpx;

		.sent {
			width: 120rpx;
			text-align: center;
			height: 60rpx;
			line-height: 60rpx;
			background-color: #3280fe;
			color: #fff;
			border-radius: 40rpx;
			font-size: 24rpx;
		}
	}

	.invite-member {
		height: 55px;
		width: 50px;
		position: fixed;
		bottom: 80px;
		right: 10px;
		cursor: pointer;

		.weimg {
			position: relative;
		}

		.addwe {
			position: absolute;
			left: -7%;
			bottom: 4rpx;
			color: #fff;
			background-color: #fc285c;
			font-size: 24rpx;
			border-radius: 20rpx;
			padding: 4rpx 12rpx;
		}
	}

	.addchat {
		height: 450rpx;
	}
</style>