(function() {
    var GV = {
        _elementId: "",
        _init: false,
        //初始方法,用divid赋值
        init: function(elementId) {
            if (!this._init) {
                this._elementId = elementId;
                _this = this;
                //			this.loadScripts(["js/jquery-2.1.0.js"],function(){
                _this.loadSucc();
                this._init = true;
            }
			setInterval(function(){
				if(paused)return;
				window.updateLogInfo({"type":"play","playStart":Math.floor(startTime).toString(),"playEnd":stream.time().toString(),time:getTime()});
				window.writeFileLog();				
				},10000
			)
            //			});
        },
        loadScripts: function(arr, fun) {
            var res;
            if ((arr.constructor) == String) {
                res = [];
                res.push(arr);
            } else {
                res = arr;
            }
            _this = this;
            queue = function(re, cb) {
                _this.loadScript(re.shift(), function() {
                    re.length > 0 ? queue(re, cb) : cb();
                })
            };
            queue(res, fun);

        },
        loadScript: function(src, callback) {
            var readyState = false;
            var script = document.createElement("script");
            script.src = src;
            script.onload = script.onreadystatechange = function() {
                if (!readyState && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) {
                    readyState = true;
                    callback && callback();
                }
            };
            document.body.appendChild(script);
        },
        loadSucc: function() {
            UI.init();
        },
        play: function(s) {
            stream.setUrl(s);
            UI.play();
        },
        position: function() {
            return UI.video.currentTime;
        },
    }
	var  startTime = 0;
	var paused = false;
    var UI = {
        video: "",
        pauseBtn: "",
        playBtn: "",
        progressBar: "",
        progressBarBg: "",
        progressBarDIV: "",
        progressBarLoad: "",
        mainDiv: "",
        // mainDivJ: "",
        bgControl: "",
        message: "",
        _this: "",
        timeTxt: "",
        totalTime: "",
        timeOut: -1,
        soundBtn: "",
        unsoundBtn: "",
        soundPanel: "",
        soundBg: "",
        soundBar: "",
        soundNum: "",
        soundHideTime: "",
        columeNum: 1,
        fullBtn: "",
        isFull: false,
        _pgPointDown: false,
        sdPointDownX: 0,
        leaveTime: -1,
        init: function() {
            _this = this;
			startTime = 0;
			paused = false;
            this.importCss();
            // this.mainDiv = document.getElementById(GV._elementId);
            this.mainDiv = $('#' + GV._elementId)
            this.mainDiv.html(this.getDivHtml());
            this.playBtn = $(".playBtn")[0];
            this.pauseBtn = $(".pauseBtn")[0];
            this.video = $(".gvideo")[0];
            this.progressBarBg = $(".progressBg")[0];
            this.timeTxt = $(".timeTxt")[0];
            this.message = $(".messageTxt")[0];
            this.progressBar = $(".progressPlay")[0];
            this.soundBtn = $(".sound")[0];
            this.unsoundBtn = $(".unsound")[0];
            this.soundPanel = $(".soundPanel")[0];
            this.soundBg = $(".soundBg")[0];
            this.soundBar = $(".soundBar")[0];
            //			this.soundNum=$(".soundNum")[0];
            this.fullBtn = $(".fullBtn")[0];
			this.isFirstPlay=true;
            this.video.addEventListener('loadedmetadata', this.metadataFun, false);
            stream.init();
        },
        getDivHtml: function() {
            return "<div class='videoDiv' id='videoDiv'>" +
                " <video class='gvideo'></video>" +
                " <div class='videoControl'>" +
                "    <div class='btnDiv'>" +
                "    	<div class='playBtn'></div>" +
                "    	<div class='pauseBtn'></div>" +
                "    </div>" +
                "    <div class='progressDiv'>" +
                "       <div class='progressBg'></div>" +
                "       <div class='progressLoad'></div>" +
                "       <div class='progressPlay'></div>" +
                "       <div class='progressPoint'></div>" +
                "    </div>" +
                "    <div class='timeTip'></div>" +
                "<div class='timeTxt'>00:00/00:00</div>" +
                "    <div class='settingDiv'>" +
                "          <div class='fullBtn'></div>" +
                "          <div class='soundPanel'>" +
                "          		<div class='soundBg'></div>" +
                "              <div class='soundBar'></div>" +
                "              <div class='soundBarPoint'></div>" +
                "          </div>" +
                "          <div class='sound'></div>" +
                "          <div class='unsound'></div>" +
                "          <div class='playbackRate'>常速</div>" +
                "          <div class='playbackRatePanel'></div>" +
                "    </div>" +
                " </div>" +
                "<div class='messageTxt'>加载中...</div>" +
                "</div>"

        },
        importCss: function() {
            var links = document.createElement("link");
            links.href = "./css/gv.css";
            links.rel = "stylesheet";
            document.head.appendChild(links);
        },
        play: function() {
            stream.play();
			window.updateLogInfo({"type":"play","playStart":Math.floor(startTime).toString(),"playEnd":stream.time().toString(),time:getTime()});
			window.writeFileLog();
            _this.playBtn.style.display = "none";
            UI.pauseBtn.style.display = "block";
        },
        pause: function() {
			window.updateLogInfo({"type":"play","playStart":Math.floor(startTime).toString(),"playEnd":stream.time().toString(),time:getTime()});
			startTime = stream.time();			
            stream.pause();
			window.updateLogInfo({"type":"pause","pauseTime":stream.time().toString(),"time":getTime()});
			//window.updateLogInfo({"type":"playState","playStart":"0","playEnd":stream.time().toString(),time:getTime()});
			window.writeFileLog();
            _this.playBtn.style.display = "block";
            UI.pauseBtn.style.display = "none";
        },
        addEvent: function() {
            this.playBtn.addEventListener("click", this.play);
            this.video.addEventListener("timeupdate", this.timeupdate)
                // this.video.addEventListener('click', this.pause);
            this.pauseBtn.addEventListener("click", this.pause)
            this.video.addEventListener('error', this.errorFun, false);
            this.video.addEventListener('play', this.playFun, false);
            this.video.addEventListener('timeupdate', this.timeUpFun, false)
            this.video.addEventListener('ended', this.endFun, false)
            this.video.addEventListener('progress', this.progress, false)
            this.video.addEventListener('seeking', this.seeking);
            this.video.addEventListener('seeked', this.seeked);
            this.progressBarBg.addEventListener("click", this.seek);
            this.progressBar.addEventListener("click", this.seek);
            $('.playbackRate').mouseover(this.showRatePanel);
            $('.playbackRatePanel').mouseover(this.showRatePanel);
            $('.playbackRate').mouseout(this.hideRatePanel);
            $('.playbackRatePanel').mouseout(this.hideRatePanel);
            $('.progressDiv').mouseover(this.showTimeTip);
            $('.progressDiv').mousemove(this.showTimeTip);
            $('.progressDiv').mouseout(this.hideTimeTip);
            $('.progressPoint').mousedown(this.pgPointDown);
            $('.soundPanel').mouseover(this.sdPointShow);
            $('.soundPanel').mouseout(this.sdPointHide);
            $('.soundBarPoint').mousedown(this.sdPointDown);
            // $('.progressPoint').mouseup(this.pgPointUp);
            // $('.progressPoint').mouseout(this.pgPointUp);
            this.soundBg.addEventListener('click', this.getVolumeNum);
            this.soundBar.addEventListener('click', this.getVolumeNum);
            this.soundBtn.addEventListener('click', this.closeSound);
            this.unsoundBtn.addEventListener('click', this.openSound);
            this.fullBtn.addEventListener('click', this.goFullScreen);
            UI.mainDiv.mouseenter(this.enterDiv);
            UI.mainDiv.mouseleave(this.leaveDiv);
            UI.mainDiv.mousemove(this.enterDiv);
            document.oncontextmenu = this.contextmenu;
        },
        enterDiv: function(e) {
            clearTimeout(UI.leaveTime);
            $('.videoControl').css('display', 'block');
            UI.leaveTime = setTimeout(function() {
                $('.videoControl').css('display', 'none');
            }, 3000);
        },
        leaveDiv: function(e) {
            UI.leaveTime = setTimeout(function() {
                $('.videoControl').css('display', 'none');
            }, 3000);

        },
        sdPointShow: function(e) {
            $('.soundBarPoint').css('display', 'block');
            $('.soundBarPoint').css('left', $('.soundBar').width() - 4 + "px");
        },
        sdPointHide: function(e) {
            $('.soundBarPoint').css('display', 'none');
        },
        sdPointDown: function(e) {
            UI.sdPointDownX = e.pageX;
            $('.videoDiv').mouseup(UI.sdPointUp);
            UI.mainDiv.mouseleave(UI.sdPointUp);
            $('.videoDiv').mousemove(UI.sdPointMove);

        },
        sdPointUp: function(e) {
            $('.videoDiv').off('mouseup', UI.sdPointUp);
            UI.mainDiv.off('mouseleave', UI.sdPointUp);
            $('.videoDiv').off('mousemove', UI.sdPointMove);
        },
        sdPointMove: function(e) {
            _this.soundBtn.style.display = 'block';
            _this.unsoundBtn.style.display = 'none';
            let vector = e.pageX - UI.sdPointDownX;
            let displacement = (UI.sdPointDownX - $('.soundBar').offset().left + vector);
            console.log(vector, displacement, UI.sdPointDownX - $('.soundBar').offset().left);
            if (displacement < 0) displacement = 0;
            if (displacement > $('.soundBg').width()) displacement = $('.soundBg').width();
            $('.soundBarPoint').css('left', displacement - 4 + "px");
            _this.setVolume(displacement / $(".soundBg").width());
        },
        //进度条的小圆点按下
        pgPointDown: function(e) {
            UI._pgPointDown = true;
            $('#videoDiv').mouseup(UI.pgPointUp);
            UI.mainDiv.mouseleave(UI.pgPointUp);
            UI.mainDiv.mouseup(UI.pgPointUp);
            $('#videoDiv').mouseleave(UI.pgPointUp);
            $('#videoDiv').mousemove(UI.pgPointMove);
        },
        //进度条的小圆点松开
        pgPointUp: function(e) {
            if (!UI._pgPointDown) return;

            console.log("松开了")
            $('#videoDiv').off("mouseup", UI.pgPointUp);
            UI.mainDiv.off("mouseleave", UI.pgPointUp);
            UI.mainDiv.off("mouseup", UI.pgPointUp);
            $('#videoDiv').off("mouseleave", UI.pgPointUp);
            $('#videoDiv').off("mousemove", UI.pgPointMove);
            let time = ($('.progressPoint').offset().left + 5 - (_this.progressBarBg.getBoundingClientRect().left)) / _this.progressBarBg.offsetWidth * _this.video.duration;
            stream.seek(time);
            console.log($('.progressPoint').offset().left, _this.progressBarBg.getBoundingClientRect().left);
            UI._pgPointDown = false;
            UI.hideTimeTip(null);
        },
        pgPointMove: function(e) {
            var Px = e.pageX - $('#videoDiv').offset().left;

            if (Px > _this.progressBarBg.offsetWidth) {
                Px = _this.progressBarBg.offsetWidth;
                UI.pgPointUp(null);
                return;
            }
            let time = (Px) / _this.progressBarBg.offsetWidth * _this.video.duration;
            if (UI._pgPointDown) {
                $('.progressPoint').css('left', Px - 5 + "px");
                UI.progressBar.style.width = (time / UI.video.duration) * 100 + "%";
            }
            UI.showTimeTip(e);
        },
        seeking: function(e) {
            UI.showTip(true, '跳转中');
            UI.progressBarBg.removeEventListener("click", UI.seek);
            UI.progressBar.removeEventListener("click", UI.seek);
            $('.progressPoint').off("mousedown", this.pgPointDown);
        },
        seeked: function(e) {
            UI.showTip(true, '跳转完成');			
			window.updateLogInfo({"type":"seek","seekStart":Math.floor(startTime).toString(),"seekEnd":Math.floor(stream.time()).toString(),"time":getTime()});
			window.updateLogInfo({"type":"play","playStart":Math.floor(stream.time()).toString(),"playEnd":Math.floor(stream.time()).toString(),time:getTime()});
			window.writeFileLog();
            UI.progressBarBg.addEventListener("click", UI.seek);
            UI.progressBar.addEventListener("click", UI.seek);
            $('.progressPoint').mousedown(UI.pgPointDown);
        },
        hideTimeTip: function(e) {
            $('.timeTip').css('display', 'none');
            $('.progressPoint').css('display', 'none');
        },
        showTimeTip: function(e) {
            $('.timeTip').css('display', 'block');
            $('.progressPoint').css('display', 'block');
            var Px = e.pageX - $('#videoDiv').offset().left;
            if (Px > $('.timeTip').width() / 2) {
                $('.timeTip').css('left', Px - $('.timeTip').width() / 2 + "px");
            } else {
                $('.timeTip').css('left', "0px");
            }
            if (Px + $('.timeTip').width() / 2 > $('body').width()) {
                $('.timeTip').css('left', $('body').width() - $('.timeTip').width() + "px");
            }

            var time = (e.pageX - (_this.progressBarBg.getBoundingClientRect().left)) / _this.progressBarBg.offsetWidth * _this.video.duration;

            var timeS = ""
            if (time / 60 >= 10) {
                timeS = parseInt(time / 60) + ":";
            } else {
                timeS = "0" + parseInt(time / 60) + ":";
            }

            if (time % 60 >= 10) {
                timeS += parseInt(time % 60);
            } else {
                timeS += "0" + parseInt(time % 60);
            }
            $('.timeTip').html(timeS)
        },
        showRatePanel: function(e) {
            if ($('.playbackRatePanel').css('display') == 'block') return;
            $('.playbackRatePanel').empty();
            $('.playbackRatePanel').css('display', 'block');
            UI.showRateEle();
            $('.playbackRatePanelele').click(UI.selectRate);
        },
        selectRate: function(e) {
            stream.setPlaybackRate($('.playbackRatePanelele:contains(' + e.currentTarget.innerHTML + ')').attr('datanum'));
            $('.playbackRate').html($('.playbackRatePanelele:contains(' + e.currentTarget.innerHTML + ')').html());
            _this.showTip(true, "已经切换为" + $('.playbackRatePanelele:contains(' + e.currentTarget.innerHTML + ')').html());
            $('.playbackRatePanel').css('display', 'none');
        },
        hideRatePanel: function(e) {
            $('.playbackRatePanel').css('display', 'none');
            $('.playbackRatePanelele').off();

        },
        showRateEle: function() {
            $('.playbackRatePanel').append($('<div class="playbackRatePanelele" datanum="2">2.0X</div>'));
            $('.playbackRatePanel').append($('<div class="playbackRatePanelele" datanum="1.5">1.5X</div>'));
            $('.playbackRatePanel').append($('<div class="playbackRatePanelele" datanum="1.25">1.25X</div>'));
            $('.playbackRatePanel').append($('<div class="playbackRatePanelele" datanum="1">常速</div>'));
            $('.playbackRatePanel').append($('<div class="playbackRatePanelele" datanum="0.75">0.75X</div>'));
            $('.playbackRatePanel').append($('<div class="playbackRatePanelele" datanum="0.5">0.5X</div>'));
        },
        contextmenu: function(e) {
            if (e.target.className == 'gvideo')
                return false;
        },
        goFullScreen: function() {
            if (!_this.isFull)
                $("#videoDiv")[0].className = "fullScreen";
            else
                $("#videoDiv")[0].className = "videoDiv";
            _this.isFull = !_this.isFull;

        },
        closeSound: function(e) {
            var _volnum = _this.columeNum;
            _this.setVolume(0);
            _this.columeNum = _volnum;
            _this.soundBtn.style.display = 'none';
            _this.unsoundBtn.style.display = 'block';
        },
        openSound: function(e) {
            _this.setVolume(_this.columeNum);
            _this.soundBtn.style.display = 'block';
            _this.unsoundBtn.style.display = 'none';
        },
        //根据鼠标点计算音量
        getVolumeNum: function(e) {
            console.log($(".soundBg").offset().left, e.pageX);
            _this.soundBtn.style.display = 'block';
            _this.unsoundBtn.style.display = 'none';
            _this.setVolume(((e.pageX - $(".soundBg").offset().left)) / $(".soundBg").width())
            UI.sdPointShow();
        },
        soundPs: function() {
            _this.soundPanel.style.display = "block"
            clearTimeout(_this.soundHideTime);
        },
        soundPh: function() {
            _this.soundHideTime = setTimeout(function() {
                _this.soundPanel.style.display = "none"
            }, 1000)

        },
        ///设置声音
        setVolume: function(num) {
            if (num > 1) num = num / 100;
            _this.soundBar.style.width = parseInt($(".soundBg").width() * num) + "px";
            //			_this.soundNum.innerHTML=parseInt(100*num)+"";
            _this.columeNum = parseInt(100 * num);
            stream.setVolume(_this.columeNum);
        },
        seek: function(e) {
            var time = "";
            time = (e.pageX - (_this.progressBarBg.getBoundingClientRect().left)) / _this.progressBarBg.offsetWidth * _this.video.duration;
            stream.seek(time);
            UI.progressBar.style.width = (time / UI.video.duration) * 100 + "%";
        },
        timeupdate: function() {

            // console.log(UI.video.buffered.end(0), UI.video.buffered.start(0))
            if (!UI._pgPointDown) {
                UI.progressBar.style.width = (UI.video.currentTime / UI.video.duration) * 100 + "%";
                $('.progressPoint').css('left', $('.progressPlay').width() - 5 + "px")
            }
            var time = "";
            if (_this.video.currentTime / 60 >= 10) {
                time = parseInt(_this.video.currentTime / 60) + ":";
            } else {
                time = "0" + parseInt(_this.video.currentTime / 60) + ":";
            }

            if (_this.video.currentTime % 60 >= 10) {
                time += parseInt(_this.video.currentTime % 60);
            } else {
                time += "0" + parseInt(_this.video.currentTime % 60);
            }
            _this.timeTxt.innerHTML = time + "/" + totalTime;
        },
        progress: function() {

        },
        endFun: function() {
            UI.showTip(true, '播放结束');
			paused = true;
			window.updateLogInfo({"type":"play","playStart":Math.floor(startTime).toString(),"playEnd":stream.time().toString(),time:getTime()});
			window.writeFileLog();
            _this.playBtn.style.display = "block";
            UI.pauseBtn.style.display = "none";
        },
        metadataFun: function() {
            // _this.showTip(true, "读取数据成功,进入对接通道");
            _this.addEvent();
			window.reportLogInfo.videoDuration=_this.video.duration.toString();
            if (_this.video.duration / 60 >= 10) {

                totalTime = parseInt(_this.video.duration / 60) + ":";
            } else {
                totalTime = "0" + parseInt(_this.video.duration / 60) + ":";
            }

            if (_this.video.duration % 60 >= 10) {
                totalTime += parseInt(_this.video.duration % 60);
            } else {
                totalTime += "0" + parseInt(_this.video.duration % 60);
            }
            _this.timeTxt.innerHTML = "00:00/" + totalTime;
        },
        playFun: function() {
			window.updateLogInfo({"type":"play","playStart":"0","playEnd":stream.time().toString(),time:getTime()});
			window.writeFileLog();
            UI.showTip(false)
        },
        errorFun: function(e) {
			UI.showTip(true, '出错');
        },
        showTip: function(b, m) {
            clearTimeout(_this.timeOut);
            if (b) {
                _this.message.innerHTML = m;
                _this.timeOut = setTimeout(_this.showTip, 2000, false);
            } else {
                _this.message.innerHTML = "";
            }
        },
        initialize: function() {
            UI.progressBar.style.width = '0%';
            UI.playBtn.style.display = "block";
            UI.pauseBtn.style.display = "none";
            $('.playbackRate').html('常速');
        }
    }	

    //详细的流处理
    var stream = {

        init: function() {
            UI.addEvent();

        },
        setUrl: function(s) {
			console.log('当前的播放地址是-->'+s);
            UI.initialize();
            UI.video.src = s;
        },
        play: function() {
			paused = false;
            UI.video.play();
        },
		time:function(){
			return Math.floor(UI.video.currentTime);
		},
        pause: function() {
			paused = true;
            UI.video.pause();
        },
        seek: function(time) {
			window.updateLogInfo({"type":"play","playStart":Math.floor(startTime).toString(),"playEnd":Math.floor(this.time()).toString(),time:getTime()});
			startTime = this.time();			
            UI.video.currentTime = (time);
        },
        setVolume: function(num) {
            UI.video.volume = num / 100;
        },
        //倍速播放
        setPlaybackRate: function(num) {
            return UI.video.playbackRate = num;
        }
    }
    window.H5ClientVideo = GV;
})(window)