<template>
	<view>
		<!--pages/liveMiddle/liveMiddle.wxml-->
		<image :src="date.cover_img" class="background"></image>
		<view class="button">
			<view class="btn" @tap="intoLive" v-if="flag">{{star?'进入直播间':'直播未开始'}}</view>
			<view class="btn" @tap="intoLive" v-else>查看回放</view>
			<view class="btn1" @tap="showShare">分享海报</view>
		</view>
		<v-share :hide-toast="hideShare" :product="date" :code-url="codeUrl" a-type="6" @onFather="click"></v-share>
<!-- #ifdef H5 -->
		<wx-share ref="wxshare" />
		<!-- #endif -->
		<!-- <v-share hide-toast="{{hideShare}}" product="{{pro}}" code-url="{{codeUrl}}" bg-url="{{bgUrl}}"></v-share> -->
	</view>
</template>

<script>
	// pages/liveMiddle/liveMiddle.js
	const req = require("../../utils/request.js");
	const util = require("../../utils/util.js");
	const app = getApp();
	import vShare from "../../components/share/share";

	export default {
		data() {
			return {
				flag: true,
				hideShare: true,
				star: true,
				date: '',
				codeUrl: ""
			};
		},

		components: {
			vShare
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			if(options.appId) req.setStorage('appId',options.appId);
			this.isLoad = true;
			this.query = options;

			if (options.scene) {
				this.scene = options.scene;
			}

			if (options.isShare) {
				this.query.roomid = options.id;
				req.setStorage('pidCode', options.userId);
			}
			this.getList().then(resolve=>{
				// console.log("debug1", resolve);
				this.getStar();
			})
			// console.log(options);
		},
		//分享
		onShareAppMessage: function() {
			return this.onShareMessage();
		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: async function() {
			await this.loadCodeParams();
		},
		
		onReady() {
			// #ifdef H5
			var that = this;
			//初始化分享内容
			setTimeout(function() {
				var shareContent = that.onShareMessage();
				if (shareContent) {
					shareContent.path = window.location.origin + shareContent.path;
				}
				console.log('分享内容》》》》》', shareContent);
				that.$refs.wxshare.init(shareContent);
			}, 4 * 1000);
			// #endif
		},
		
		methods: {
			click(e) {
				// console.log(e)
				this.hideShare = e
			},
			
			onShareMessage(){
				let path = '';
				let isSolution = '';
				// #ifndef H5
				isSolution = req.env[req.env.NODE_ENV].isSolution;
				// #endif
				// #ifdef H5
				isSolution = false;
				// #endif
				let userInfo = req.getStorage('userInfo');
				if(isSolution){
					path = '/share/home/index?appId='+req.getStorage('appId')+'&userId='+userInfo.id;
				}else{
					path = '/service/liveMiddle/liveMiddle?id=' + this.query.id + '&isShare=' + true + '&userId=' + userInfo.id+ '&appId=' + req.getStorage('appId');
				}
				return {
					title: req.getStorage('userInfo').nickName + '邀请您观看直播：' + this.date.name,
					imageUrl: this.date.cover_img,
					path: path
				};
			},
			
			getList() {
				return new Promise((resolve, reject) => {
					let that = this;
					
					if (!that.isLoad) return false;
					that.isLoad = false;
					let form = {
						page: 1,
						limit: 100
					};
					let date = {};
					req.getRequest('/api/live/list', form, data => {
						if (data) {
							data.map(item => {
								item.time = util.transTime(item.start_time);
								return item;
							}); // console.log(data)
					
							data.forEach(res => {
								if (res.roomid == this.query.id) {
									date = res;
								}
							});
							that.setData({
								date: date
							});
							resolve(date);
						}
					});
				});
				

			},

			onShareTimeline() {
				return {
					title: '直播分享' + this.date.name,
					imageUrl: this.date.cover_img
				};
			},

			// 分享
			showShare() {
				// #ifndef H5
				req.isLogin().then(success => {
					if (success) {
						this.getCodeUrl();
						this.setData({
							hideShare: false
						});
					}
				});
				// #endif
			},

			// 解析路由参数
			loadCodeParams() {
				let _ts = this;

				// console.log(_ts.scene);
				return new Promise((resolve, reject) => {
					if (!_ts.scene) {
						resolve();
						return false;
					}

					req.getRequest('/api/code/params', {
						scene: _ts.scene
					}, data => {
						// console.log(data);
						let res = data.scene.split('_');
						this.query.id = res[0];
						req.setStorage('pidCode', data.userId);
						req.setStorage('appId',res[res.length-1]);
						resolve();
					});
				});
			},

			getCodeUrl() {
				let that = this; //获取小程序码

				const params = {
					page: 'service/liveMiddle/liveMiddle',
					scene: this.query.id
				};
				if(req.getStorage('appId')) params.scene += '_'+ req.getStorage('appId');
				// console.log("pa--", params);
				req.getRequest('/api/program/codev', params, url => {
					// console.log(url);
					that.setData({
						codeUrl: url
					});
				});
			},

			//获取当前直播间的状态码 101：直播中，102：未开始， 可以直接进入直播间
			// 103已结束，  只能查看回放
			// 104禁播，105：暂停，106：异常，107：已过期  未处理
			getStar() {
				// console.log(this.date.time);
				let status = this.date.live_status;
				this.getDate(this.date);
				this.date.month = this.year;
				this.date.hour = this.hour;
				let str = this.date.share_img;
				if (str.indexOf("https") == -1) {
					this.date.share_img = str.replace(/http/, 'https');
				}

				let res = this.date;
				this.setData({
					date: res
				}); //状态码为101

				if (status == 101) {
					this.setData({
						flag: true,
						star: true,
						date: res
					});
				} //状态码为102


				if (status == 102) {
					this.setData({
						flag: true,
						star: false,
						date: res
					});
				} //状态码为103


				if (status == 103) {
					this.setData({
						flag: false
					});
				}
			},

			// 进入直播间
			intoLive(event) {
				let roomId = this.date.roomid;
				let customParams = encodeURIComponent(JSON.stringify({
					isShare: true,
					userId: req.getStorage(
						'userInfo').id
				}))
				// let redirect=`plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
				// uni.navigateToMiniProgram({
				// 	appId:'wxae03e9c5b5fcb1fb',
				// 	path:redirect
				// })
				uni.navigateTo({
					url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
				});
			},

			/**
			 * 
			 *  直播开始时间转换 year-month-day hour:minute:00
			 * 
			 */
			getDate(str) {
				// console.log(str)
				if (str.time) {
					// str = this.date.time;
					var strArr = str.time.split(' ');
					// console.log(strArr)
					var time = strArr[0].toString().split('-');
					var hose = strArr[1].toString().split(':');
					var hour = hose[0];
					var minute = hose[1];
					var day = time[2];
					var month = time[1];
					var year = time[0];
					var date = (month + '月' + day + '日').toString();
					var date1 = (hour + ':' + minute).toString();
					var date2 = strArr[0];
					this.year = date
					this.hour = date1
				}
			},

			getLive(id) {
				return new Promise((resolve, reject) => {
					req.getRequest('/api/live/playBack', {
						page: 1,
						limit: 10,
						room_id: id
					}, data => {
						this.videoList = data;
						resolve();
					});
				});
			},

			async playBack(event) {
				let roomId = this.date.roomid;
				await this.getLive(roomId);
				let videoList = JSON.stringify(this.videoList);
				if (videoList.length < 1) return req.msg('回放生成中');
				uni.navigateTo({
					url: '/service/video/video?videoList=' + videoList
				});
			}

		}
	};
</script>
<style>
	@import "./liveMiddle.css";
</style>
