(function(){
    /**
     * 计算服务器时间
     */
    var serverTime = 0;
    /**
     * 获取服务器时间
     */
    $.get('/plus/ajaxs.ashx?a=gettime',function(time){
        var serverDate = new Date(time);
        serverTime = serverDate.getTime();
        setInterval(function(){
            serverTime += 100;
        },100)
    });
    window.getCosKeshi = function(courseid,courseType,current,keshiTarget){
        var $el = $('#getCosKeshi');
        var target = keshiTarget === '_blank' ? ' target="_blank"' : '';
        var getUrl = courseType === 'face' ? '/plus/ajaxs.ashx?a=getcosInfo&isface=1' : '/plus/ajaxs.ashx?a=getcosInfo';
        if(courseid === undefined){
            return false
        }
        $el.html('<div class="chapter-loading">加载中...</div>')
        
        
        /**
         * 通过periodid获取dom
         */
        function getPeriodidDom(periodid){
            return $el.find('[data-periodid="'+periodid+'"]')
        }

        /**
         * 将秒数转换 mm:ss 格式
         */
        function secondsConversion(ss){
            var time = Number(ss);
            var hour = Math.floor(time / 3600);
            var minute = Math.floor((time - hour*3600) / 60);
            var second = time - hour*3600 - minute*60
            hour = hour.toString().length < 2 ? '0'+hour : hour
            minute = minute.toString().length < 2 ? '0'+minute : minute
            second = second.toString().length < 2 ? '0'+second : second
            return hour === '00' ? minute+':'+second : hour+':'+minute+':'+second
            
        }

        $.ajax({
            type:'get',
            dataType:'json',
            url:getUrl+'&courseid='+courseid,
            success: function (data) {
                console.log(data)
                
                /**
                 * 课程购买链接
                 */
                var coursebuyurl = data.Course.coursebuyurl;
                /**
                 * 课程购买情况
                 */
                var specialPermission = false;
                var buyallcos_isCanLearn = false;
                var myPeriodids = [];
                var Pay = data.Pay;
                var ispower = data.ispower;

                /**
                 * 判断是否有特殊权限
                 */
                if(ispower == 1){
                    specialPermission = true

                }else if(Pay){
                    
                    /**
                     * 是否购买了整个课程
                     */
                    var isbuyallcos = Pay.isbuyallcos;
                    var shixian = Pay.shixian;
                    if(isbuyallcos == 1){
                        if(shixian == 0){
                            /**
                             * 该课程未限制时间
                             */
                            buyallcos_isCanLearn = true;
                        }else{
                            /**
                             * 限制了时间，检查课程是否已过期
                             */
                            var enddate = new Date(Pay.enddate).getTime();
                            
                            if(enddate > serverTime){
                                buyallcos_isCanLearn = true
                            }
                        }

                    }else{
                        var periodlist = Pay.periodlist;
                        domap(periodlist,function(period_item){
                            var enddate = period_item.enddate ? new Date(period_item.enddate).getTime() : null;
                            
                            var ids = period_item.periodids.split(',');
                            for(var p=0;p<ids.length;p++){
                                myPeriodids.push({
                                    id:ids[p],
                                    shixian:period_item.shixian,
                                    enddate:enddate
                                })
                            }
                        })
                        
                    }
                }
                
                /**
                 * 课程学习情况
                 */
                var Learn = data.Learn;
                var myLearnPeriodlist = [];
                if(Learn){
                    myLearnPeriodlist = Learn.periodlist
                }

                /**
                 * 课时列表
                 */
                var periodlist = data.Course.periodlist;
                var chapterIndex = 0;
                var sectionIndex = 0;
                var keshiIndex = 0;
                if(!periodlist.length){
                    $el.html('<div class="empty">该课程下暂无课时数据</div>');
                    return false
                }
                for(var i=0;i<periodlist.length;i++){
                    var item = periodlist[i];
                    var addtype = item.addtype;
                    var periodname = item.periodname;
                    var periodid = item.periodid;
                    var parentid = item.parentid;
                    switch(addtype){
                        case '0':
                            /**
                             * 章
                             */
                            chapterIndex++;
                            $el.append('<div class="chapter"><div class="chapter-name"><span class="chapter-index">'+chapterIndex+'</span>'+periodname+'</div><div class="chapter-box" data-periodid="'+periodid+'"></div></div>')
                            break
                        case '2':
                            /**
                             * 节
                             */
                            sectionIndex++;
                            var className = parentid == 0 ? 'chapter-section ' : '';
                            var code = '<div class="'+className+'section"><div class="section-name">'+periodname+'</div><div class="section-box" data-periodid="'+periodid+'"></div></div>';
                            if(parentid == 0){
                                /**
                                 * 当parentid为0，说明是独立的节，无章
                                 */
                                $el.append(code)
                            }else{
                                /**
                                 * 在已有章节点下追加节
                                 */
                                getPeriodidDom(parentid).append(code)
                            }
                            break
                        case '1':
                        case '4':
                            /**
                             * 课时
                             */
                            keshiIndex++;

                            /**
                             * isCanLearn
                             * 0 不可观看
                             * 1 可观看
                             * 2 已过期
                             * 3 可试听
                             * 4 已过期但可试听
                             */
                            var isCanLearn = 0;
                            
                            if(specialPermission || item.isfree == 0){
                                /**
                                 * 该课时免费
                                 */
                                isCanLearn = 1
                            }else if(item.islistening == 1){
                                isCanLearn = 3
                            }else if(Pay){
                                
                                if(Pay.isbuyallcos == 1 && buyallcos_isCanLearn){
                                    /**
                                     * 购买了整个课程，并且课程未到期
                                     */
                                    isCanLearn = 1;

                                }else{
                                    /**
                                     * 按课时购买
                                     * 遍历当前课时是否存在购买队列，并且课时未到期
                                     */
                                    for(var p=0;p<myPeriodids.length;p++){
                                        var period_item = myPeriodids[p];
                                        if(period_item.id == periodid){
                                            if(period_item.shixian == 0){
                                                isCanLearn = 1;
                                                break
                                            }else{
                                                if(period_item.enddate > serverTime){
                                                    /**
                                                     * 已满足学习条件，直接跳出循环
                                                     */
                                                    isCanLearn = 1;
                                                    break
                                                }else{
                                                    /**
                                                     * 当前课时已过期，但不跳出循环，继续查找是否有重复购买同课时并且满足学习条件
                                                     */
                                                    if(period_item.islistening == 1){
                                                        isCanLearn = 4
                                                    }else{
                                                        isCanLearn = 2
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    
                                }
                            }

                            /**
                             * 绑定试卷
                             */
                            var exampaper = '';
                            domap(item.exampaper,function(paper){
                                
                                exampaper += '<div class="keshi-exam"><a href="'+paper.url+'" target="_blank">【试卷】'+paper.name+'</a></div>';
                            });
                            
                            /**
                             * 资料
                             */
                            var course_file = '';
                            if(item.zlurl){
                                course_file = isCanLearn === 1 ? '<a href="'+item.zlurl+'" target="_blank"><span class="zlicon"><font class="zl-link-tips">讲义下载</font></span></a>' : '<span class="zlicon zlicon-disabled"></span>'
                                
                            }
                            
                            /**
                             * 学习进度
                             */
                            var schedule = 0;
                            domap(myLearnPeriodlist,function(learn_period){
                                if(learn_period.periodid == periodid){
                                    schedule = learn_period.status == 1 ? 100 : (learn_period.maxlearncount / learn_period.timecount).toFixed(1)*100
 
                                }
                            })
                            
                            var learnState = '<div class="learn-state"><span class="schedule-icon'+schedule+'"></span></div>';
                            var active = periodid == current ? ' active' : '';
                            var href = (isCanLearn === 1 || isCanLearn === 3 || isCanLearn === 4) ? item.url : coursebuyurl;
                            
                            var unlearn = isCanLearn === 1 ? '' : ' unlearn';
                            var state = ((isCanLearn === 1 && schedule > 0) && '继续学习') || (isCanLearn === 1 && '开始学习') || (isCanLearn === 2 && '已过期') || (isCanLearn === 3 && '试听') || (isCanLearn === 4 && '已过期') || '去购买';
                            var icon_lock = isCanLearn === 1 ? '' : '<i class="icon-lock"></i>';
                            var className = parentid == 0 ? 'chapter-keshi ' : '';
                            var free = item.isfree == 0 ? '<span class="free">免费</span>' : '';
                            var time = secondsConversion(item.timecount);
                            var code = '<div class="'+className+'keshi'+active+'" data-periodid="'+periodid+'">'+course_file+'<a href="'+href+'" class="keshi-url'+unlearn+'"'+target+'>'+icon_lock+'<span class="learn-btn">'+state+'</span>'+learnState+'<span class="type-name">课时'+keshiIndex+'</span>'+periodname+free+'<span class="keshi-duration">'+time+'</span></a>'+exampaper+'</div>';
                            parentid == 0 ? $el.append(code) : getPeriodidDom(parentid).append(code)
                            
                            break
                    }
                }
                $el.find('.chapter-loading').remove()

            },error:function(){
                
                $el.html('<div class="data-errer">数据请求失败了，程序员正在抢修中...</div>');
            }
        });
    }

    /**
     * 遍历
     */
    function domap(data,fn){
        for(var i=0;i<data.length;i++){
            fn(data[i],i)
        }
    }
})();