var SERVER_TIME = 0;
(function(Vue){

    window.KS_Main = KS_Main;

    function KS_Main(parameter){
        parameter = parameter || {};
        this.parameter = parameter;
        typeof parameter.beforeCreat === 'function' && parameter.beforeCreat();
        this.created();
        typeof parameter.created === 'function' && parameter.created()
        
    };

    KS_Main.prototype.created = function(){
        
        /**
         * 计算服务器时间
         */
        getServerTime(function(time){
            SERVER_TIME = new Date(time).getTime();
            setInterval(function(){
                SERVER_TIME += 100;
            },100)
        });

        /**
         * 定义组件
         */
        Vue.component('countdown', {
            props:{
                beginTime:[String,Number],
                endTime:[String,Number],
                interval:{
                    type:[String,Number],
                    default:1000
                },
                cdKey:[String,Number]
            },
            data:function(){
                return{
                    str:''
                }
            },
            template:'<div v-html="str"></div>',
            mounted:function(){
                var that = this;
                setInterval(function(){
                    var beginTime = that.beginTime;
                    if(beginTime){
                        if(typeof beginTime === 'string'){
                            beginTime = beginTime.replace(/\-/g,'/');
                        }
                        beginTime = new Date(beginTime).getTime();
                        if(beginTime > SERVER_TIME){
                            that.str = '未开始.';
                            return false
                        }
                    }
                    var endTime = that.endTime;
                    if(typeof endTime === 'string'){
                        endTime = endTime.replace(/\-/g,'/');
                    }
                    endTime = new Date(endTime);
                    var nMS = endTime.getTime() - SERVER_TIME;
                    var myD = Math.floor(nMS / (1000 * 60 * 60 * 24));
                    var myH = Math.floor(nMS / (1000 * 60 * 60)) % 24;
                    var myM = Math.floor(nMS / (1000 * 60)) % 60;
                    var myS = Math.floor(nMS / 1000) % 60;
                    var myMS = that.interval <= 100 ? '.' + Math.floor(nMS / 100) % 10 : '';
                    var str = '';
                    if (nMS > 0) {
                        if (myD > 0) str = "剩余：<span><font class='d'>" + myD + "</font>天</span>";
                        str += "<span><font class='h'>" + myH + "</font>小时</span><span><font class='m'>" + myM + "</font>分</span><span><font class='s'>" + myS + myMS + "</font>秒</span>";
                    } else {
                        str = "已结束.";
                    }
                    that.str = str;
                    that.$emit('change',{
                        s:nMS,
                        key:that.cdKey
                    })
                },Number(this.interval))
                
            }
        });
        
        Vue.component('course-cart-num', {
            template:'<div>{{num}}</div>',
            data:function(){
                return{
                    num:null
                }
            },
            mounted:function(){
                var that = this;
                request('/index.aspx?c=course&a=shopcart&action=num',null,function(num){
                    that.num = num
                })
                
            }
        })
        
        /**
         * 对外暴露方法
         */
        window.request = request;
        window.domap = domap;
        window.getIsScrolltolower = getIsScrolltolower;
        window.getUserInfo = getUserInfo;
       
    }

    /**
     * 请求服务器数据
     * @method request
     */
    function request(url,data,fn,type){
        var xhr = new XMLHttpRequest();
        var requestType = data ? 'POST' : 'GET';
        
        xhr.open(requestType, url, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  // 添加http头，发送信息至服务器时内容编码类型
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                switch (type){
                    case "json":
                        typeof fn === 'function' && fn(JSON.parse(xhr.responseText))
                        break;
                    default:
                        typeof fn === 'function' && fn(xhr.responseText)
                        break;
                }
            }
        };
        if(requestType === 'POST'){
            xhr.send(JSON.stringify(data))
        }else{
            xhr.send()
        };
        
    }

    /**
     * 获取服务器时间
     */
    function getServerTime(resolve){
        request('/plus/ajaxs.ashx?a=gettime',null,function(res){
            typeof resolve === 'function' && resolve(res)
        })
        
    };

    /**
     * 遍历对象
     */
    function domap(data,fn){
        if(typeof data === 'object' && data.length){
            for(let i=0;i<data.length;i++){
                typeof fn === 'function' && fn(data[i],i)
            }
        }else{
            return false
        }
    }

    /**
     * 判断是否滚动至最底部
     */
    function getIsScrolltolower(el){
        var isScrolltolower = false;
        if(el.nodeName === 'BODY'){
           
            if(window.scrollY + window.innerHeight >= el.scrollHeight){
                isScrolltolower = true
            }
        }else{
            if(el.scrollTop + el.offsetHeight >= el.scrollHeight){
                isScrolltolower = true
            }
        }

        return isScrolltolower
    }

    /**
     * 获取用户信息
     * @param {Function} 已登录回调函数
     * @param {Function} 未登录回调
     * res 返回用户信息json
     */
    function getUserInfo(resolve,fail){
        request('/plus/ajaxs.ashx?a=checkislogin&json=1',null,function(res){
           
            var islogin = res.islogin === 'true' ? true : false;
            if(islogin){
                typeof resolve === 'function' && resolve(res)
            }else{
                typeof fail === 'function' && fail(res)
            }

        },'json')
    }



})(Vue)

