<template>
	<view style="display: none;">阅读socket正在运行...</view>
</template>
<script>
	import {
		info
	} from '@/api/user'

	export default {
		name: 'ReadSocket',
		props: {
			value: String,
			courseId: String
		},
		data() {
			return {
				websocket: null,
				stompClient: null,
				timer: null,
				fileId: '',
				userId: '',
				msgShow: false
			}
		},
		watch: {

			value: {
				handler() {
					this.fileId = this.value
				}
			}
		},
		created() {
			this.fileId = this.value
		},

		mounted() {
			let token = uni.getStorageSync('token');
			info(token).then(res => {
				console.log(res)
				this.userId = res.id
				this.connection()
			})
		},

		destroyed() {
			// 关闭连接
			uni.closeSocket()
			
			// 清理定时器
			if(this.timer!=null){
				clearInterval(this.timer)
			}
		},

		methods: {

			beat() {
				// 清理定时器
				if (this.timer!=null) {
					clearInterval(this.timer)
				}
				let that = this
				// 10秒联系一次
				this.timer = setInterval(() => {
					// 发送消息
					that.sendPing()
				}, 10000)

				// 维持心跳
				this.sendPing();
			},

			sendPing() {

				// 发送消息，断线重连
				uni.sendSocketMessage({
					data: 'ping',
					success: res => {
						return;
					},
					fail: err => {
						// 未连接打开websocket连接
						this.connection();
					}
				});
			},

			// 建立连接
			connection() {

				// socket服务器
				let host = this.$urls.socket

				// 如果为空，则表示使用自己的
				if (host == null || host === '') {
					const https = 'https:' == document.location.protocol ? true : false;
					host = https ? 'wss://'+window.location.host : 'ws://' + window.location.host
				}

				let that = this
				const socketUrl = `${host}/api/socket/read/${this.userId}/${this.courseId}/${this.fileId}`
				console.log('开始连接：', socketUrl);
				uni.connectSocket({
					url: socketUrl
				});

				uni.onSocketError(function(res) {
					console.log('WebSocket连接打开失败，请检查！');
				});

				// 连接打开开始计时
				uni.onSocketOpen(function(res) {
					console.log('WebSocket连接已打开！');
					// 开始发送数据
					that.beat()
				});

				// 关闭连接
				uni.onSocketClose(function(res) {
					console.log('WebSocket 已关闭！');
				});


				// 收到消息
				uni.onSocketMessage(function(res) {

					console.log('msg', res.data)
					const data = JSON.parse(res.data)
					
					// 意外终止消息
					if (data.stopped) {
						uni.showToast({
							icon: 'none',
							title: data.stopMsg,
							duration: 3500
						})
					
						that.msgShow = true
						setTimeout(() => {
							// 切到课程页面回去
							uni.switchTab({
								url: '/pages/course/index'
							})
						}, 3500)
						return
					}
					
					if (data.all && !that.msgShow) {
						uni.showToast({
							title: '恭喜，您已经学完全部课程啦！',
							icon: 'none',
							duration: 2000
						});
						
						that.msgShow = true
						
						return
					}

					if (data.current && !that.msgShow) {
						uni.showToast({
							title: '恭喜，您已学完本课件！',
							icon: 'none',
							duration: 2000
						});
						that.msgShow = true
						return
					}

				})

			}
		}
	}
</script>
