<template>
	<view class="page">
		<navbar leftClick @leftClick="$utils.navigateBack" />

		<view class="content">
			<video class="video" id="video" :src="detail.vio" autoplay play-btn-position="center" :controls="!timeIsUp"
				:show-fullscreen-btn="false" :show-center-play-btn="true" @timeupdate="onTimeupdate"
				@ended="onTimeEnd"></video>
			<view class="info">
				<view class="author">{{ detail.author || '' }}</view>
				<view class="title">{{ detail.headTitle || '' }}</view>
				<view class="desc">{{ detail.textDetails || '' }}</view>
			</view>
		</view>

		<uv-overlay :show="timeIsUp" @click="onPlay" zIndex="998">
			<popupUnlock ref="popupUnlock" src="../static/sharing/unlock-video.png"></popupUnlock>
		</uv-overlay>

		<popupQrCode ref="popupQrCode" :src="detail.wxCodeImage"></popupQrCode>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'

	import popupUnlock from '../components/popupUnlock.vue'
	import popupQrCode from '../components/popupQrCode.vue'
	import shareLog from '@/utils/shareLog'

	export default {
		components: {
			popupUnlock,
			popupQrCode,
		},
		data() {
			return {
				id: null,
				detail: {
					id: null,
					headTitle: null,
					indexImage: null,
					vio: null,
					timeNum: 0,
					num: 0,
					wxCodeImage: null,
					textDetails: null,
				},
				timeIsUp: false,
				isLocked: true,
				videoContext: null,
			}
		},
		computed: {
			...mapState(['userInfo']),
		},
		onShow() {
			// if (this.id && uni.getStorageSync('token')) {
			//   this.detail.id ? this.refreshLockStatus() : this.initData()
			// }

			if (this.detail.id) { // 转发后返回页面的场景
				this.refreshLockStatus()
			}
		},
		async onLoad(option) {
			const {
				id,
				state,
				shareId
			} = option

			if (shareId) {
				uni.setStorageSync('shareId', shareId)
			}

			if (state) {
				uni.setStorageSync('state', state)
			}

			if (id) {
				uni.setStorageSync('id', id)
			}

			this.id = id

			// if(uni.getStorageSync('token')){
			//   this.initData()
			// }else{
			//   uni.navigateTo({
			//     url: '/pages_order/auth/wxLogin'
			//   })
			// }

			this.initData()

		},
		onShareAppMessage(res) {
			const {
				headTitle,
				indexImage,
			} = this.detail

			let o = {
				title: headTitle,
				imageUrl: indexImage,
				query: `id=${this.id}&state=1&shareId=${this.userInfo.id}`,
			}


			//调用增加分享次数的方法
			const params = {
				id: this.id,
				state: "1",
			}
			// this.$fetch('addLogShareInfo', params)
			
			// 将分享记录移到回调成功里面，避免分享取消也计数
			shareLog.insert(this.id)

			return o
		},
		methods: {
			async fetchDetails(id) {
				try {
					this.detail = await this.$fetch('getVideoShareInfo', {
						id
					})
					
					// 确保num和timeNum是数字类型
					if (this.detail) {
						this.detail.num = parseInt(this.detail.num) || 0;
						this.detail.timeNum = parseFloat(this.detail.timeNum) || 0;
					}
				} catch (err) {

				}
			},
			async initData() {
				this.isLocked = true
				await this.fetchDetails(this.id)
				this.videoContext = uni.createVideoContext('video');
				
				// 初始加载时检查是否已经解锁
				const result = await this.fetchCheckShare()
				if (result.open) {
					this.isLocked = false
					this.timeIsUp = false
				}
			},
			async refreshLockStatus() {
				// 不要在这里设置timeIsUp = false，这会导致弹窗被关闭
				// this.timeIsUp = false
				
				setTimeout(async () => {
					const result = await this.fetchCheckShare()
					const {
						open,
						need_num,
						num
					} = result
					
					if (open) { // 转发已达标
						this.videoContext.play()
						this.isLocked = false
						this.timeIsUp = false // 只有在达标时才关闭弹窗
						return
					}else{
                        if(this.timeIsUp){
                            this.onPlay()
                        }
                    }
					
					// 如果未达标，只显示提示，不改变弹窗状态
					uni.showToast({
						title: `还需转发${need_num - num}次`,
						icon: 'none',
					})
				})
			},
			async fetchCheckShare() {
				try {
					// 确保detail.num被转换为数字，因为API返回的是字符串类型
					const numValue = parseInt(this.detail.num) || 0;
					return await shareLog.check(this.id, numValue)
				} catch (err) {
					return {}
				}
			},
			async onPlay() {
				if (!this.isLocked) {
					return
				}

				// 先检查是否已经达到分享条件
				const result = await this.fetchCheckShare()
				if (result.open) {
					this.isLocked = false
					this.timeIsUp = false
					this.videoContext.play()
					return
				}

				// 如果未达到条件，则暂停视频并显示弹窗
				this.videoContext.pause()
				this.timeIsUp = true
				this.$refs.popupUnlock.open();
			},
			async onTimeupdate(e) {
				const {
					currentTime
				} = e.target

				if (currentTime >= this.detail.timeNum && this.isLocked) {
					this.onPlay()
				}
			},
			onTimeEnd() {
				this.$refs.popupQrCode.open()
			},
		},
	}
</script>

<style scoped lang="scss">
	.video {
		width: 100%;
		height: calc(100vh - #{$navbar-height} - var(--status-bar-height) - 20rpx);
	}

	.info {
		color: #FFFFFF;
		font-size: 28rpx;

		position: fixed;
		left: 40rpx;
		bottom: 100rpx;

		.title {
			font-size: 32rpx;
			margin: 5rpx 0;
		}
	}
</style>