/**
 * 激励视频广告混入
 * 提供激励视频广告的通用功能
 */
export default {
	data() {
		return {
            rewardedRecordConfig: {
                category: 3, // 分类 3激励视频
                type: 0, // 类型 0帖子-1租房-2工作-3景点-4美食-5活动-6人找车-7车找人-8文章-9群聊-10抽奖
                formId: '', // 目标对象ID
            },
			// 视频广告相关
			rewardedVideoAd: null, // 激励视频广告实例
			isAdLoaded: false, // 广告是否已加载
			isWatchingAd: false, // 是否正在观看广告
			adUnitId: 'adunit-3b232fe9e10e8744' // 广告位ID，需要替换为实际的广告位ID
		}
	},
	
	mounted() {
		this.initRewardedVideoAd()
	},
	
	methods: {
		/**
		 * 初始化激励视频广告
		 */
		initRewardedVideoAd() {
			// #ifdef MP-WEIXIN
			if (wx.createRewardedVideoAd) {
				this.rewardedVideoAd = wx.createRewardedVideoAd({
					adUnitId: this.adUnitId
				})
				
				// 监听广告加载成功
				this.rewardedVideoAd.onLoad(() => {
					console.log('激励视频广告加载成功')
					this.isAdLoaded = true
					// 调用子组件的回调方法（如果存在）
					if (this.onAdLoaded && typeof this.onAdLoaded === 'function') {
						this.onAdLoaded()
					}
				})
				
				// 监听广告加载失败
				this.rewardedVideoAd.onError((err) => {
					console.log('激励视频广告加载失败', err)
					this.isAdLoaded = false
					// 调用子组件的回调方法（如果存在）
					if (this.onAdError && typeof this.onAdError === 'function') {
						this.onAdError(err)
					}
				})
				
				// 监听广告关闭
				this.rewardedVideoAd.onClose((res) => {
					this.isWatchingAd = false
					if (res && res.isEnded) {
						// 用户看完了广告
						console.log('用户看完广告')
						// 调用临时回调方法或组件中定义的方法
						if (this.tempOnAdWatchComplete && typeof this.tempOnAdWatchComplete === 'function') {
							this.tempOnAdWatchComplete()
						} else if (this.onAdWatchComplete && typeof this.onAdWatchComplete === 'function') {
							this.onAdWatchComplete()
						}

					} else {
						// 用户中途关闭了广告
						console.log('用户中途关闭广告')
						// 调用临时回调方法或组件中定义的方法
						if (this.tempOnAdWatchCancel && typeof this.tempOnAdWatchCancel === 'function') {
							this.tempOnAdWatchCancel()
						} else if (this.onAdWatchCancel && typeof this.onAdWatchCancel === 'function') {
							this.onAdWatchCancel()
						} else {
							// 默认提示
							uni.showToast({
								title: '请观看完整广告',
								icon: 'none'
							})
						}
					}

                    this.$api('addBrowseRecord', {
                        ...this.rewardedRecordConfig,
                        complete: (res && res.isEnded) ? 'Y' : 'N'
                    })
					
					// 清理临时回调方法
					this.tempOnAdWatchComplete = null
					this.tempOnAdWatchCancel = null
					this.tempOnAdError = null
				})
				
				// 预加载广告
				this.rewardedVideoAd.load()
			} else {
				console.log('当前环境不支持激励视频广告')
			}
			// #endif
		},

		/**
		 * 显示激励视频广告
		 * @param {Object} options 配置选项
		 * @param {Function} options.onSuccess 观看完成后的回调
		 * @param {Function} options.onCancel 取消观看的回调
		 * @param {Function} options.onError 广告加载失败的回调
		 * @param {String} options.fallbackTitle 广告加载失败时的弹窗标题
		 * @param {String} options.fallbackContent 广告加载失败时的弹窗内容
		 */
		showRewardedVideoAd(options = {}) {
			// 如果正在观看广告，直接返回
			if (this.isWatchingAd) {
				return
			}
			
			// 保存当前的回调方法，避免覆盖组件中已定义的方法
			const originalOnAdWatchComplete = this.onAdWatchComplete
			const originalOnAdWatchCancel = this.onAdWatchCancel
			const originalOnAdError = this.onAdError
			
			// 临时设置回调方法
			if (options.onSuccess) {
				this.tempOnAdWatchComplete = options.onSuccess
			}
			if (options.onCancel) {
				this.tempOnAdWatchCancel = options.onCancel
			}
			if (options.onError) {
				this.tempOnAdError = options.onError
			}
			
			// #ifdef MP-WEIXIN
			if (this.rewardedVideoAd) {
				this.isWatchingAd = true
				this.rewardedVideoAd.show().catch(() => {
					// 广告显示失败，重新加载
					this.rewardedVideoAd.load().then(() => {
						return this.rewardedVideoAd.show()
					}).catch((err) => {
						console.log('激励视频广告显示失败', err)
						this.isWatchingAd = false
						
						// 显示失败处理
						const title = options.fallbackTitle || '广告加载失败'
						const content = options.fallbackContent || '无法加载广告，是否继续操作？'
						
						uni.showModal({
							title: title,
							content: content,
							success: (res) => {
								if (res.confirm) {
									// 用户确认继续，调用成功回调
									if (this.tempOnAdWatchComplete && typeof this.tempOnAdWatchComplete === 'function') {
										this.tempOnAdWatchComplete()
									} else if (originalOnAdWatchComplete && typeof originalOnAdWatchComplete === 'function') {
										originalOnAdWatchComplete.call(this)
									}
								}
								// 恢复原始回调方法
								this.onAdWatchComplete = originalOnAdWatchComplete
								this.onAdWatchCancel = originalOnAdWatchCancel
								this.onAdError = originalOnAdError
							}
						})
					})
				})
			} else {
				// 没有广告实例，直接调用成功回调
				if (this.tempOnAdWatchComplete && typeof this.tempOnAdWatchComplete === 'function') {
					this.tempOnAdWatchComplete()
				} else if (originalOnAdWatchComplete && typeof originalOnAdWatchComplete === 'function') {
					originalOnAdWatchComplete.call(this)
				}
				// 恢复原始回调方法
				this.onAdWatchComplete = originalOnAdWatchComplete
				this.onAdWatchCancel = originalOnAdWatchCancel
				this.onAdError = originalOnAdError
			}
			// #endif
			
			// #ifndef MP-WEIXIN
			// 非微信小程序环境，直接调用成功回调
			if (this.tempOnAdWatchComplete && typeof this.tempOnAdWatchComplete === 'function') {
				this.tempOnAdWatchComplete()
			} else if (originalOnAdWatchComplete && typeof originalOnAdWatchComplete === 'function') {
				originalOnAdWatchComplete.call(this)
			}
			// 恢复原始回调方法
			this.onAdWatchComplete = originalOnAdWatchComplete
			this.onAdWatchCancel = originalOnAdWatchCancel
			this.onAdError = originalOnAdError
			// #endif
		},

		/**
		 * 重新加载广告
		 */
		reloadAd() {
			// #ifdef MP-WEIXIN
			if (this.rewardedVideoAd) {
				this.rewardedVideoAd.load()
			}
			// #endif
		},

		/**
		 * 销毁广告实例
		 */
		destroyAd() {
			// #ifdef MP-WEIXIN
			if (this.rewardedVideoAd) {
				this.rewardedVideoAd.destroy()
				this.rewardedVideoAd = null
			}
			// #endif
		}
	},
	
	// 组件销毁时清理广告实例
	beforeDestroy() {
		this.destroyAd()
	},
	
	// uni-app 生命周期
	onUnload() {
		this.destroyAd()
	}
}