import httpRequestApi from '../../../utils/APIClient';
import {
    formatDate
} from '../../../utils/util';
import {
    getOpenidNoLogin
} from '../../../utils/httpUtilNoLogin';
import {
    getOpenidSessionKey
} from '../../../utils/httpUtil';
const app = getApp()
Page({
    data: {
        fullScreenBtn: false,
        playBtn: true,
        gesture: false,
        author: '',
        videoSrc: '',
        total: '',
        authorAvatar: '',
        user: [],
        inputValue: '',
        inputSBValue: '',
        replyList: [],
        howMuch: '200',
        moneySelect: 'moneySelect',
        moneyNormal: 'moneyNormal',
        ifReward: false,
        id: '',
        path: '',
        replyModal: false,
        totalRead: 0,
        pageNo: 1,
        pageSize: 3,
        goBackHome: false,
        isIOS: app.globalData.isIOS,
        alertFlag: false,
        modalType: "text",
        noScroll: '',
        modalText: app.globalData.isIOS ? [{
                text: '由于相关规范，ios功能暂不可用',
                type: 'bigOrange'
            },
            {
                text: '联系客服解锁哦',
                type: 'normal'
            }
        ] : [{
                text: '快去开通VIP',
                type: 'bigOrange'
            },
            {
                text: '享受更多权益吧',
                type: 'normal'
            }
        ],
        modalBtnText: '解锁课程',
        isModalShow: false,
        modalCloseShow: true,
        hide: true,
        addComeOut: '',
        flowerNum: '6',
        readIsRisky: ''
        // shareFlag: false
    },
    showAlert: function () {
        this.setData({
            alertFlag: !this.data.alertFlag
        })
    },
    onLoad: function (option) {
        console.log(option)
        console.log(option.flowerCount)
        console.log(option.flowerCount === 0)
        if (option.flowerCount) {
            this.setData({
                fromReading: true
            })
            this.flowerAnimationHandler();
            // setTimeout(() => {
            //     this.openShare();
            // }, 300)
            if (option.flowerCount > 0) {
                this.setData({
                    flowerNum: option.flowerCount
                })
            }
        }
        // getOpenidNoLogin
        getOpenidNoLogin((res) => {
            let id = option.id ? option.id : option.scene.replace('QR', '')
            if (option.scene || option.shareCard) {
                this.setData({
                    goBackHome: true
                })
            }
            // wx.setNavigationBarTitle({
            //     title: option.title //页面标题为路由参数
            // })
            this.uid = wx.getStorageSync('uid');
            let stackSize = 1;
            if (option.stackSize) {
                stackSize = option.stackSize;
            }
            console.log(2222222222222222)
            this.setData({
                // title: option.title,
                id: id,
                myUid: this.uid,
                stackSize
            }, () => {
                console.log(this.data.id)
                this.getWorks(this.uid, id);
                // this.getReply();
            })

        }, (error) => {
            wx.setStorageSync('userSourseType', 'reading')
            // this.setData({
            //     hide: !this.data.hide,
            //     onLoadOption: option
            // })
            return;
        });
    },
    onHide: function () {
        // this.data.stackSize >= 2
        console.log('=================================hide')
        if (this.innerAudioContext) {
            console.log('音频应该被暂停')
            this.innerAudioContext.pause();
            this.innerAudioContext.volume = 0;
        }
        // this.videoCtx = null
    },
    onUnload: function () {
        console.log('-------------------页面雨鞋')
        if (this.videoPlayTime) {
            const data = {
                "title": this.data.title,
                "lessonId": this.data.classId,
                "productId": this.data.productId,
                "playStopTime": Math.ceil(this.videoPlayTime),
                "userReadId": this.data.userReadId,
                "type": 'READ',
            }
            httpRequestApi.playLogReport(data).success(res => {
                console.log(res)
            })
            if (this.innerAudioContext) {
                console.log('音频应该被暂停')
                this.innerAudioContext.pause();
                this.innerAudioContext.volume = 0;
            }
        }

        if (this.innerAudioContext) {
            this.innerAudioContext.destroy();
        }
        this.videoCtx = null
        // let videoCtx = wx.createVideoContext('worksVideo', this);
        // videoCtx.stop();
    },
    getWorks: function (uid, id) {
        httpRequestApi.getWorksDetail(uid, id, this.data.goBackHome ? 'READ_SHARE' : '').success((res) => {

            const others = res.data.data.otherRead;
            const author = res.data.data.user;
            const works = res.data.data.userRead;
            console.log(11111111, author)
            console.log(22222222, others)

            wx.setNavigationBarTitle({
                title: works.title //页面标题为路由参数
            })
            const othersTemp = [];
            others.forEach((item) => {
                if (!item) return
                const temp = {};
                temp.uid = item.userRead.id;
                temp.title = item.userRead.title;
                temp.image = item.user.avatar;
                temp.nickName = item.user.wechatName;
                othersTemp.push(temp);
            });
            this.setData({
                user: othersTemp,
                totalRead: res.data.data.totalRead,
                author: author.wechatName,
                authorAvatar: author.avatar,
                authorProfession: author.profession,
                authorUid: author.uid,
                audioSrc: works.audioPath,
                iconImg: works.iconImg,
                classId: works.lessonId,
                isLike: res.data.data.isLike,
                isFans: res.data.data.isFans,
                videoSrc: works.originVideo,
                title: works.title,
                userReadId: works.id
            })
            httpRequestApi.checkLesson(works.lessonId).success(res => {
                const productId = res.data.data[0];
                this.setData({
                    productId: productId
                })
            });
            if (this.data.fromReading) {
                setTimeout(() => {
                    this.openShare()
                })
            }
            if (works.isRisky === 'DEL') {
                this.setData({
                    readIsRisky: 'DEL'
                });
                return false;
            }
            // 设置音频路径
            this.innerAudioContext = wx.createInnerAudioContext();
            this.innerAudioContext.onPause((res) => {
                // 播放音频失败的回调
                console.log('音频暂停')
            })
            this.innerAudioContext.src = this.data.audioSrc; // 这里可以是录音的临时路径


        });
    },
    onShow() {
        this.timeOut = setInterval(()=>{
            if (this.data.id) {
                clearInterval(this.timeOut)
                this.setData({
                    replyList: [],
                    pageNo: 1,
                    pageSize: 8
                }, () => {
                    this.getReply();
                })
            }
        },200)
        
    },
    videoPlayHandler: function () {
        if (this.data.readIsRisky === 'DEL') {
            wx.showModal({
                title: '提示',
                content: '作品还在审核中，请稍后收听（一分钟内）。',
                confirmText: '我知道了',
                showCancel: false,
                success(res) {
                    console.log('用户点击确定')
                }
            })
            return false;
        }
        this.setData({
            videoLoad: true
        }, () => {
            this.videoCtx = wx.createVideoContext('worksVideo', this);
            this.videoCtx.play();
        })
    },
    likeWorks: function (e) {
        // + 1 + 1的动画
        this.setData({
            addComeOut: 'add-one-come-out'
            // isLike: true
        })
        setTimeout(() => {
            if (this.data.addComeOut) {
                this.setData({
                    addComeOut: ''
                })
            }
        }, 1100)

        // 恭喜获得x朵小红花
        if (this.data.isLike) {
            // wx.showToast({
            //     title: '不要重复点赞哦',
            //     icon: 'fail',
            //     duration: 1000
            // })
            return;
        }
        httpRequestApi.likeWorks(this.uid, this.data.id).success(res => {
            this.setData({
                isLike: true,
                flowerNum: res.data.count
            }, () => {
                if (res.data.count > 0) {
                    this.flowerAnimationHandler();
                }
            });
        })

    },
    // 弹出分享框
    openShare: function (e) {
        console.log(this.data.authorAvatar)
        console.log(this.data.author)
        console.log(this.data.iconImg)
        console.log(this.data.title)
        console.log(this.data.id)
        if (this.data.authorAvatar && this.data.author && this.data.iconImg && this.data.title && this.data.id) {
            this.shareDialog = this.selectComponent("#share-dialog");
            const data = {
                avatar: this.data.authorAvatar,
                author: this.data.author,
                iconImg: this.data.iconImg,
                title: this.data.title,
                path: `pages/social/works/works`,
                scene: this.data.id,
                productId: this.data.productId
                // tip: this.data.tip,
            }
            // console.log(data)
            this.setData({
                noScroll: 'noScroll'
            })
            this.shareDialog.share(data);
        }
    },
    // 分享框关闭
    shareDialogClose: function (e) {
        this.setData({
            noScroll: ''
        })
    },
    videoPlay: function (event) {
        console.log(11111, this.videoPlayTime)
        if (this.data.readIsRisky === 'DEL') {
            wx.showModal({
                title: '提示',
                content: '作品还在审核中，请稍后收听（一分钟内）。',
                confirmText: '我知道了',
                showCancel: false,
                success(res) {
                    console.log('用户点击确定')
                }
            })
            return false;
        }
        if (this.innerAudioContext) {
            this.innerAudioContext.volume = 1;
            if (this.videoPlayTime) {
                this.innerAudioContext.seek(this.videoPlayTime);
            }
        }
        console.log('============', this.data.goBackHome)
        // 视频开始 先结束 再开始
        // this.innerAudioContext.play();
        // this.innerAudioContext.pause();
        // wx.showToast({
        //     title: '加载中',
        //     icon: 'loading',
        //     duration: 600
        // })
        // setTimeout(() => {
        this.innerAudioContext.play();
        // }, 800)
        // httpRequestApi.playWorks(this.uid, this.data.id).success(() => {
        //     console.log('容个错')
        // });
    },
    // 视频播放完毕销毁录音
    videoEnd: function (e) {
        console.log(e)

        this.innerAudioContext.stop();
    },
    videoPause: function (event) {
        console.log('视频暂停')
        console.log('暂停', event)
        this.innerAudioContext.pause();
        this.innerAudioContext.volume = 0;
    },
    videoWaiting: function () {
        console.log('视频缓冲')
        this.innerAudioContext.pause();
    },
    videoProgress: function (e) {
        if (e.detail.buffered <= 10) {
            this.innerAudioContext.pause();
        } else {
            this.innerAudioContext.play();
        }
    },
    videoTimeupdate: function (e) {
        this.videoPlayTime = e.detail.currentTime
        // if (e.detail.currentTime - this.innerAudioContext.currentTime >= 1) {
        //     this.innerAudioContext.seek(e.detail.currentTime - 0.1);
        // } 
    },
    goToReading: function () {
        // this.setData({
        //     isModalShow: true
        // })
        // return
        const classId = this.data.classId;
        if (this.innerAudioContext && this.videoCtx) {
            this.videoCtx.pause();
            this.innerAudioContext.pause();
            this.innerAudioContext.volume = 0;
            console.log('关闭音频')
        }
        getOpenidSessionKey((res) => {
            httpRequestApi.getUserAuth().success(res => {
                if (res.data.data) {
                    wx.authorize({
                        scope: 'scope.record',
                        success() {
                            // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                            console.log('成功')
                            wx.navigateTo({
                                url: `../../reading/reading?id=${classId}`
                            })
                        },
                        fail() {
                            wx.showModal({
                                title: '录音前请打开麦克风权限',
                                content: '点击右上角浮点...，选择：设置-麦克风，点击/打开。',
                                confirmText: '我知道了',
                                showCancel: false,
                                success(res) {
                                    console.log('用户点击确定')
                                }
                            })
                        }
                    })
                } else {
                    if (this.data.isIOS) {
                        wx.navigateTo({
                            url: `../../vipPage/wechat/wechat`
                        })
                    } else {
                        this.setData({
                            modalType: 'androidVIP',
                            isModalShow: true
                        })
                    }

                }
            })
        }, (error) => {
            this.setData({
                hide: !this.data.hide
            })
            return;
        });
    },
    onShareAppMessage: function () {
        console.log(this.data.productId);
        const data = {
            shareTypeEnum: 'LINK',
            shareContentEnum: 'READ',
            productId: this.data.productId
        }
        httpRequestApi.shareRecord(data).success((res) => {
            console.log(res)
        })
        return {
            title: '一样的课文，不一样的味道！我的配音表演已开始，求各位大咖围观、点评！',
            path: `pages/social/works/works?id=${this.data.id}&title=${this.data.title}&shareCard=true`,
            imageUrl: `https://efunbox.lingjiao.cn/reader/resource/share/read_${this.data.productId}.jpg`,
        }
    },
    follow: function () {
        let followUid = this.data.authorUid;
        if (this.data.isFans) {
            httpRequestApi.cancerFollow(this.uid, followUid).success((res) => {
                this.setData({
                    isFans: false
                })
                wx.showToast({
                    title: '取消关注',
                    icon: 'success',
                    duration: 1000
                })
            });
        } else {
            httpRequestApi.followUser(this.uid, followUid).success((res) => {
                this.setData({
                    isFans: true
                })
                wx.showToast({
                    title: '关注啦',
                    icon: 'success',
                    duration: 1000
                })
            });
        }
    },
    // 点赞评论
    likeCommend: function (e) {
        console.log(e);
        // let uid = wx.getStorageSync('uid');
        let followUid = e.currentTarget.dataset.id;
        let index = e.currentTarget.dataset.index;
        httpRequestApi.likeCommend(this.uid, followUid).success(res => {
            console.log(res);
            const str = `replyList[${index}].likes`;
            const strImg = `replyList[${index}].isLike`;
            this.setData({
                [str]: res.data.data.favors,
                [strImg]: true
            })
        });
    },
    // 去用户主页
    goToUsers: function (e) {
        let uid = e.currentTarget.dataset.uid;
        wx.navigateTo({
            url: `../../user/myworks/myworks?uid=${uid}`
        });
    },
    // 去其他用户的作品页
    goToOthers: function (e) {
        this.data.stackSize++;
        console.log(this.data.stackSize)
        if (this.data.stackSize >= 3) {
            console.log('跳转', this.data.stackSize)
            wx.redirectTo({
                url: `../../social/works/works?id=${e.currentTarget.dataset.uid}&title=${e.currentTarget.dataset.title}&stackSize=${this.data.stackSize}`
            })
        } else {
            console.log('下一个页面', this.data.stackSize)
            wx.navigateTo({
                url: `../../social/works/works?id=${e.currentTarget.dataset.uid}&title=${e.currentTarget.dataset.title}&stackSize=${this.data.stackSize}`
            })
        }

    },
    // 查询回复
    getReply: function () {
        // let uid = wx.getStorageSync('uid');
        let columnId = this.data.id;
        console.log(123123123, columnId)
        let pageNo = this.data.pageNo;
        let pageSize = this.data.pageSize;
        httpRequestApi.getReply(this.uid, columnId, pageNo, pageSize).success((res) => {
            const replyList = res.data.data.list;
            // const replyTemp = [];
            replyList.forEach((item) => {
                const temp = {};
                temp.nickName = item.user.wechatName;
                temp.avatar = item.user.avatar;
                temp.profession = item.user.profession;
                temp.uid = item.user.uid;
                // temp.text = decodeURI(item.detailDesc);
                temp.text = item.detailDesc;
                temp.id = item.id;
                temp.replyCount = item.replyCount;
                temp.time = formatDate(item.gmtCreated, 3);
                temp.likes = item.postsAttributeInfo.favors || 0;
                temp.isLike = item.isLike;
                if (item.isRisky === 'NORMAL') {
                    this.data.replyList.push(temp);
                }
            });
            this.setData({
                replyList: this.data.replyList,
                total: this.data.replyList.length,
                totalPage: res.data.data.totalNo
            })
        });
    },
    // 打开回复详情页
    goToDetail: function (e) {
        let id = e.currentTarget.dataset.id;
        // let count = e.currentTarget.dataset.count;
        wx.navigateTo({
            url: `../../social/replyDetail/replyDetail?id=${id}&productId=${this.data.productId}`
        })
    },
    //  绑定输入框内容
    inputValue: function (e) {
        this.setData({
            inputValue: e.detail.value
        });
    },
    // 发布回复
    sendHandler: function () {
        console.log(this.data.productId)
        if (this.data.inputValue !== '') {
            // let uid = wx.getStorageSync('uid');
            let data = {
                "columnId": this.data.id,
                colunmNames: 'what',
                // "detailDesc": encodeURI(this.data.inputValue)
                "detailDesc": this.data.inputValue,
                productId: this.data.productId
            }
            httpRequestApi.postReply(this.uid, data).success(res => {
                console.log(res)
                this.setData({
                    inputValue: '',
                    pageNo: 1,
                    replyList: [],
                    flowerNum: res.data.count
                })
                this.getReply();
                if (res.data.count > 0) {
                    this.flowerAnimationHandler();
                }
            });
            // 评论成功后刷新数据

        }
    },
    flowerAnimationHandler: function () {
        this.flowerBox = this.selectComponent("#flower-box");
        this.flowerBox.comeOut();
    },
    // 触底加载
    onReachBottom: function () {
        // 当前在推荐页面 加载推荐
        if (this.data.pageNo <= this.data.totalPage) {
            this.setData({
                pageNo: this.data.pageNo + 1
            }, () => {
                this.getReply();
            })
        }


    },
    // 设置点击时的id
    setSBId: function (e) {
        this.setData({
            replySBId: e.currentTarget.dataset.id,
            replyModal: true,
            replyIndex: e.currentTarget.dataset.index
        })
    },
    // 回复某个评论
    replySB: function () {
        const data = {
            postsId: this.data.replySBId,
            content: this.data.inputSBValue,
            productId: this.data.productId
        }
        httpRequestApi.postReplyComment(this.uid, data).success(res => {
            const replyWho = this.data.replyList[this.data.replyIndex];
            const indexStr = `replyList[${this.data.replyIndex}]`;
            replyWho.replyCount++;
            this.setData({
                replyModal: false,
                [indexStr]: replyWho
            })
        });
    },
    // 获取回复楼中楼的内容
    inputSBValue: function (e) {
        this.setData({
            inputSBValue: e.detail.value
        });
    },
    // 选择金额
    setMoney: function (e) {
        this.setData({
            howMuch: e.currentTarget.dataset.money
        })
    },
    reward: function () {
        if (this.data.isIOS) {
            return
        };
        this.setData({
            ifReward: true
        })
    },
    quitReward: function () {
        this.setData({
            ifReward: false
        })
    },
    // 奖励
    rewardMoney: function () {
        const data = {
            targetUid: this.data.authorUid,
            amount: this.data.howMuch
        }
        // let uid = wx.getStorageSync('uid');
        httpRequestApi.rewardMoney(this.uid, data).success(res => {
            if (res.data.message) {
                wx.showModal({
                    title: '提示',
                    content: res.data.message,
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')
                        } else if (res.cancel) {
                            console.log('用户点击取消')
                        }
                    }
                })
                return false;
            }
            this.payMoney(res.data.data);
        })

    },
    //支付
    payMoney: function (orderInfo) {
        if (this.data.haveTapMoney) {
            return false
        }
        this.setData({
            haveTapMoney: true
        })
        wx.requestPayment({
            'appId': orderInfo.appId,
            'timeStamp': orderInfo.timeStamp,
            'nonceStr': orderInfo.nonceStr,
            'package': orderInfo.package,
            'signType': orderInfo.signType,
            'paySign': orderInfo.sign,
            'success': res => {
                this.setData({
                    modalType: 'image',
                    isModalShow: true,
                    modalCloseShow: false,
                    modalBtnText: '确定',
                    haveTapMoney: false,
                    ifReward: false
                })
                // wx.showModal({
                //     title: '提示',
                //     content: '支付成功',
                //     success(res) {
                //         if (res.confirm) {
                //             this.setData({
                //                 ifReward: false
                //             })
                //         } else if (res.cancel) {
                //             this.setData({
                //                 ifReward: false
                //             })
                //         }
                //     }
                // })

            },
            'fail': res => {
                this.setData({
                    haveTapMoney: false,
                })
                console.log('支付失败', res)
            }
        })
    },
    // 回到首页
    goBackHome: function () {
        wx.redirectTo({
            url: '../../index/index'
        })
    },
    modalConfirmHandler: function () {
        this.setData({
            isModalShow: false
        })
        if (this.data.isIOS) {
            // wx.navigateTo({
            //   url: `../../vipPage/vipCode/vipCode`
            // })
            wx.navigateTo({
                url: `../../vipPage/wechat/wechat`
            })
        } else {
            wx.navigateTo({
                url: `../../vipPage/vip/vip`
            })
        }

    },
    modalCloseHandler: function () {
        this.setData({
            isModalShow: false
        })
    },
    jurisdiction: function () {
        //隐藏弹框
        this.setData({
            hide: !this.data.hide
        })
        //登录页信息
        // this.onLoad(this.data.onLoadOption);
        this.goToReading();
    },
    goToClass: function () {

        if (!this.data.isIOS && this.videoCtx) {
            this.innerAudioContext.stop();
            this.innerAudioContext.destroy();
            this.videoCtx.stop();
            this.setData({
                videoLoad: false
            })
        }

        setTimeout(() => {
            wx.navigateTo({
                url: `../../main/class/class?id=${this.data.classId}`
            })
        }, 100)

    }
})