import {
    submitTask
} from '~/api/global'
var videoAd = null;
Component({
    /**
     * 组件的属性列表
     */
    properties: {

    },
    lifetimes: {
        attached() {
            this.createVideo()
        }
    },
    /**
     * 组件的初始数据
     */
    data: {

    },

    /**
     * 组件的方法列表
     */
    methods: {
        rewardedVideo() {
            if (!videoAd) {
                this.createVideo()
            }
            videoAd.show().catch(err => {
                // 失败重试
                videoAd.load()
                    .then(() => videoAd.show())
            })
        },
        // 创建广告对象并监听
        createVideo() {
            if (wx.createRewardedVideoAd) {
                // 加载激励视频广告
                videoAd = wx.createRewardedVideoAd({
                    adUnitId: 'adunit-77f46b2dc73da123'
                })
                //捕捉错误
                videoAd.onError(err => {
                    console.log(err);
                })
                // 监听关闭
                videoAd.onClose((status) => {
                    videoAd.offClose()
                    videoAd = null
                    if (status && status.isEnded || status === undefined) {
                        // 正常播放结束,下发奖励
                        submitTask({
                            id: 3
                        }).then(res => {
                            wx.showToast({
                                icon: 'none',
                                title: '观看成功!',
                            })
                            this.triggerEvent('taskOver')
                        })
                    } else {
                        // 播放中途退出,进行提示
                        wx.showToast({
                            icon: 'none',
                            title: '取消观看',
                        })
                    }
                })
            }
        }
    }
})