import httpRequestApi from '../../../utils/APIClient';
Page({
    data: {
        title: '',
        id: '',
        img: '',
        fullScreenBtn: false,
        playBtn: false,
        gesture: true,
        muted: false,
        gesture: false,
        centerBtn: false,
        recordFlag: 0,
        recordSource: '',
        videoCtr: 'recordingVideoEnd',
        btnFlag: false,
        btnImgFlag: false,
        microphonePng: '../../../static/image/microphone.png',
        recordingGif: '../../../static/image/readingNow.gif',
        videoUrl: '',
        readingText: ''
    },
    onLoad: function (option) {
        console.log(option);
        this.videoCtx = null;

        const uid = wx.getStorageSync('uid')
        httpRequestApi.getClassDetail(uid, option.id).success(res => {
            console.log(res)
            wx.setNavigationBarTitle({
                title: res.data.data.title //页面标题为路由参数
            })
            let reg = /\\n/g
            this.setData({
                title: res.data.data.lesson.title,
                videoUrl: res.data.data.lesson.accompany || res.data.data.playUrl,
                img: res.data.data.lesson.iconImg,
                id: res.data.data.lesson.id,
                // readingText: res.data.data.lessonText.replace(reg,'')
                readingText: res.data.data.lesson.lessonText,
                grade: res.data.data.lesson.gradeClassify,
                productId: res.data.data.product.id
            })
            console.log(this.data.readingText)
            console.log(this.data.img)
            httpRequestApi.userIntoPage('pages/main/reading/reading','朗读页面').success((res)=>{
        
            })
        })

        this.recorderManager = wx.getRecorderManager();


        // 监听录音部分
        // 录音开始
        this.recorderManager.onStart(() => {
            // this.saveVideo();
            this.setData({
                btnImgFlag: true,
                btnFlag: false
            })
            console.log('recorder start')
        })
        // this.recorderManager.onPause(() => {
        //     wx.showToast({
        //         title: '录音被暂停',
        //         icon: 'fail',
        //         duration: 500
        //     })
        // })
        // this.recorderManager.onInterruptionBegin(() => {
        //     wx.showToast({
        //         title: '录音被应用中断开始',
        //         icon: 'fail',
        //         duration: 500
        //     })
        // })
        // this.recorderManager.onInterruptionEnd(() => {
        //     wx.showToast({
        //         title: '录音中断结束',
        //         icon: 'fail',
        //         duration: 500
        //     })
        // })
        this.recorderManager.onError(() => {
            wx.getSetting({
                success(res) {
                    if (!res.authSetting['scope.record']) {
                        wx.showModal({
                            title: '无法开启您的录音权限',
                            content: '点击右上角浮点按钮->进入关于->点击右上角按钮->设置，进行授权',
                            confirmText: '我知道了',
                            showCancel: false,
                            success(res) {
                                console.log('用户点击确定')
                            }
                        })
                    }
                    // else {
                    //     wx.showToast({
                    //         title: 'onError',
                    //         icon: 'fail',
                    //         duration: 500
                    //     })
                    // }
                }
            })
        })
        // 录音结束
        this.recorderManager.onStop((res) => {
            // wx.showToast({
            //     title: 'onStop',
            //     icon: 'fail',
            //     duration: 500
            // })
            this.videoCtx.stop();
            console.log('recorder stop', res)
            const recordFile = res.tempFilePath;
            this.setData({
                recordFlag: 0,
                recordSource: recordFile,
                btnFlag: true,
                btnImgFlag: false
            })
        })
    },
    onHide: function () {
        console.log('onhide')
        if (this.data.btnImgFlag) {
            this.recorderManager.stop();
        }

        if (this.innerAudioContext) {
            this.innerAudioContext.stop();
        }
    },
    onUnload: function () {
        console.log('onUnload')
        if (this.recorderManager) {
            this.recorderManager.stop();
        }
        if (this.innerAudioContext) {
            this.innerAudioContext.stop();
        }
    },
    // onShow:function(){

    // },
    // 视频缓冲
    // videoWaiting: function () {
    //     this.recorderManager.pause();
    // },
    // //视频播放
    // videoPlay: function () {
    //     this.recorderManager.resume();
    // },
    // 录音中视频播放结束 (控制录音同时结束)
    recordingVideoEnd: function () {
        console.log(this.data.videoCtr)
        console.log('recordingVideoEnd');
        // 
        if (this.data.recordFlag === 0) {
            // this.recordStop();

            this.playingVideoEnd();
            return;
        }
        // 录音结束
        if (this.data.recordFlag === 1) {
            this.recordStop();
        }
    },
    // 播放中视频播放结束 (控制录音同时结束)
    playingVideoEnd: function () {
        console.log('playingVideoEnd')
        this.innerAudioContext.stop();
    },
    /***
     *  recordFlag: 
     *      0 初始状态
     *      1 录音中
     *      2 录音结束
     ***/
    audioRecord: function () {
        console.log(this.data.recordFlag)
        if (this.data.recordFlag === 0) {
            // this.recordStart();
            // this.saveVideo();
            if (this.videoCtx) {
                this.videoCtx.stop();
            }
            if (this.recorderManager) {
                this.recorderManager.stop();
            }
            if (this.innerAudioContext) {
                this.innerAudioContext.stop();
            }
            this.videoComplete();
            return;
        }
        // 录音结束后
        if (this.data.recordFlag === 1) {
            wx.showLoading({
                title: '作品转码中',
                mask: true
            })
            this.recordStop();
        }
    },
    // 录音开始
    /**
     * duration: 时长 最长10分钟
            sampleRate: 44100, 采样率
            numberOfChannels: 1, 录音通道
            encodeBitRate: 192000, 码率
            format: 'mp3', 格式
            frameSize: 50 制定帧大小
     */
    recordStart: function () {
        console.log('录音开始');
        const options = {
            duration: 600000,
            sampleRate: 44100,
            numberOfChannels: 1,
            encodeBitRate: 192000,
            format: 'mp3',
            frameSize: 50
        }
        this.recorderManager.start(options);
    },
    // 录音结束
    recordStop: function () {
        console.log('录音结束')
        this.recorderManager.stop();
        wx.hideLoading()
    },
    // 播放录音
    audioPlay: function () {
        console.log('音频播放');
        if (this.innerAudioContext) {
            this.innerAudioContext.stop();
            this.videoCtx.stop();
        }
        this.innerAudioContext = wx.createInnerAudioContext();
        this.innerAudioContext.src = this.data.recordSource; // 这里可以是录音的临时路径
        console.log(this.innerAudioContext.src);
        this.videoCtx.play();
        this.innerAudioContext.play();
    },

    videoComplete: function () {
        // let videoUrl = 'http://efunimgs.ai160.com/ott/test/002tPr2Xlx07oP7B4ro40104120022hP0k010.mp4';
        this.setData({
            recordFlag: 1
        }, () => {

        })
        this.videoCtx = wx.createVideoContext('myVideo', this);
        this.videoCtx.play();
        this.recordStart();
    },
    // 上传
    upload: function () {
        if (this.videoCtx) {
            this.videoCtx.stop();
        }
        if (this.recorderManager) {
            this.recorderManager.stop();
        }
        if (this.innerAudioContext) {
            this.innerAudioContext.stop();
        }
        wx.showLoading({
            title: '作品分享中',
            mask: true
        })
        const recordSource = this.data.recordSource;
        wx.uploadFile({
            url: 'https://reader.lingjiao.cn/readerBase/file/upload',
            filePath: recordSource,
            name: '朗读录音',
            header: {
                uid: wx.getStorageSync('uid')
            },
            success: (res) => {
                const formateRes = JSON.parse(res.data);
                let audioPath = formateRes.data;
                let uid = wx.getStorageSync('uid');
                shareWorks(uid, audioPath);
            }

        })
        let shareWorks = (uid, audio) => {
            if (this.innerAudioContext) {
                this.innerAudioContext.stop();
            }
            const data = {
                "lessonId": this.data.id,
                "originVideo": this.data.videoUrl,
                "audioPath": audio,
                "title": this.data.title,
                "iconImg": this.data.img,
                "summary": this.data.grade,
                productId: this.data.productId
            };
            httpRequestApi.postWork(uid, data).success(res => {
                wx.hideLoading({
                    success: () => {
                        wx.showToast({
                            title: '上传成功',
                            icon: 'success',
                            duration: 1000,
                            success: () => {
                                console.log(res);
                                wx.redirectTo({
                                    url: `../../social/works/works?id=${res.data.data.id}`
                                })
                            }
                        })
                    }
                });

            })
        };
    }
})