Vue.config.devtools = true;

var v = new Vue({
    el: ".container",
    data: {
        isVip: localStorage.getItem('isVip') == 1,
        cata: [
            {name: "目录", active: 1, id: 1, disable: true},
            {name: "详情", active: 0, id: 2, disable: true},
            {name: "互动", active: 0, id: 3, disable: true},
            {name: "相关课程", active: 0, id: 4, disable: true},
        ],
        list: [],
        cataList: [],
        comments: [],
        info: {},
        start: 1,
        size: 10,
        finished: false,
        loading: false,//出现了上拉到底触发了两次请求接口的情况  加一个变量控制一下
        ad: [],//广告信息
        id: -1,
        tqCourseCourse: {},
        vodInfo: {},
        currentTime: 0,
        learnTime: 0,
        timer: null,
        canSave: true,
        content: "",
        isLogin: 0,
        memToken: '',
        memHeadImg: '',
        userJf: -1,
        playIndex: -1,
        memberInfo: {},
        toast: false,
        url: "https://www.qkyxzx.com/course/courseDetails?from=web",
        subing: 0,
        parse: false,
        integralType: "学习课程10分钟",
        integralCount: "10",
        questionFlag: false, // 是否展示调查问卷
        attestation: {},
        countNum:-1
    },
    created: function () {
        if ($.cookie("memToken")) {
            this.memToken = $.cookie("memToken");
            this.isLogin = 1;
        }
        if ($.cookie("memHeadImg")) {
            this.memHeadImg = $.cookie("memHeadImg");
        }

        this.id = $("#id").val();
        this.getIndexData();
        this.getAdInfo();
        this.findUserBaseInfo();
        this.findUserIntegral();
        this.getAttestation();
        if (typeof (fromlogin) != "undefined" && fromlogin == "1") {
            jifen();
        }
    },
    filters: {
        date(time) {
            let oldDate = new Date(time)
            let newDate = new Date()
            var dayNum = "";
            var getTime = (newDate.getTime() - oldDate.getTime()) / 1000;

            if (getTime < 60 * 5) {
                dayNum = "刚刚";
            } else if (getTime >= 60 * 5 && getTime < 60 * 60) {
                dayNum = parseInt(getTime / 60) + "分钟前";
            } else if (getTime >= 3600 && getTime < 3600 * 24) {
                dayNum = parseInt(getTime / 3600) + "小时前";
            } else if (getTime >= 3600 * 24 && getTime < 3600 * 24 * 30) {
                dayNum = parseInt(getTime / 3600 / 24) + "天前";
            }
            if (dayNum != "") {
                return dayNum;
            }
            let year = oldDate.getFullYear();
            let month = oldDate.getMonth() + 1;
            let day = oldDate.getDate();
            let hour = oldDate.getHours();
            let minute = oldDate.getMinutes();
            let second = oldDate.getSeconds();
            return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
        }
    },
    mounted() {
        var that = this;
        window.addEventListener('pageshow', function (event) {
            if (event.persisted) { // ios 有效, android 和 pc 每次都是 false
                setTimeout(() => {
                    that.findUserBaseInfo();
                }, 500);
            } else { // ios 除外
                if (sessionStorage.getItem('refresh') === 'true') {
                    setTimeout(() => {
                        that.findUserBaseInfo();
                    }, 500);
                }
            }
            sessionStorage.removeItem('refresh');
        });
        setTimeout(() => {
            var mySwiper = new Swiper('.swiper-container', {
                direction: 'horizontal', // 水平切换选项
                loop: this.ad.length > 1, // 循环模式选项
                observerParents: true,
                observer: true,
                autoplay: {
                    disableOnInteraction: false,  //触碰后自动轮播也不会停止
                    delay: 2000,
                },
                // 如果需要分页器
                pagination: {
                    el: '.swiper-pagination',
                },

                // 如果需要前进后退按钮
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },

                // 如果需要滚动条
                scrollbar: {
                    el: '.swiper-scrollbar',
                },

            })
        }, 1000);
        setTimeout(() => {
            $(".loading-item").fadeOut(200);
        }, 500)
    },
    methods: {
        getAttestation() {
            var that = this;
            $.ajax({
                type: 'POST',
                url: serverHttp + "/popu/window/checkWindow",
                data: {
                    id: that.id,
                    idType: 3,
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        that.attestation = data.data;
                    }
                },
                error: function (data) {
                }
            });
        },
        copy() {
            var aux = document.createElement("input");
            aux.setAttribute('readonly', 'readonly');
            aux.value = this.url + "&id=" + this.id;
            document.body.appendChild(aux);
            aux.setSelectionRange(0, 9999);
            aux.select();
            document.execCommand("copy");
            document.body.removeChild(aux);
            this.toast = false;
        },
        showTast() {
            this.toast = true;
        },
        closeToast() {
            this.toast = false;
        },
        getAdInfo() {
            var that = this;
            $.ajax({
                type: 'POST',
                data: {
                    id: that.id,
                },
                url: serverHttp + "/course/getAdInfoNew",
                success: function (res) {
                    if (res.code == 200) {
                        that.ad = res.data;
                    }
                },
                error: function (data) {
                }
            });
        },
        findUserIntegral() {
            var that = this;
            $.ajax({
                type: 'POST',
                url: serverHttp + "/user/findUserIntegral",
                data: {
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        that.userJf = data.data;
                    }
                },
                error: function (data) {
                }
            });
        },
        isNull(str) {
            if (str == "") return true;
            if (str == null) return true;
            var regu = "^[ ]+$";
            var re = new RegExp(regu);
            return re.test(str);
        },
        confirm() {
            if (!checkLogin()) {
                // goLogin();
                return false;
            }
            var that = this;
            if (that.isNull(that.content)) {
                alert('请输入内容');
                return;
            }
            if (that.subing == 1) {
                return false;
            }
            that.subing = 1;
            $.ajax({
                type: 'POST',
                url: serverHttp + "/course/saveCommon",
                data: {
                    memToken: that.memToken,
                    content: that.content,
                    id: that.id,
                },
                success: function (data) {
                    if (data.code == 200) {
                        // alert("保存成功");
                        $(".common").hide("slow");
                        that.content = "";
                        that.subing = 0;
                        that.getIndexData();
                    }
                },
                error: function (data) {
                }
            });
        },
        commonClose() {
            $(".common").hide("slow");
            this.content = "";
        },
        toPay() {
            if (!checkLogin()) {
                // goLogin();
                return false;
            }
            var that = this;
            if (!that.parseRule()) {
                return false;
            }
            toPay(1, that.info.id, 1, '');
        },
        addFreeBuyApi() {
            $('.allblackbox').hide();
            if (!checkLogin()) {
                // goLogin();
                return false;
            }
            var that = this;
            if (!that.parseRule()) {
                return false;
            }
            $.ajax({
                type: 'POST',
                url: serverHttp + "/pay/addFreeBuyApi",
                data: {
                    memToken: that.memToken,
                    orderType: 1,
                    objId: that.info.id,
                    ispackage: 1,
                    paySource: 1,
                    fromMemCard: $.cookie("fromMemCard")
                },
                success: function (data) {
                    if (data.code == 200) {
                        that.info.isBuy = 1;
                        that.integralType = "领取课程";
                        that.integralCount = 10;
                        $(".integral-toast").show();
                        playMusic()
                        setTimeout(function () {
                            $(".integral-toast").fadeOut(200);
                        }, 2000);
                    } else if (data.code == 10008) {
                        //去登录
                        goLogin();
                    } else {
                        alert(data.message);
                    }
                },
                error: function (data) {
                }
            });
        },
        parseRule() {
            var that = this;
            if (that.attestation.attestType == 2) {
                window.location.href = serverHttp + "/user/certificationSm?from=H5&memToken=&type=3&id=" + that.id;
                return false;
            } else if (that.attestation.attestType == 1) {
                window.location.href = serverHttp + "/user/certificationYs?from=H5&memToken=&type=3&id=" + that.id;
                return false;
            } else if (that.attestation.attestType == 4) {
                window.location.href = serverHttp + "/user/certificationSmojl?from=H5&memToken=&type=3&id=" + that.id;
                return false;
            } else if (that.attestation.attestType == 3) {
                window.location.href = serverHttp + "/user/certificationYsojl?from=H5&memToken=&type=3&id=" + that.id;
                return false;
            } else if (that.attestation.attestType == 5) {
                return true;
            }
            return true;
        },
        findUserBaseInfo() {
            var that = this;
            $.ajax({
                type: 'POST',
                url: serverHttp + "/user/findUserBaseInfo",
                data: {
                    memToken: that.memToken
                },
                success: function (data) {
                    that.memberInfo = data.data;
                },
                error: function (data) {
                }
            });
        },
        updateTime(e) {
            var video = document.getElementById('video');
            this.currentTime = Math.floor(video.currentTime) * 1000;
        },
        videoPlay() {
            this.startTiming();
        },
        videoPause() {
            var video = document.getElementById('video');
            video.pause();
            clearInterval(this.timer)
        },
        startTiming() {
            var that = this;
            that.timer = setInterval(function () {
                that.learnTime = that.learnTime + 1;
                if (that.learnTime == 600) {
                    that.integralType = "学习课程10分钟";
                    that.integralCount = 10;
                    $(".integral-toast").show();
                    playMusic()
                    setTimeout(function () {
                        $(".integral-toast").fadeOut(200);
                    }, 2000);
                }
                if (that.learnTime % 30 == 0) {
                    //1分钟的倍数
                    that.addVideoPlayRecorde();
                }
            }, 1000)
        },
        getIndexData() {
            var that = this;
            if (that.loading) {
                return;
            }
            that.loading = true;
            if (that.start == 1) {
                that.list = []
            }
            const detailParams = {
                cataId: -1,
                start: that.start,
                size: that.size,
                fId: that.id,
                memToken: that.memToken
            }

            console.log("detailParams -->", detailParams)

            $.ajax({
                type: 'POST',
                url: serverHttp + "/course/getIndexData",
                data: {
                    from: 'H5',
                    cataId: -1,
                    start: that.start,
                    size: that.size,
                    fId: that.id,
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        that.list = that.list.concat(data.data.list);
                        that.info = data.data.info;
                        that.tqCourseCourse = data.data.info;

                        if (that.tqCourseCourse.qkjVodinfo) {
                            that.newPlayer();
                        }

                        that.cataList = data.data.cataList;
                        that.comments = data.data.comments;
                        if (data.data.list) {
                            that.finished = true;
                        }
                        that.loading = false;

                        console.log("that.tqCourseCourse -->", that.tqCourseCourse)

                        $("meta[name='sharetitle']").attr("content", that.info.shareTitle);
                        $("meta[name='sharedesc']").attr("content", that.info.shareDesc);
                        $("meta[name='sharepic']").attr("content", that.info.sharePic);
                        // $("meta[name='shareurl']").attr("content",that.info.shareUrl);
                        document.title = that.info.title;
                        if (that.cataList == null || that.cataList == undefined || that.cataList.length == 0) {
                            that.cata[3].disable = false;
                        }
                        //判断是否从认证页过来
                        let lastUrl = document.referrer;
                        if (lastUrl.indexOf('user') > 0 && that.list[0].isSpecialCourse == 1 && $.cookie("coursecodestatus" + that.list[0].id) != 'ok') {
                            $("#takeCode").show();
                            $('#takeCodeBtn').click(() => {
                                that.checkCode(0)
                            })
                        }
                    } else if (data.code == 10005) {
                        that.finished = true;
                    }
                },
            });
        },
        formatDuring(mss) {
            var secondTime = parseInt(mss) // 秒
            var minuteTime = 0 // 分
            var hourTime = 0 // 小时
            var dayTime = 0 // 天
            var result = ''
            if (mss < 60) {
                result = secondTime + '秒'
            } else {
                if (secondTime >= 60) { // 如果秒数大于60，将秒数转换成整数
                    // 获取分钟，除以60取整数，得到整数分钟
                    minuteTime = parseInt(secondTime / 60)
                    // 获取秒数，秒数取佘，得到整数秒数
                    secondTime = parseInt(secondTime % 60)
                    // 如果分钟大于60，将分钟转换成小时
                    if (minuteTime >= 60) {
                        // 获取小时，获取分钟除以60，得到整数小时
                        hourTime = parseInt(minuteTime / 60)
                        // 获取小时后取佘的分，获取分钟除以60取佘的分
                        minuteTime = parseInt(minuteTime % 60)
                        if (hourTime >= 24) {
                            // 获取天数， 获取小时除以24，得到整数天
                            dayTime = parseInt(hourTime / 24)
                            // 获取小时后取余小时，获取分钟除以24取余的分；
                            hourTime = parseInt(hourTime % 24)
                        }
                    }
                }
                if (secondTime > 0) {
                    secondTime = parseInt(secondTime) >= 10 ? secondTime : '0' + secondTime
                    result = '' + secondTime + '秒'
                }
                if (minuteTime > 0) {
                    minuteTime = parseInt(minuteTime) >= 10 ? minuteTime : '0' + minuteTime
                    result = '' + minuteTime + '分' + result
                }
                if (hourTime > 0) {
                    result = '' + parseInt(hourTime) + '小时' + result
                }
                if (dayTime > 0) {
                    result = '' + parseInt(dayTime) + '天' + result
                }
            }
            return result
        },
        coursePrefectureList(id) {
            window.location.href = serverHttp + "/course/courseDetails?from=H5&id=" + id;
        },
        chooseTab(i) {
            const that = this;
            for (var item of that.cata) {
                if (item.active == 1) {
                    item.active = 0
                }
            }
            that.cata[i].active = 1;
        },
        gotoAdHtml(url) {
            window.location.href = url;
        },
        findTqCourseCourseInfo(item, i) {
            const that = this;
            var video = document.getElementById('video');
            if (video) {
                video.pause();
            }
            that.canSave = false;
            that.questionFlag = item.questionFlag == 1;
            that.addVideoPlayRecorde();
            $("#takeCodeBtn").unbind("click");
            if (!checkLogin()) {
                // goLogin();
                return false;
            }
            if (!that.parseRule()) {
                return false;
            }
            coursecodestatus = $.cookie("coursecodestatus" + this.list[i].id);
            if (coursecodestatus == "ok") {
                this.startVideo(i);
            } else {
                // 是否为定向人员课程
                if (that.list[i].isSpecialCourse == 1) { // 1为定向课程
                    $("#takeCode").show();
                    $('#takeCodeBtn').click(() => {
                        this.checkCode(i)
                    })
                } else {
                    this.startVideo(i)
                }
            }


            // else if (that.list[i].isSpecialCourse == null) { // 是否为定向人员课程专区
            //     if (that.info.isSpecialCourse == 1) {
            //         $("#takeCode").show();
            //         $('#takeCodeBtn').click(() => {
            //             this.checkCode()
            //         })
            //     } else {
            //         this.startVideo(i)
            //     }
            // }

            //that.startTiming();
        },
        startVideo(i) {
            this.countNum = i;
            if (this.list[i].isTrailer == 1 || this.info.isBuy == 1) {
                // layer.msg("课程播放结束后需要有自评"); //msg：消息提示
                if (this.questionFlag) {
                    $("#ziping").show();
                    $('#zipingBtn1').click(() => {
                        $('#ziping').hide()
                        this.tqCourseCourse = this.list[i];

                        if (this.tqCourseCourse.qkjVodinfo) {
                            this.newPlayer();
                        }

                        this.playIndex = i;
                    })
                } else {
                    this.tqCourseCourse = this.list[i];

                    if (this.tqCourseCourse.qkjVodinfo) {
                        this.newPlayer();
                    }

                    this.playIndex = i;
                }
            } else {
                $(".allblackbox").show();
                $("#takeCode").hide();
            }
        },

        newPlayer() {
            var that = this
            document.getElementById('dplayer').style.display = ""
            const dp = new DPlayer({
                container: document.getElementById('dplayer'),
                video: {
                    url: that.tqCourseCourse.qkjVodinfo.originalUrl,
                    pic: 'http://files.qkyxzx.com/' + this.tqCourseCourse.coverImg
                },
                autoplay: true,
                hotkey: true,

            });
            setTimeout(function () {
                $("#dplayer").addClass("dplayer-hide-controller")
            }, 3000);
            dp.on("timeupdate", () => {
                this.currentTime = Math.floor(dp.video.currentTime) * 1000;
                // if(this.currentTime == 3000){
                //     $("#dplayer").addClass("dplayer-hide-controller")
                // }
            });
            dp.on("play", () => {
                setTimeout(function () {
                    $("#dplayer").addClass("dplayer-hide-controller")
                }, 3000);
                this.videoPlay()
            });
            dp.on("pause", () => {
                this.videoPause()
            });
            dp.on("pause", () => {
                this.videoPause()
            });
            dp.on("ended", () => {
                this.videoEnded()
            });
            document.getElementById('dplayer').style.display = ""
            document.getElementById('dplayer').oncontextmenu = function (event) {
                event.preventDefault();
                return false;
            }
        },

        // 提取码
        checkCode(i) {
            if ($("#tqm").val() == '' || $("#tqm").val() == null) {
                alert('请输入提取码')
            } else {
                $.ajax({
                    type: 'GET',
                    url: serverHttp + "/course/checkCode",
                    async: false,
                    data: {
                        code: $("#tqm").val(),
                        id: this.list[i].id,

                    },
                    success: (data) => {
                        if (data.code == 200) {
                            $('#takeCode').hide()
                            this.startVideo(i)
                            $.cookie("coursecodestatus" + this.list[i].id, "ok");
                        } else {
                            alert(data.message)
                        }
                    },
                });
            }
        },

        beforeunloadHandler() {
            this.addVideoPlayRecorde();
        },
        addVideoPlayRecorde() {
            var that = this;
            if (that.canSave) {
                return false;
            }
            if (that.playIndex == -1) {
                return false;
            }
            $.ajax({
                type: 'POST',
                url: serverHttp + "/course/addVideoPlayRecorde",
                async: false,
                data: {
                    playTime: that.currentTime,
                    totalLearnTime: that.learnTime * 1000,
                    objType: 1,
                    objId: that.list[that.playIndex].id,
                    memToken: that.memToken
                },
                success: function (data) {
                    if (data.code == 200) {
                        // that.currentTime = 0;
                        // that.learnTime = 0;
                    }else if(data.code == 10008){
                        goLogin();
                    }else if(data.code == 10029){
                        //在另一设备登录，重新登录
                        $(".userConfirmBox").show();
                    }
                },
            });
        },
        addCommon() {
            $(".common").show("slow");
        },
        // 视频播放完成
        videoEnded() {
            if (this.questionFlag) {
                $("#wd").show();
                $('#submitWd1').click(() => {
                    if ($("#sfxh").val() == '') {
                        layer.msg("请填写答案");
                    } else {
                        $.ajax({
                            type: 'POST',
                            url: serverHttp + "/live/saveQuestionAnswer",
                            data: {
                                questions: JSON.stringify(
                                    [{
                                        objType: 3,
                                        objId: this.info.id,
                                        quTitle: '您是否学会本课程，为什么？',
                                        answerContent: $("#sfxh").val()

                                    }])
                            },

                            success: (data) => {
                                if (data.code == 200) {
                                    $("#wd").hide();
                                    layer.msg("提交成功")
                                    // that.liveInfo.isQuestionAnswer = 1;
                                }
                            },
                            error: function (data) {
                            }
                        });
                    }
                })
            }
        },

    }
})
