(function() {
    window.nodeRequire = require;
	window.reportLogInfo ={"ccrName":"","ccrPlayerVersion":"1.5.6","videoDuration":"","actions":[]};
	//更新行为日志内容
	window.updateLogInfo = function(obj){
		var actions = reportLogInfo.actions;
		var obj1 = actions[actions.length -1];
		if(obj.type === "play" && (obj1 &&obj1.type === "play")){
		     //obj1 = actions[actions.length -1];
			obj1.playEnd = obj.playEnd;			
		}else{
			actions.push(obj);
		}		
	}
	//写入日志行为统计
	window.writeFileLog = function(){		
		var writeInfo = JSON.stringify(window.reportLogInfo);		
		var filePath=path;		
		fs.open(filePath,"r+",function(err,fd){
			if(err){
				console.log("打开文件失败");
				return;
			}

			var dirName = filePath+"CCofflinePlayer\\playerLogs\\";
			(fs.existsSync(pathModule.resolve(dirName)) == false) && mkdirs(pathModule.resolve(dirName));
			filePath = dirName+fileName;
			fs.writeFile(filePath,JSON.stringify(reportLogInfo),"utf-8",function(err){
				if(err){
					console.log("当前出现的写入错误");
					return;
				}
				console.log("数据写入成功");
				fs.close(fd,function(e){});
			})
			
			
		})
		
	}
	window.getTime = function(){
		var date= new Date();
		return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"_"+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
	}
	function mkdirs(dirPath){
		if(!fs.existsSync(pathModule.dirname(dirPath))){
			mkdirs(pathModule.dirname(dirPath));
		}
		fs.mkdirSync(dirPath);
	}
    delete window.require;
    delete window.exports;
    delete window.module;
    var remote = nodeRequire('electron').remote;
	var pathModule = nodeRequire("path");
    var ipcRenderer = nodeRequire('electron').ipcRenderer;
	var path="C:\\Users\\Administrator\\AppData\\Local\\";
	var fileName = "";
	var  fs = nodeRequire('fs');
    var data = null;
    var metajson = null;
	ipcRenderer.on("closeWindow",function(e,msg){		
	
		window.updateLogInfo({"type":"closeWindow","time":getTime()});
		window.writeFileLog();
		
	});
    var video = {
        init: function() {
            this.loadScripts([
                "./js/jquery-3.1.0.js",
                "./js/H5ClientVideo.js",
                './js/handlebars-v4.0.5.js',
                './js/cc.callback.qa.js',
                './js/cc.callback.chat.js',
                './js/cc.offline.dp.js'
            ], function() {
                video.loadSucc();
            });
        },
        loadSucc: function() {			
            data = JSON.parse(ipcRenderer.sendSync('getZipData'));
			var date = new Date();
			var urls = data.path.split("\\");
			urls.pop();			
			path = urls.join("\\")+"\\";			
			fileName = data.name+"_"+data.pid+"_"+date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+"_"+date.getHours()+"-"+date.getMinutes()+"-"+date.getSeconds()+"_"+date.getTime()+".json";
            H5ClientVideo.init('main-video');
			fs.exists(data.path + "/" + data.name + "/c.mp4",function(exists){
				if(exists){
					H5ClientVideo.play(data.path + "/" + data.name + "/c.mp4");
				}else{
					H5ClientVideo.play(data.path + "/" + data.name + "/c");
				}
			})         
            meta.init();
        },
        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);
        },
    };
    var meta = {
        init: function() {
            metajson = JSON.parse(data.meta);
			window.reportLogInfo.ccrName = data.name;
			if(!metajson.datas.recordId){
				
				
			}else{
				window.reportLogInfo.recordId = metajson.datas.recordId;
			}
			//window.reportLogInfo.roomid = metajson.datas.room.encryptId;
			window.writeFileLog();
            document.title = "CCR播放器";
            UI.init();
        }
    };
    //ui层
    var UI = {
        //计时器id
        intervalId: -1,
        //聊天列表
        chat_list: null,
        //聊天模板
        chat_list_tpl: null,
        //聊天模板
        chat_list_tpl_compile: null,
        //问答列表
        question_list: null,
        //提问模板
        question_ask_tpl: null,
        //提问编译模板
        question_ask_tpl_compile: null,
        //回答模板
        question_answer_tpl: null,
        //回答编译模板
        question_answer_tpl_compile: null,
        init: function() {
            switch (metajson.datas.template.type) {
                case 1:

                    break;
                case 2:
                    // 提问
                    window.qa(metajson.datas.meta);
                    //聊天
                    UI.chat_list = $('#chat-list');
                    UI.chat_list_tpl = $('#chatMsgTemplate').html();
                    UI.chat_list_tpl_compile = Handlebars.compile(UI.chat_list_tpl);
                    break;
                case 3:
                    UI.chat_list = $('#chat-list');
                    UI.chat_list_tpl = $('#chatMsgTemplate').html();
                    UI.chat_list_tpl_compile = Handlebars.compile(UI.chat_list_tpl);
                    break;
                case 4:
                    UI.chat_list = $('#chat-list');
                    UI.chat_list_tpl = $('#chatMsgTemplate').html();
                    UI.chat_list_tpl_compile = Handlebars.compile(UI.chat_list_tpl);

                    // 画板数据
                    UI.DP = new DrawPanel('drawPanel', data.path + "/" + data.name);
                    var pageChanges = metajson.datas.meta.pageChange || [];
                    pageChanges.sort(function (p1, p2) {
                        return parseInt(p1.time) - parseInt(p2.time);
                    });

                    UI.PAGE_CHANGES = {
                        currentIndex: -1,
                        pages: pageChanges,
                        hasNext: function() {
                            return (this.currentIndex + 1) < this.pages.length;
                        },
                        current: function(currentTime) {
                            var p = undefined;

                            this.currentIndex = -1;
                            var cI = -1;
                            $.each(this.pages, function(index, page) {
                                if (page.time <= currentTime) {
                                    p = page;
                                    cI = index;
                                }
                            });
                            this.currentIndex = cI;

                            return p;
                        },
                        next: function(currentTime) {
                            var p = undefined;

                            if (!this.hasNext()) {
                                return p;
                            }

                            if (this.pages[this.currentIndex + 1].time <= currentTime) {
                                p = this.pages[this.currentIndex + 1];
                                this.currentIndex = this.currentIndex + 1;
                            }

                            return p;
                        }
                    };
                    var draws = metajson.datas.meta.draw || [];
                    draws.sort(function (p1, p2) {
                        return parseInt(p1.time) - parseInt(p2.time);
                    });
                    UI.PAGECHANGES_DRAWS = {
                        draws: draws,
                        currentIndex: -1,
                        hasNext: function() {
                            return (this.currentIndex + 1) < this.draws.length;
                        },
                        nexts: function(currentTime) {
                            var ds = [];
                            if (!this.hasNext()) {
                                return ds;
                            }

                            var d = this.draws[this.currentIndex + 1];
                            while (d.time <= currentTime) {
                                ds.push(d);
                                this.currentIndex = this.currentIndex + 1;
                                if (!this.hasNext()) {
                                    break;
                                }
                                d = this.draws[this.currentIndex + 1];
                            }
                            return ds;
                        }
                    };
                    break;
                case 5:
                    window.qa(metajson.datas.meta);
                    //聊天
                    UI.chat_list = $('#chat-list');
                    UI.chat_list_tpl = $('#chatMsgTemplate').html();
                    UI.chat_list_tpl_compile = Handlebars.compile(UI.chat_list_tpl);

                    // 画板数据
                    UI.DP = new DrawPanel('drawPanel', data.path + "/" + data.name);
                    var pageChanges = metajson.datas.meta.pageChange || [];
                    pageChanges.sort(function (p1, p2) {
                        return parseInt(p1.time) - parseInt(p2.time);
                    });
                    UI.PAGE_CHANGES = {
                        currentIndex: -1,
                        pages: pageChanges,
                        hasNext: function() {
                            return (this.currentIndex + 1) < this.pages.length;
                        },
                        current: function(currentTime) {
                            var p = undefined;

                            this.currentIndex = -1;
                            var cI = -1;
                            $.each(this.pages, function(index, page) {
                                if (page.time <= currentTime) {
                                    p = page;
                                    cI = index;
                                }
                            });
                            this.currentIndex = cI;

                            return p;
                        },
                        next: function(currentTime) {
                            var p = undefined;

                            if (!this.hasNext()) {
                                return p;
                            }

                            if (this.pages[this.currentIndex + 1].time <= currentTime) {
                                p = this.pages[this.currentIndex + 1];
                                this.currentIndex = this.currentIndex + 1;
                            }

                            return p;
                        }
                    };
                    var draws = metajson.datas.meta.draw || [];
                    draws.sort(function (p1, p2) {
                        return parseInt(p1.time) - parseInt(p2.time);
                    });
                    UI.PAGECHANGES_DRAWS = {
                        draws: draws,
                        currentIndex: -1,
                        hasNext: function() {
                            return (this.currentIndex + 1) < this.draws.length;
                        },
                        nexts: function(currentTime) {
                            var ds = [];
                            if (!this.hasNext()) {
                                return ds;
                            }

                            var d = this.draws[this.currentIndex + 1];
                            while (d.time <= currentTime) {
                                ds.push(d);
                                this.currentIndex = this.currentIndex + 1;
                                if (!this.hasNext()) {
                                    break;
                                }
                                d = this.draws[this.currentIndex + 1];
                            }
                            return ds;
                        }
                    };

                    break;
                case 6:
                    window.qa(metajson.datas.meta);
                    //聊天
                    break;
            }

            intervalId = setInterval(UI.runTime, 500);

            if (UI.DP) {
                $('#videoDiv video')[0].addEventListener("seeked", function(e) {
                    UI.DP.clearCache();

                    UI.PAGE_CHANGES.currentIndex = -1;
                    UI.PAGECHANGES_DRAWS.currentIndex = -1;

                    var currentTime = parseInt(H5ClientVideo.position(), 10);

                    var pc = UI.PAGE_CHANGES.current(currentTime);
                    if (pc) {
                        UI.DP.flip(JSON.stringify({
                            "fileName": pc.docName,
                            "totalPage": pc.docTotalPage,
                            "docid": pc.encryptDocId,
                            "url": pc.url,
                            "page": pc.pageNum,
                            "useSDK": pc.useSDK
                        }));
                    }

                    var ds = UI.PAGECHANGES_DRAWS.nexts(currentTime);
                    $.each(ds, function(index, d) {
                        UI.DP.draw(d.data);
                    });

                    UI.DP_SEEKING = false;
                }, false);

                // 当用户开始移动/跳跃到音频/视频中的新位置时触发
                $('#videoDiv video')[0].addEventListener("seeking", function(e) {
                    UI.DP_SEEKING = true;
                }, false);

                // 直播结束回调
                $('#videoDiv video')[0].addEventListener("ended", function(e) {
                    UI.PAGE_CHANGES.currentIndex = -1;
                    UI.PAGECHANGES_DRAWS.currentIndex = -1;
                    UI.VIDEO_END = true;
                }, false);

                initDP();
            }

            initBtnSwitch();

        },
        runTime: function() {
            if (UI.chat_list != null) {
                let chatOpen = true;
                while (chatOpen) {
                    var cl = metajson.datas.meta.chatLog[0];
                    if (cl && cl.time <= H5ClientVideo.position()) {
                        let tempO = metajson.datas.meta.chatLog.shift();
                        chat(tempO);
                    } else {
                        chatOpen = false;
                    }
                }
            }

            if (UI.DP) {
                // 直播播放结束
                if ($('#videoDiv video')[0].ended) {
                    return;
                }

                if (UI.VIDEO_END) {
                    UI.DP.clearCache();
                    UI.VIDEO_END = false;
                }

                var currentTime = parseInt(H5ClientVideo.position(), 10);
                if (currentTime < 0) {
                    return;
                }

                if (UI.DP_SEEKING) {
                    return;
                }

                var pc = UI.PAGE_CHANGES.next(currentTime);
                if (pc) {
                    UI.DP.flip(JSON.stringify({
                        "fileName": pc.docName,
                        "totalPage": pc.docTotalPage,
                        "docid": pc.encryptDocId,
                        "url": pc.url,
                        "page": pc.pageNum,
                        "useSDK": pc.useSDK
                    }));
                }

                var ds = UI.PAGECHANGES_DRAWS.nexts(currentTime);
                $.each(ds, function(index, d) {
                    UI.DP.draw(d.data);
                });
            }
        }
    };
	var lastW= -1;
    window.onload = function() {
        video.init();
		setInterval(function(){
			dpCenter();			
		},300);
		
    };

    function initBtnSwitch() {
		$(window).resize(function () {
			if ($('#doc-main').attr('data-module') === '0') {
				var w = $('#video-middle').width(),
					h = $('#video-middle').height() - 80;
				$('#widget-video').css({
					'width': w,
					'height': h
				})
				//console.log('resize')
			}
		});
        $('#btn-switch').bind('click', function() {
            if ($('#widget-video').is(':animated')) {
                return false;
            }
            var video = $('#widget-video'),
                videoWidth = video.width(),
                videoHeight = video.height(),
                videoLeft = video.css('left'),
                videoRight = video.css('right'),
                videoZindex = video.css('z-index'),
                ppt = $('#doc-main'),
                pptWidth = $('#video-middle').width(),
                pptHeight = ppt.height(),
                pptLeft = $('#video-middle').css('left'),
                pptRight = $('#video-middle').css('right'),
                pptZindex = parseInt($('#video-middle').css('z-index')) + 1,
                winMain = ppt.attr('data-module'),
                pptStyle, videoStyle, _width, _height;

            if (winMain == 1) {
                videoLeft = (videoLeft == 'auto' || videoLeft == '0px') ? '-270px' : videoLeft;
                pptStyle = {
                    'width': videoWidth,
                    'height': videoHeight,
                    'left': videoLeft,
                    'right': videoRight,
                    'z-index': videoZindex
                };
                videoStyle = {
                    'width': pptWidth,
                    'height': pptHeight,
                    'left': pptLeft,
                    'right': pptRight,
                    'z-index': pptZindex
                };

                if ($.support.opacity) {
					video.fadeOut(400, function () {
						video.css(videoStyle).show();
						dpCenter();
					});

					ppt.fadeOut(400, function () {
						ppt.css(pptStyle).show();
						dpCenter();
					});
				} else {
					video.css(videoStyle);
					ppt.css(pptStyle);
				}
                ppt.attr('data-module', '0');
                $('#full-ppt').fadeOut(0, function() {
                    $('#full-vod').fadeIn();
                });
            } else {
                pptLeft = (pptLeft == '270px') ? '0' : pptLeft;
                pptWidth = 'auto';
                videoLeft = (videoLeft == '270px') ? '0' : videoLeft;

                pptStyle = {
                    'width': videoWidth,
                    'height': videoHeight,
                    'left': videoLeft,
                    'right': videoRight,
                    'z-index': videoZindex
                };

                videoStyle = {
                    'width': pptWidth,
                    'height': pptHeight,
                    'left': pptLeft,
                    'right': pptRight,
                    'z-index': pptZindex
                };
                
				if ($.support.opacity) {
					video.stop(1, 1).fadeOut(400, function () {
						video.css(videoStyle).removeAttr('style').show();
						dpCenter();
					});
					ppt.stop(1, 1).fadeOut(400, function () {
						ppt.css(pptStyle).removeAttr('style').show();
						dpCenter();
					});
				} else {
					video.css(videoStyle);
					ppt.css(pptStyle);
				}     
    
                ppt.attr('data-module', '1');
                $('#full-vod').fadeOut(0, function() {
                    $('#full-ppt').fadeIn();
                });
            }
			
            if (typeof window.on_cc_live_switch_ppt_video === 'function') {
                window.on_cc_live_switch_ppt_video(winMain);
            }
			
            return false;
        });
    }


	var lastH = 0;
    function dpCenter() {
       	var ph = $('#drawPanel').parent().height();
		if(lastH == ph)return;
		var t = $('#drawPanel').parent().height() - $('#drawPanel').height();
			if (t < 0) {
				t = 0;
			}
			$('#drawPanel').css({'margin-top':t / 2});
		lastH = ph;			
    }

    function initDP() {
        window.VIDEO_DEFALUT = false;
        window.on_cc_live_switch_ppt_video = function(winMain) {
            if (winMain == '1') { // 视频为主
                window.VIDEO_DEFALUT = true;
                $('#fullscreen-btn').css('right', '970px');

                $('#drawPanel').attr({
                    width: $('#drawPanel').attr('width') / 3,
                    height: $('#drawPanel').attr('height') / 3
                });

            } else {
                window.VIDEO_DEFALUT = false;

                if ($('#video-right').length) {
                    $('#fullscreen-btn').css('right', '300px');
                } else {
                    $('#fullscreen-btn').css('right', '30px');
                }

                $('#drawPanel').attr({
                    width: $('#drawPanel').attr('width') * 3,
                    height: $('#drawPanel').attr('height') * 3
                });
            }

            UI.DP.reflip();

            dpCenter();
        };

        $('#video-middle').mouseenter(function() {
            $('#fullscreen-btn').show();
        });

        $('#fullscreen-btn').mouseenter(function() {
            var s = 'img/big_h.png';
            if ($('#video-middle').hasClass('fullscreen')) {
                s = 'img/small_h.png';
            }

            $('#fullscreen-btn img').attr('src', s);
        });

        $('#fullscreen-btn').mouseleave(function() {
            var s = 'img/big_n.png';
            if ($('#video-middle').hasClass('fullscreen')) {
                s = 'img/small_n.png';
            }

            $('#fullscreen-btn img').attr('src', s);
        });

        $('#fullscreen-btn').click(function() {
            $('#video-middle, #doc-main').toggleClass('fullscreen');

            // 文档最大化
            if ($('#video-middle').hasClass('fullscreen')) {
                $('#fullscreen-btn').css('right', '30px');

                $('#doc-main').css('bottom', '0px');
                $('.l-m-b').hide();
                $('#fullscreen-btn img').attr('src', 'img/small_h.png');

                if (window.VIDEO_DEFALUT) {
                    $('#drawPanel').attr({
                        width: $('#drawPanel').attr('width') * 3,
                        height: $('#drawPanel').attr('height') * 3
                    });

                    UI.DP.reflip();
                }
            } else { // 恢复文档大小
                if (window.VIDEO_DEFALUT) {
                    $('#fullscreen-btn').css('right', '960px');

                    $('#drawPanel').attr({
                        width: $('#drawPanel').attr('width') / 3,
                        height: $('#drawPanel').attr('height') / 3
                    });

                    UI.DP.reflip();
                } else {
                    if ($('#video-right').length) {
                        $('#fullscreen-btn').css('right', '300px');
                    } else {
                        $('#fullscreen-btn').css('right', '30px');
                    }
                }
                $('#doc-main').css('bottom', '80px');
                $('.l-m-b').show();
                $('#fullscreen-btn img').attr('src', 'img/big_h.png');
            }



            dpCenter();
        });

        $('#video-middle').mouseleave(function() {
            $('#fullscreen-btn').hide();
        });
    }
})();