Greasy Fork is available in English.

acfun直播弹幕

acfun直播弹幕。

Pada tanggal 2020-12-18 08:20:24 UTC. Lihat %(latest_version_link).

// ==UserScript==
// @name     acfun直播弹幕
// @description acfun直播弹幕。
// @namespace syachiku
// @author       syachiku
// @match        https://live.acfun.cn/live/*
// @run-at document-end
// @grant   GM_addStyle
// @grant GM_getResourceURL
// @grant   GM_xmlhttpRequest
// @grant       GM_getValue
// @grant       GM_setValue
// @version  1.2.2.5
// @require https://cdnjs.cloudflare.com/ajax/libs/qs/6.9.4/qs.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.1/uuid.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/clipboard-polyfill/3.0.1/promise/clipboard-polyfill.promise.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.12/vue.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/element-ui/2.14.1/index.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.2.0/exceljs.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/keymaster/1.6.1/keymaster.min.js
// ==/UserScript==



;(async function(){

	const css = `
		/* base html */
		#header,#footer,
		.main>.list-container.outer-wrapper,
		.main>.list-container.outer-wrapper:before,
		.container-live>.left,
		.live-feed-watching,
		.container-live-feed-messages:before
		{display:none!important}
		#app>.main,
		.player-outer-wrapper,
		.player-outer-wrapper>.container-live,
		.player-outer-wrapper>.container-live>.container-live-feed.right,
		.player-outer-wrapper>.container-live>.container-live-feed.right>.live-feed,
		.player-outer-wrapper>.container-live>.container-live-feed.right>.live-feed>.container-live-feed-messages,
		.player-outer-wrapper>.container-live>.container-live-feed.right>.live-feed>.container-live-feed-messages>.live-feed-messages
		{
		display:block!important;
		position:fixed!important;
		width:100%!important;
		height:100%!important;
		margin:0!important;
		padding:0!important;
		border:0!important;
		top:0!important;
		bottom:0!important;
		word-break:break-all!important;
		}
		.player-outer-wrapper>.container-live>.container-live-feed.right>.live-feed>.container-live-feed-messages{background:#0c0!important;}
		.player-outer-wrapper>.container-live>.container-live-feed.right>.live-feed>.container-live-feed-messages>.live-feed-messages{height:calc(100% - 5px)!important}
		/* danmu */
		.live-feed-messages>div{
		height:auto!important;
		line-height:30px!important;
		font-size:120%!important;
		font-weight:900!important;
		margin-left:5px!important;
		font-family:Microsoft Yahei!important;
		margin-bottom:3px!important;
		}
		.container-live-feed-messages .live-feed-messages>div>div{
		text-shadow: 0px 2px 2px #000, 0px -2px 2px #000, 2px 0px 2px #000, -2px 0px 2px #000, 2px 2px 2px #000, -2px -2px 2px #000, 2px -2px 2px #000, -2px 2px 2px #000!important;
		padding:1px 5px 1px 1px!important;max-width:unset!important;
		}
		.container-live-feed-messages .live-feed-messages>div>div>:nth-child(1){color:#b6d9fa!important}
		.container-live-feed-messages .live-feed-messages>div>div>:nth-child(2){color:#fff!important}
		.container-live-feed-messages .live-feed-messages>div>div>.nickname{text-overflow:unset!important;overflow:visible!important;max-width:unset!important;}
		.container-live-feed-messages .live-feed-messages>:not(.comment)>div>:nth-child(2){color:#ddd!important}
		.container-live-feed-messages .live-feed-messages>:not(.comment)>div>span:nth-child(1){margin-right:10px!important;}
		.container-live-feed-messages .live-feed-messages>.comment{padding:1px 0px 1px 0px!important;margin:0 0 -5px 0px!important}
		.container-live-feed-messages .live-feed-messages>.comment>div{line-height:24px!important;padding:0px 10px 0px 4px!important;margin:0px 0 0 8px!important}
		.container-live-feed-messages .live-feed-messages>.like{padding:0px 0px 2px 10px!important;}
		.container-live-feed-messages .live-feed-messages>.like>div{padding:2px 18px 2px 10px!important;margin:0 0 0 -12px!important;border-radius:10px!important}
		.container-live-feed-messages .live-feed-messages>.like>div>span:after{padding:0px 5px 0px 5px!important;margin:0px -10px 0 10px!important}
		.container-live-feed-messages .live-feed-messages>.follow>div{height:auto!important;padding:2px 10px 3px 7px!important;margin:3px 0px 4px 0!important}
		.container-live-feed-messages .live-feed-messages>.user-enter>div{height:auto!important;padding:2px 10px 3px 4px!important;margin:3px 0 1px 3px!important;border-radius:10px!important}
		.container-live-feed-messages .live-feed-messages>.gift>div{background:#fedf3b!important;height:auto!important;line-height:25px!important;padding:2px 5px 2px 10px!important;margin:0 0 -5px 0!important;border-radius:10px!important}
		.container-live-feed-messages .live-feed-messages>.gift>div>span:nth-child(2){padding:0px 5px 0px 0px!important;}
		.container-live-feed-messages .live-feed-messages>.gift>div>img{margin:0 0 1px 0!important}

		.container-live-feed-messages .live-feed-messages >div{
			cursor: pointer;
			background-size: 200.22% auto;
			-webkit-background-size: 200.22% auto;
			-moz-background-size: 200.22% auto;
			background-position: 0% 0;
			background-image: linear-gradient(to right, rgba(255, 255, 255, 0) 50%, #1890ff 50%);
			text-decoration: none;
			transition: background-position 0.5s ease-out;
			-webkit-transition: background-position 0.5s ease-out;
		}
		.container-live-feed-messages .live-feed-messages >div:hover{
			background-position: -99.99% 0;
		}
		.container-live-feed-messages .live-feed-messages > :not(.comment) > div > :nth-child(2).nickname{
				color : #b6d9fa !important
		}
		.container-live-feed-messages .live-feed-messages > div > div > :nth-child(2).nickname{
				color : #b6d9fa !important
		}
		.container-live-feed-messages .live-feed-messages > :not(.comment) > div > :nth-child(2){
				color:#fff !important;
		}
		.container-live-feed-messages .live-feed-messages > div.comment > div .comment-text{
				color:#fff !important;
		}
		.container-live-feed-messages .live-feed-messages > div.like > div .like-text{
				color:#fff !important;
		}
		.container-live-feed-messages .live-feed-messages > div.gift > div{
				color : #fff !important;
		}
		.container-live-feed-messages .live-feed-messages > div.user-enter{
			color: #fff !important;
		}
		.container-live-feed-messages .live-feed-messages .vup.vup-user{
				position: relative;
				display: inline-block;
				padding: 0 8px;
				background: #409bef;
				border-radius: 9px;
				color: white !important;
				height: 18px;
				line-height: 18px;
		}
		.live-feed-input{
				display : none !important;
		}


		.live-feed .live-feed-dropmenu{
				display:block;
				position:absolute;
				top : 50px;
				right : 50px;
				z-index : 999999;
		}

		/*.live-feed-input:hover{
				opacity : 1;
		}*/

		@font-face{
			font-family:element-icons;
			src:url('https://cdnjs.cloudflare.com/ajax/libs/element-ui/2.14.1/theme-chalk/fonts/element-icons.ttf');
		}

		.lottery-form-dialog {
			z-index : 999999;
		}

		.lottery-form-dialog .el-dialog__body{
			height : 350px;
			overflow : auto;
		}

		.lottery-form .gift-selector .el-select-dropdown__item{
			height : 40px;
			line-height : 40px;
		}

		.lottery-form .el-divider{
			margin-top : 40px;
		}
		.lottery-form .el-divider .el-divider__text{
			color : #409EFF;
		}
		.lottery-form .douga-list-wrapper{
			overflow:auto;
			height:200px;
		}

		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.video .douga-info{
			height : 100px;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.article .douga-info{
			height : 60px;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item .douga-info .douga-info-right{
			height : 100%;
			display:flex;
			flex-direction:column;
			justify-content:space-between;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item .cover{
			display:inline-block;
			height:100px;
			width:177px;
			line-height:100px;
			border-radius : 4px;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item .cover >img{
			object-fit:cover;
		    display: block;
		    height: 100%;
		    vertical-align: middle;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.video .title{
			height:60px;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 3;
			-webkit-box-orient: vertical;
			font-weight : bold;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.article .title{
			height:40px;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			text-decoration : underline;
			font-weight : bold;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item .el-card:hover{
			background-color : #409effb0;
			cursor:pointer;
			color : white;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.active .el-timeline-item__tail{
			border-left: 2px solid #409EFF;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.active .el-timeline-item__node{
			background-color : #409EFF;
		}
		.lottery-form .douga-list-wrapper .douga-list .douga-list-item.active .el-card{
			color : white;
			background-color : #409eff;
		}

		.lottery-table .lottery-status-finish{
			background: #8aec53;
		}

		.lottery-table-dialog{
			z-index : 999999;
		}

		.lottery-table-dialog .el-dialog__body{
			height : 350px;
			overflow : auto;
		}

		.user-table-dialog{
			z-index : 999999;
		}

		.user-table-dialog .el-dialog__body{
			height : 350px;
			overflow : auto;
		}


		.lottery-countdown-dialog{
			z-index : 999999;
			background-color : rgba(0,0,0,0) !important;
			box-shadow : none !important;
		}
		.lottery-countdown-dialog button[data-setter] {
				outline: none;
				background: transparent;
				border: none;
				font-family: 'Roboto';
				font-weight: 300;
				font-size: 18px;
				width: 25px;
				height: 30px;
				color: #409EFF;
				cursor: pointer;
		}
		.lottery-countdown-dialog button[data-setter]:hover {
				opacity: 0.5;
		}
		.lottery-countdown-dialog .container {
				position: relative;
				top: 30px;
				width: 300px;
				margin: 0 auto;
		}
		.lottery-countdown-dialog .setters {
				position: absolute;
				left: 85px;
				top: 75px;
		}
		.lottery-countdown-dialog .minutes-set {
				float: left;
				margin-right: 28px;
		}
		.lottery-countdown-dialog .seconds-set {
				float: right;
		}
		.lottery-countdown-dialog .controlls {
				position: absolute;
				left: 75px;
				top: 105px;
				text-align: center;
		}
		.lottery-countdown-dialog .display-remain-time {
				font-family: 'Roboto';
				font-weight: bold;
				font-size: 65px;
				color: #409EFF;
		}
		.lottery-countdown-dialog #pause {
				outline: none;
				background: transparent;
				border: none;
				margin-top: 10px;
				width: 50px;
				height: 50px;
				position: relative;
		}
		.lottery-countdown-dialog .play::before {
				display: block;
				content: "";
				position: absolute;
				top: 8px;
				left: 16px;
				border-top: 15px solid transparent;
				border-bottom: 15px solid transparent;
				border-left: 22px solid #409EFF;
		}
		.lottery-countdown-dialog .pause::after {
				content: "";
				position: absolute;
				top: 8px;
				left: 12px;
				width: 15px;
				height: 30px;
				background-color: transparent;
				border-radius: 1px;
				border: 5px solid #409EFF;
				border-top: none;
				border-bottom: none;
		}
		.lottery-countdown-dialog #pause:hover {
				opacity: 0.8;
		}
		.lottery-countdown-dialog .e-c-base {
				fill: none;
				stroke: #B6B6B6;
				stroke-width: 15px;
		}
		.lottery-countdown-dialog .e-c-progress {
				fill: none;
				stroke: #409EFF;
				stroke-width: 15px;
				transition: stroke-dashoffset 0.7s;
		}
		.lottery-countdown-dialog .e-c-pointer {
				fill: #FFF;
				stroke: #409EFF;
				stroke-width: 2px;
		}
		.lottery-countdown-dialog #e-pointer {
				transition: transform 0.7s;
		}

		.lottery-start-dialog{
			z-index : 999999;
		}
		.lottery-start-dialog .el-carousel__item{
			background-color: #99a9bf;
			opacity: 0.75;
			margin: 0;
			display:flex;
			width : 250px;
			justify-content:center;
			align-items:center;
			flex-direction:column;
		}

		.lottery-start-dialog .el-dialog__header{
			display:none;
		}
		.lottery-start-dialog .el-carousel__item.highlight{
			background-color: gold;
		}
		.lottery-start-dialog .el-carousel__item .nickname{
			font-size : 20px;
			color : white;
		}

		.login-form-dialog {
			z-index : 999999;
		}

		.audio-form-dialog {
			z-index : 999999;
		}

		.audio-form-dialog .el-dialog__body{
			height : 350px;
			overflow : auto;
		}

		.interaction-form-dialog {
			z-index : 999999;
		}

		.interaction-form-dialog .el-dialog__body{
			height : 350px;
			overflow : auto;
		}

	`;

	GM_addStyle(css);
	Vue.use(ELEMENT);
	Vue.prototype.$message = ELEMENT.Message;
	var audio = null;



	const config = {
		UID : parseInt(window.location.href.split('/').pop()),
		TOKEN : null,
		SERVER : 'http://47.112.178.125',
		ACFUN_SERVER : 'https://www.acfun.cn',
		ACFUNLIVE_SERVER : 'https://live.acfun.cn',
		URLS : {
			USER : {
				INFO : '/user/info'
			},
			ACFUN_USER : {
				VUP : '/user/acfun_user_info_simplified',
				INFO : '/rest/pc-direct/user/userInfo',
				SPACE : '/u'
			},
			DOUGA : {
				COMMENT : '/rest/pc-direct/comment/list'
			},
			ALICLOUD : {
				NLS : '/alicloud/nls',
				VOICE : '/alicloud/voice',
			},
		},
		RESPONSE : {
			FIELD : {
				STATUS : 'code',
				MSG : 'message',
				DATA : 'data',
			},
			STATUS : {
				SUCCESS : 200,
			}
		}
	};

	// 检查token是否存在
	var token = await GM_getValue("token");
	if(token){
		config.TOKEN = token;
	}


	// 禁止播放视频
	function disableVideos(){
		window.setInterval(function(){
			let videoEles = document.querySelectorAll('video');
			for(let videoEle of videoEles){
				videoEle.src = null;
			}
		}, 500);

	}
	
	// 是否为空
	function isNullOrEmpty(val){
		return _.isUndefined(val) || _.isNull(val) || _.isNaN(val) || (((_.isObject(val) && !_.isDate(val)) || _.isArray(val) || _.isString(val)) && _.isEmpty(val))
	}
	
	// 通用请求
	function commonRequrest(url, method, form, raw, callback, headers){
		var isSuccess = false;
		var data = null;
		if(!headers){
			headers = {};
		}

		if(!raw){

			if(method == 'post'){

				headers['Content-Type'] = 'application/x-www-form-urlencoded';
				if(form){
					form = Qs.stringify(form);
				}

			}

		}

		if(method == 'get' && form){
			form = Qs.stringify(form);
			url += '?' + form;
		}

		// 获取了token
		if(config.TOKEN){
			headers['Authorization'] = `Token ${config.TOKEN}`;
		}

		GM_xmlhttpRequest({
			synchronous : !_.isFunction(callback),
			method : method,
			url : url,
			data : form,
			headers : headers,
			onload : function(res){

				// 200
				if(res.status==200){
					if(raw){
						callback(true, res.responseText);
					}
					else{
						res = JSON.parse(res.responseText);
						isSuccess = res[config.RESPONSE.FIELD.STATUS] == config.RESPONSE.STATUS.SUCCESS;
						data = res[config.RESPONSE.FIELD.DATA];

						if(_.isFunction(callback)){
							callback(isSuccess, data);
						}
					}
				}
				else{
					if(_.isFunction(callback)){
						callback(isSuccess, data);
					}
				}
			},
			onerror : function(){
				if(_.isFunction(callback)){
					callback(isSuccess, data);
				}
			},
			onabort : function(){
				if(_.isFunction(callback)){
					callback(isSuccess, data);
				}
			},
		});
			
		return [isSuccess, data];
	}

	function formatText(text, params){

		for(var key in params){
			text = text.replace(new RegExp('\\$\\{'+ key +'\\}', 'g'), params[key]);
		}	

		return text;
		
	}

	// 播放音频
	function nls(text, voice, speechRate, speechVolume, params, callback){

		if(params){
			text = formatText(text, params);
		}

		var data = {
			text : text,
		};
		if(voice){
			data.voice = voice;
		}
		if(speechRate){
			data.speech_rate = speechRate;
		}
		if(speechVolume){
			data.speech_volume = speechVolume;
		}

		commonRequrest(config.SERVER + config.URLS.ALICLOUD.NLS, 'post', data, null, function(isSuccess, data){

			// 获取失败
			if(!isSuccess){
				return;
			}

			// 播放音频
			audio = new Audio('data:audio/wav;base64,'+data);
			audio.loop = false;
			audio.play().catch(function(){
				Vue.prototype.$message({
					type : 'error',
					message : '您的浏览器不支持语音播放,请更换浏览器如Chrome',
				});
			});

			if(_.isFunction(callback)){
				audio.addEventListener("pause", function () {
					callback();
				});
			}

		});

	}
	
	function addCssResource(url){
		
		commonRequrest(url, 'get', null, true, function(isSuccess, css){
			if(isSuccess){
				GM_addStyle(css);
			}
		})
	}
	
	// 添加element-ui样式
	addCssResource('https://cdnjs.cloudflare.com/ajax/libs/element-ui/2.14.1/theme-chalk/index.min.css');
	

	class CallbackManager{
		constructor(feedback){
			this.callbacks = {};
			this.callbackGroupMapper = {};
		}

		register(group, func, params, first){
			if(!(group in this.callbacks)){
				this.callbacks[group] = [];
			}

			var callback = {
				id : uuid.v4(),
				func : func,
				params : params
			};

			// 添加到最前
			if(first){
				this.callbacks[group].splice(0, 0, callback);
			}
			else{
				this.callbacks[group].push(callback);
			}
			this.callbackGroupMapper[callback.id] = group;

			return callback.id;

		}

		cancel(handler){

			if(!(handler in this.callbackGroupMapper) || !(this.callbackGroupMapper[handler] in this.callbacks)){
				return;
			}

			var findIndex = _.findIndex(this.callbacks[this.callbackGroupMapper[handler]], {id:handler});
			if(findIndex==-1){
				return;
			}

			this.callbacks[this.callbackGroupMapper[handler]].splice(findIndex, 1);
			delete this.callbackGroupMapper[handler];

		}

		feed(group, data){

			if(!(group in this.callbacks)){
				return;
			}



			this.callbacks[group].forEach(function(callback){

				callback.func(data, callback.params);

			});


		}

	}

	var callbackManager = new CallbackManager();

	// 添加vup徽章
	function addVupSign(){
		
		function addBadgeToUser(userEle){
			var badgeNode = document.createElement('span');
			badgeNode.className = 'vup vup-user';
			badgeNode.innerText = 'VUP';
			userEle.parentNode.insertBefore(badgeNode, userEle.parentNode.childNodes[0]);
		}
		
		const acSeriesPattern = /[aA][cC][=号]?\s*(\d+)/;
		function extractAcSeries(text){
			var match = text.match(acSeriesPattern);
			if(match){
				return parseInt(match[match.length-1]);
			}
			else{
				return null;
			}
		}
		const giftPattern = /送出((?<count>\d+)个)?(?<name>.+)/;
		function extractGift(text){
			var match = text.match(giftPattern);
			if(match){
				return {
					name : match.groups.name,
					count : match.groups.count?parseInt(match.groups.count):1,
				};
			}
			else{
				return null;
			}
		}
		
		// 获取vup列表
		commonRequrest(config.SERVER + config.URLS.ACFUN_USER.VUP, 'GET', null, false, function(isSuccess, data){
			// 获取失败
			if(!isSuccess){
				return
			}
			
			var userInfo = {};

			var vupInfo = {};
			data.forEach(function(item){
				vupInfo[item.uid] = item;
			});
			
			// 监听弹幕添加
			var messageContainer = document.querySelector('.live-feed-messages');
			var observer = new MutationObserver(function(mutations, observer){
				
				
				// 遍历改变
				mutations.forEach(function(mutation){
					// 子节点发生变化
					if(mutation.type == 'childList'){
						
						// 遍历新增节点
						mutation.addedNodes.forEach(function(node){
							
							// 获取用户名元素
							var userEle = node.querySelector('.nickname');
							var userName = userEle.innerText;
							var uid = null;
							
							if(userEle && userEle.attributes['data-user-id']){
								uid = parseInt(userEle.attributes['data-user-id'].value);
							}

							var interaction = {
							};
							// 弹幕
							if(node.classList.contains('comment')){
								interaction.type = 'danmaku';
								interaction.content = _.trimStart(node.querySelector('.comment-text').innerText, ':');
							}
							// 送礼
							else if(node.classList.contains('gift')){
								var giftText = userEle.nextElementSibling.innerText;
								var gift = extractGift(giftText);

								interaction.type = 'gift';
								interaction.giftName = gift.name;
								interaction.giftCount = gift.count;
							}
							// 点赞
							else if(node.classList.contains('like')){
								interaction.type = 'like';
							}
							// 进入直播间
							else if(node.classList.contains('user-enter')){
								interaction.type = 'enterroom';
							}
							// 关注了主播
							else if(node.classList.contains('follow')){
								interaction.type = 'follow';
							}

							// 添加点击事件
							node.addEventListener('click', function(event){
								var clickUser = event.target.classList.contains('nickname');
								// 弹幕
								if(interaction.type=='danmaku' && !clickUser){
									// 获取弹幕内容
									var comment = interaction.content;
									var acSeries = extractAcSeries(comment);
									
									// 普通文本
									if(isNullOrEmpty(acSeries)){
										clipboard.writeText(comment);
										Vue.prototype.$message({
											message : '已复制弹幕:' + comment,
											type : 'info',
											duration : 2000,
										});
									}
									// 如果有ac号
									else{
										clipboard.writeText(acSeries);
										Vue.prototype.$message({
											message : '已复制ac号:' + acSeries,
											type : 'info',
											duration : 2000,
										});
									}
									
								}
								// 其他类型
								else{
									clipboard.writeText(userName);
									Vue.prototype.$message({
										message : '已复制用户名:' + userName,
										type : 'info',
										duration : 2000,
									});
									
								}
							});
							// vup
							if(uid in vupInfo){
								addBadgeToUser(userEle);
							}

							if(uid in userInfo){
								callbackManager.feed('message', {
									uid : uid,
									userName : userName,
									photo : userInfo[uid].photo,
									interaction : interaction,
                  					node : node,
								});

							}
							else{
								// 获取用户信息
								commonRequrest(config.ACFUNLIVE_SERVER + config.URLS.ACFUN_USER.INFO + `?userId=${uid}`, 'get', null, true, function(isSuccess, data){

									var photo = null;
									if(data){
										data = JSON.parse(data);
										if(data.result == 0){
											photo = data.profile.headUrl;
										}
									}
									userInfo[uid] = {
										userName : userName,
										photo : photo,
									};

									callbackManager.feed('message', {
										uid : uid,
										userName : userName,
										photo : userInfo[uid].photo,
										interaction : interaction,
                    					node : node,
									});

								});
							}

						});
					}
				});
			});
			observer.observe(messageContainer, {childList:true});
			

		});
	}
	

	// 加载Vue实例
	function loadVue(){
		// 获取礼物列表
		var giftList = [];
		var giftContainerEles = document.querySelectorAll('.item-gift');
		giftContainerEles.forEach(function(giftContainerEle, giftIndex){
			var gift = {
				index : giftIndex,
				id : giftContainerEle.attributes['data-gift-id'].value,
				name : giftContainerEle.querySelector('.name').textContent,
				price : _.parseInt(giftContainerEle.attributes['data-gift-price'].value),
				img : giftContainerEle.querySelector('img').attributes['src'].value,
			};

			// 设置香蕉的价格为0
			if(gift.name == '香蕉'){
				gift.price = 0;
			}

			giftList.push(gift);

		});

		// 无法获取礼物列表
		if(giftList.length==0){
			return;
		}

		// 将礼物按照AC币排序
		giftList = _.sortBy(giftList, ['price', 'index']);

		// 添加悬浮菜单
		// 容器
		var containerEle = document.querySelector('.live-feed');
		// 悬浮菜单元素
		var menuEle = document.createElement('div');
		menuEle.className = 'live-feed-dropmenu';
		menuEle.innerHTML = `
			<el-dropdown trigger="click" @command="handleDropdownMenuClick">
				<span class="el-dropdown-link" style="font-size:32px;">
					<i class="el-icon-menu"></i>
				</span>
				<el-dropdown-menu slot="dropdown">
					<el-dropdown-item icon="el-icon-edit" command="editInteraction">弹幕编辑</el-dropdown-item>
					<el-dropdown-item>
						<el-dropdown trigger="hover" placement="right-start"  trigger="click" @command="handleDropdownMenuClick">
							<span class="el-icon-lollipop">
								直播抽奖<i class="el-icon-arrow-down el-icon--right"></i>
							</span>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item icon="el-icon-circle-plus" command="newLottery">添加抽奖</el-dropdown-item>
								<el-dropdown-item icon="el-icon-info" command="lotteryTable">查看抽奖</el-dropdown-item>
								<el-dropdown-item icon="el-icon-download" command="exportLottery">导出名单</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</el-dropdown-item>
					<el-dropdown-item icon="el-icon-setting" command="audioConfig">语音配置</el-dropdown-item>
					<el-dropdown-item icon="el-icon-notebook-1" command="help">帮助文档</el-dropdown-item>
				</el-dropdown-menu>
			</el-dropdown>

			<el-dialog title="登录" :visible.sync="loginFormDialogVisible" :modal="false" width="550px" custom-class="login-form-dialog">
				<el-form :model="loginFormData" class="login-form" ref="loginForm" :rules="loginFormRules" @submit.native.prevent>
					<el-form-item label="口令" label-width="130px" prop="token">
						<el-input v-model="loginFormData.token" placeholder="请输入口令" autocomplete="off" style="width:100%;" show-password></el-input>
					</el-form-item>
					<el-form-item style="display:flex;justify-content:center;">
						<el-button type="primary" @click="handleLoginFormSubmit">提交</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>

			<el-dialog title="查看抽奖" :visible.sync="lotteryTableDialogVisible" :modal="false" width="550px" custom-class="lottery-table-dialog">
				<el-table :data="lotteryTableData" style="width: 100%" class="lottery-table" :row-class-name="lotteryTableRowClassName">
					<el-table-column prop="name" label="奖品名称" :width="150">
					</el-table-column>
					<el-table-column prop="startTimeText" label="开奖时间" :width="100">
					</el-table-column>
					<el-table-column label="操作" :width="250">
						<template slot-scope="scope">
							<el-button type="text" @click="handleLotteryModify(scope.row)">编辑</el-button>
							<el-button type="text" @click="handleLotteryCopy(scope.row)">复制</el-button>
							<el-button type="text" @click="handleLotteryCandidatesCheck(scope.row)" v-if="scope.row.status == '未开始'">查看候选名单</el-button>
							<el-button type="text" @click="handleLotteryWinnersCheck(scope.row)" v-if="scope.row.status == '已结束'">查看中奖名单</el-button>
						</template>
					</el-table-column>

				</el-table>

			</el-dialog>
			
			<el-dialog :title="lotteryFormDialogTitle" :visible.sync="lotteryFormDialogVisible" :modal="false" width="550px" custom-class="lottery-form-dialog" >
				<el-form :model="lotteryFormData" class="lottery-form" ref="form" :rules="lotteryFormRules" @submit.native.prevent  v-loading="lotteryFormData.loading" :element-loading-text="lotteryFormData.loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
					<el-form-item label="奖品名称" label-width="130px" prop="name">
						<el-input v-model="lotteryFormData.name" autocomplete="off" style="width:100%;"></el-input>
					</el-form-item>
					<el-form-item>
						<el-col :span="11">
							<el-form-item label="中奖人数" label-width="130px" prop="count">
								<el-input-number size="medium" v-model="lotteryFormData.count" :min="1" controls-position="right" style="width:100%;"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="13">
							<el-form-item label="开奖时间" label-width="100px" prop="startTime">
								<el-time-picker v-model="lotteryFormData.startTime" :picker-options="timePickerOptions" style="width:100%;">
								</el-time-picker>
							</el-form-item>
						</el-row>
					</el-form-item>
					<el-form-item>
						<el-col :span="11">
							<el-form-item label="抽奖倒计时(秒)" label-width="130px" prop="countdown">
								<el-input-number size="medium" v-model="lotteryFormData.countdown" :min="0" controls-position="right" style="width:100%;"></el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="13">
							<el-form-item label="互斥抽奖" label-width="100px" prop="mutualLotteryList">
								<el-select v-model="lotteryFormData.mutualLotteryList" multiple placeholder="请选择互斥的抽奖" style="width:100%;">
									<el-option
										:value="lottery.id"
										:label="lottery.name"
										:key="lottery.id"
										v-if="lottery.id != lotteryFormData.id"
										v-for="lottery in lotteryTableData"
									>
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-form-item>
					<!--
					<el-form-item label="抽奖权重" label-width="130px" prop="weight">
						<el-switch v-model="lotteryFormData.weight" active-text="加权" inactive-text="等权">
						</el-switch>
					</el-form-item>
					-->


					<el-form-item label="抽奖来源" label-width="130px" prop="source">
						<el-radio-group v-model="lotteryFormData.source" style="width:100%;">
							<el-radio label="livestream">直播间抽奖</el-radio>
							<el-radio label="douga">稿件抽奖</el-radio>
						</el-radio-group>
					</el-form-item>


					<template v-if="lotteryFormData.source == 'livestream'">

						<el-form-item label="抽奖参与方式" label-width="130px" prop="joinMethod">
							<el-checkbox-group v-model="lotteryFormData.joinMethod" style="width:100%;">
								<el-checkbox label="danmaku">弹幕</el-checkbox>
								<el-checkbox label="gift">礼物</el-checkbox>
								<el-checkbox label="like">点赞</el-checkbox>
							</el-checkbox-group>
						</el-form-item>

						<!-- 弹幕 -->
						<template v-if="lotteryFormData.joinMethod.indexOf('danmaku')!=-1">
							<el-form-item label="抽奖参与关键词" label-width="130px" prop="joinKeyword">
								<el-input v-model="lotteryFormData.joinKeyword" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
							</el-form-item>
						</template>

						<!-- 礼物 -->
						<template v-if="lotteryFormData.joinMethod.indexOf('gift')!=-1">
							<el-form-item label="抽奖参与礼物" label-width="130px" prop="joinGiftList">
								<el-select v-model="lotteryFormData.joinGiftList" multiple placeholder="请选择礼物" popper-class="gift-selector" style="width:100%;">
									<el-option
										:label="gift.name"
										:value="gift.id"
										:key="gift.id"
										v-for="gift in giftList"
									>
										<el-row>
											<el-col :span="8">
												<el-avatar shape="square" :size="40" fit="fill" :src="gift.img" style="background-color:white;"></el-avatar>
											</el-col>
											<el-col :span="6" :offset="4">
												<span>{{gift.name}}</span>
											</el-col>
											<el-col :span="6">
												<span v-if="gift.price>0">({{gift.price}}AC币)</span>
											</el-col>
										</el-row>
									</el-option>
								</el-select>
							</el-form-item>
						</template>
					</template>
					<template v-else-if="lotteryFormData.source == 'douga'">

						<el-form-item label="抽奖稿件类型" label-width="130px" prop="dougaType">
							<el-radio-group v-model="lotteryFormData.dougaType" style="width:100%;" @change="refreshDougaList">
								<el-radio label="video">视频投稿</el-radio>
								<el-radio label="article">文章投稿</el-radio>
							</el-radio-group>
						</el-form-item>

						<!--
						<el-form-item label="抽奖参与方式" label-width="130px" prop="joinMethod">
							<el-checkbox-group v-model="lotteryFormData.joinMethod" style="width:100%;">
								<el-checkbox label="comment">评论</el-checkbox>
								<el-checkbox label="subcomment">楼中楼</el-checkbox>
								<el-checkbox label="floor">指定楼层</el-checkbox>
							</el-checkbox-group>
						</el-form-item>
						 -->

						<el-divider>请选取参与抽奖的稿件</el-divider>

						<el-row class="douga-list-wrapper">
							<el-timeline class="douga-list" v-infinite-scroll="getDougaList" :infinite-scroll-disabled="lotteryFormData.dougaListDisabled">
								<el-timeline-item :class="{'douga-list-item':true,'active':lotteryFormData.dougaListActiveIndex == dougaIndex, 'video':lotteryFormData.dougaType == 'video', 'article' : lotteryFormData.dougaType == 'article'}" :timestamp="douga.uploadDateText" placement="top" v-for="(douga, dougaIndex) in lotteryFormData.dougaList" :key="douga.id">
									<el-card  :title="douga.title" @click.native="handleDougaListItemClick(dougaIndex)">
										<el-row class="douga-info">

											<template v-if="lotteryFormData.dougaType == 'video'">
												<el-col :span="12" class="douga-info-left">
													<span class="cover">
														<img :src="douga.cover" @click.stop="handleDougaListItemDetailClick(dougaIndex)">
													</span>
												</el-col>
												<el-col :span="12"  class="douga-info-right">
													<p class="title"><span>{{douga.title}}</span></p>
													<p class="play-count">播放量:<span>{{douga.playCountText}}</span></p>
												</el-col>
											</template>

											<template v-if="lotteryFormData.dougaType == 'article'">
												<p class="title"><span @click.stop="handleDougaListItemDetailClick(dougaIndex)">{{douga.title}}</span></p>
												<p class="play-count">访问量:<span>{{douga.playCountText}}</span></p>
											</template>

										</el-row>
									</el-card>
								</el-timeline-item>
							</el-timeline>
							
							<p v-if="lotteryFormData.dougaListLoading">...正在加载投稿稿件...</p>
							<p v-if="lotteryFormData.dougaListNoMore">加载完毕</p>
						</el-row>



					</template>

					<el-form-item style="display:flex;justify-content:center;">
						<el-button type="primary" @click="handleLotteryFormSubmit" v-if="">立即创建</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>


			<el-dialog :title="userTableDialogTitle" :visible.sync="userTableDialogVisible" :modal="false" width="550px" custom-class="user-table-dialog">
				<el-table :data="userTableData" style="width: 100%" class="user-table">
					<el-table-column prop="userName" label="用户名" :width="300">
						<template slot-scope="scope">
							<el-avatar shape="circle" fit="fill" size="40" :src="scope.row.photo"></el-avatar>
							<span>{{scope.row.userName}}</span>
						</template>
					</el-table-column>
					<el-table-column prop="uid" label="用户uid" :width="150">
					</el-table-column>
					

				</el-table>

			</el-dialog>

			<el-dialog :visible.sync="lotteryCountdownDialogVisible" :modal="false" width="550px" custom-class="lottery-countdown-dialog" :close-on-click-modal="false" :show-close="false">
				<div class="container">
					 <div class="circle">
							<svg width="300" viewBox="0 0 220 220" xmlns="http://www.w3.org/2000/svg">
								 <g transform="translate(110,110)">
										<circle r="100" class="e-c-base"/>
										<g transform="rotate(-90)">
											 <circle r="100" class="e-c-progress"/>
											 <g id="e-pointer">
													<circle cx="100" cy="0" r="15" class="e-c-pointer"/>
											 </g>
										</g>
								 </g>
							</svg>
					 </div>
					 <div class="controlls">
							<div class="display-remain-time">{{activeLottery.countdownText}}</div>
					 </div>
				</div>
			</el-dialog>
			
			<el-dialog :visible.sync="lotteryStartDialogVisible" :modal="false" width="550px" custom-class="lottery-start-dialog" :close-on-click-modal="false" :destroy-on-close="true" :show-close="false">
				<el-row v-if="activeLottery!=null && activeLottery.name" style="text-align:center;margin-bottom:20px;">
					<p style="font-size:30px;font-weight:bold;">{{activeLottery.name}}</p>
					<p>
						<span>抽奖名额:<span style="color:#409EFF;font-weight:bold;">{{activeLottery.count}}</span>名</span>
						<span style="margin-left:20px;">剩余名额:<span style="color:#409EFF;font-weight:bold;">{{activeLottery.count - activeLottery.winners.length}}</span>名</span>
						<span style="margin-left:20px;">候选人数:<span style="color:#409EFF;font-weight:bold;">{{activeLottery.startCandidates.length}}</span>人</span>
					</p>
				</el-row>
				<el-row class="carousel-container" v-if="activeLottery!=null && activeLottery.name">			
					<el-carousel ref="carousel" type="card" height="200px" indicator-position="none" arrow="never" :autoplay="false">
						<el-carousel-item v-for="candidate in activeLottery.startCandidates" :class="candidate.highlight?'highlight':''">
								<el-row>
									<el-avatar shape="square" :size="120" fit="fill" :src="candidate.photo"></el-avatar>
								</el-row>
								<el-row>
									<span class="nickname">{{candidate.userName}}</span>
								</el-row>
						</el-carousel-item>
					</el-carousel>
				</el-row>
			</el-dialog>


			<el-dialog title="语音配置" :visible.sync="audioFormDialogVisible" :modal="false" width="550px" custom-class="audio-form-dialog">
				<el-form :model="audioFormData" class="audio-form" ref="audioForm" :rules="audioFormRules" @submit.native.prevent>
					
					<el-form-item label="语音" label-width="130px" prop="voice">
						<el-cascader v-model="audioFormData.voice" :options="audioVoiceOptions" style="width:100%;">
						</elcascader>
					</el-form-item>

					<el-form-item label="是否启动" label-width="130px" prop="enable">
						<el-switch v-model="audioFormData.enable" active-text="启动" inactive-text="不启动">
						</el-switch>
					</el-form-item>

					<template v-if="audioFormData.enable">

						<el-form-item label="语音播报" label-width="130px" prop="joinMethod">
							<el-checkbox-group v-model="audioFormData.joinMethod" style="width:100%;">
								<el-checkbox label="danmaku">弹幕</el-checkbox>
								<el-checkbox label="gift">礼物</el-checkbox>
								<el-checkbox label="like">点赞</el-checkbox>
								<el-checkbox label="enterroom">进入直播间</el-checkbox>
								<el-checkbox label="follow">关注</el-checkbox>
							</el-checkbox-group>
						</el-form-item>

						<el-form-item label="语音语速" label-width="130px" prop="speechRate">
							<el-slider v-model="audioFormData.speechRate" :marks="speechRateMarks" :min="0" :max="1000" :step="10" style="width:100%;"></el-slider>
						</el-form-item>

						<el-form-item label="语音音量" label-width="130px" prop="speechVolume">
							<el-slider v-model="audioFormData.speechVolume" :marks="speechVolumeMarks" :min="0" :max="100" :step="5" style="width:100%;"></el-slider>
						</el-form-item>


						<!-- 弹幕 -->
						<template v-if="audioFormData.joinMethod.indexOf('danmaku')!=-1">
							<el-form-item label="弹幕语音" label-width="130px" prop="danmakuFormat">
								<el-input v-model="audioFormData.danmakuFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
							</el-form-item>
						</template>
						<!-- 礼物 -->
						<template v-if="audioFormData.joinMethod.indexOf('gift')!=-1">
							<el-form-item label="礼物语音" label-width="130px" prop="giftFormat">
								<el-input v-model="audioFormData.giftFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
							</el-form-item>
						</template>
						<!-- 点赞 -->
						<template v-if="audioFormData.joinMethod.indexOf('like')!=-1">
							<el-form-item label="点赞语音" label-width="130px" prop="likeFormat">
								<el-input v-model="audioFormData.likeFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
							</el-form-item>
						</template>
						<!-- 进入直播间 -->
						<template v-if="audioFormData.joinMethod.indexOf('enterroom')!=-1">
							<el-form-item label="进入直播间语音" label-width="130px" prop="enterroomFormat">
								<el-input v-model="audioFormData.enterroomFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
							</el-form-item>
						</template>
						<!-- 关注 -->
						<template v-if="audioFormData.joinMethod.indexOf('follow')!=-1">
							<el-form-item label="关注语音" label-width="130px" prop="followFormat">
								<el-input v-model="audioFormData.followFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
							</el-form-item>
						</template>

					</template>


					<el-form-item style="display:flex;justify-content:center;">
						<el-button type="primary" @click="handleAudioFormSubmit">提交</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>


			<el-dialog title="弹幕编辑" :visible.sync="interactionFormDialogVisible" :modal="false" width="550px" custom-class="interaction-form-dialog">
				<el-form :model="interactionFormData" class="interaction-form" ref="interactionForm" :rules="interactionFormRules" @submit.native.prevent>
					

					<el-form-item label="是否启动" label-width="130px" prop="enable">
						<el-switch v-model="interactionFormData.enable" active-text="启动" inactive-text="不启动">
						</el-switch>
					</el-form-item>

					<template v-if="interactionFormData.enable">
						<!-- 弹幕 -->
						<el-form-item label="弹幕信息" label-width="130px" prop="danmakuFormat">
							<el-input v-model="interactionFormData.danmakuFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
						</el-form-item>
						<!-- 礼物 -->
						<el-form-item label="礼物信息" label-width="130px" prop="giftFormat">
							<el-input v-model="interactionFormData.giftFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
						</el-form-item>
						<!-- 点赞 -->
						<el-form-item label="点赞信息" label-width="130px" prop="likeFormat">
							<el-input v-model="interactionFormData.likeFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
						</el-form-item>
						<!-- 进入直播间 -->
						<el-form-item label="进入直播间信息" label-width="130px" prop="enterroomFormat">
							<el-input v-model="interactionFormData.enterroomFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
						</el-form-item>
						<!-- 关注 -->
						<el-form-item label="关注信息" label-width="130px" prop="followFormat">
							<el-input v-model="interactionFormData.followFormat" autocomplete="off" style="width:100%;" placeholder="请输入参与抽奖的弹幕关键词"></el-input>
						</el-form-item>
					</template>	


					<el-form-item style="display:flex;justify-content:center;">
						<el-button type="primary" @click="handleInteractionFormSubmit">提交</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>


			<div id="douga-result" style="display:none;"></div>

		`;
		containerEle.append(menuEle);
		
		// 初始化实例
		return new Vue({
				el : '.live-feed-dropmenu',
				data : function(){

					var vue = this;

					var lotteryFormDataDefault = {
						joinMethod : [],
						count : 1,
						weight : false,
						joinGiftList : [],
						mutualLotteryList : [],
						countdown : 10,
						status : '未开始',
						candidates : {},
						winners : [],
						startCandidates : [],
						source : 'livestream',
						dougaType : 'video',
						dougaList : [],
						dougaListPage : 1,
						dougaListDisabled : false,
						dougaListLoading : false,
						dougaListNoMore : false,
						dougaListActiveIndex : null,
						loading : false,
						loadingText : '',
					};

					return {

						uid : config.UID,

						loginFormDialogVisible : false,
						lotteryTableDialogVisible : false,
						lotteryFormDialogVisible : false,
						userTableDialogVisible : false,
						lotteryCountdownDialogVisible : false,
						lotteryStartDialogVisible : false,
						lotteryFormDialogTitle : '',
						userTableDialogTitle : '',
						audioFormDialogVisible : false,
						interactionFormDialogVisible : false,

						loginFormData : {
							token : '',
						},
						loginFormRules : {
							token : [{
								required : true, message : '请输入口令', trigger : 'blur',
							}],
						},

						lotteryFormDataDefault : _.cloneDeep(lotteryFormDataDefault),
						lotteryFormData : _.cloneDeep(lotteryFormDataDefault),
						lotteryFormRules : {
							name : [{
								required : true, message : '请输入奖品名称', trigger : 'blur',
							}],
							count : [{
								required : true, message : '请输入中奖人数', trigger : 'blur',
							}],
							countdown : [{
								required : true, message : '请输入抽奖倒计时', trigger : 'blur',
							}],
							startTime : [{
								required : true, message : '请设置开奖时间', trigger : 'blur',
							},{
								trigger : 'blur',
								message : '开奖时间与当前时间差距低于1分钟',
								validator : function(rule, value, callback){
									if(value && moment(value, 'HH:mm:ss').subtract(1, 'minutes') < moment()){
										callback(new Error(rule.message));
									}
									else{
										callback();
									}
								},
							},],
							joinMethod : [{
								required : true, message : '请设置抽奖参与方式', trigger : 'blur',
							},{
								trigger : 'blur',
								message : '请选择至少一个抽奖参与方式',
								validator : function(rule, value, callback){
									if(value.length==0){
										callback(new Error(rule.message));
									}
									else{
										callback();
									}
								},
							}],
							/*joinKeyword : [{
								trigger : 'blur',
								message : '请输入参与抽奖的弹幕关键词',
								validator : function(rule, value, callback){
									// 抽奖参与方式为弹幕
									if(vue.lotteryFormData.joinMethod == 'danmaku' && !value){
										callback(new Error(rule.message));
									}else{
										callback();
									}
								},
							}],*/
							/*joinGiftList : [{
								trigger : 'blur',
								message : '请选择参与抽奖的礼物,至少一个',
								validator : function(rule, value, callback){
									// 抽奖参与方式为礼物
									if(vue.lotteryFormData.joinMethod == 'gift' && (!value || value.length==0)){
										callback(new Error(rule.message));
									}else{
										callback();
									}
								},
							}],*/
						},
						giftList : giftList,
						giftNameMapper : {},

						lotteryTableData : [],

						userTableData : [],

						// 时间筛选范围,为当前时间至23:59:59
						timePickerOptions : {
							selectableRange : `${moment().format("HH:mm:ss")} - 23:59:59`,
							"value-format" : 'HH:mm:ss',
						},

						// 当前活跃抽奖
						activeLottery : {},

						// 可选语音
						audioVoiceOptions : null,
						// 语速
						speechRateMarks : {
							250 : '更慢',
							500 : '默认',
							750 : '更快',
						},
						speechVolumeMarks : {
							25 : '更小',
							50 : '默认',
							75 : '更大',
						},
						// 语音配置表单规则
						audioFormRules : {

						},
						// 语音配置表单数据
						audioFormData : {

							voice : ['general', 'Xiaoyun'],
							enable : false,
							speechRate : 500,
							speechVolume : 50,
							joinMethod : ['danmaku', 'gift', 'follow'],
							danmakuFormat : '${用户名}说${弹幕内容}',
							likeFormat : '${用户名}点赞了',
							giftFormat : '${用户名}送出${礼物数量}个${礼物名称}',
							enterroomFormat : '${用户名}进入直播间',
							followFormat : '${用户名}关注了主播',
							danmakuTimeout : 0,
							likeTimeout : 0,
							giftTimeout : 2,
							enterroomTimeout : 0,
							followTimeout : 0,

							consumeing : false,
							interactions : [],
							messageBuffer : {},

						},


						// 弹幕配置表单规则
						interactionFormRules : {

						},
						// 弹幕配置表单数据
						interactionFormData : {

							enable : false,
							danmakuFormat : ':${弹幕内容}',
							likeFormat : '点赞了',
							giftFormat : '送出${礼物数量}个${礼物名称}',
							enterroomFormat : '进入直播间',
							followFormat : '关注了主播',

						},

						// 请求acfun用户投稿时使用
						reqId : 1,
					};
				},
				methods : {
					nls : nls,
					// 下拉菜单点击回调
					handleDropdownMenuClick : function(command){

						var vue = this;

						// 添加抽奖
						if(command=='newLottery'){
							this.addOrUpdateLottery();
						}
						// 查看抽奖表格
						else if(command=='lotteryTable'){
							this.lotteryTableDialogVisible = true;
						}
						// 导出中奖名单
						else if(command=='exportLottery'){
							this.exportLottery();
						}
						// 语音配置
						else if(command=='audioConfig'){

							// 如果未登录
							if(!config.TOKEN){

								this.$message({
									type : 'error',
									message : '未登录,请先登录',
								});

								this.login(function(){
									vue.openAudioForm();
								});

							}
							else{
								this.openAudioForm();
							}

						}
						// 弹幕编辑
						else if(command=='editInteraction'){
							this.interactionFormDialogVisible = true;
						}
						// 帮助手册
						else if(command == 'help'){
							window.open('https://docs.qq.com/doc/DZXF2aFJWb0FxR3N4', '_blank');
						}
					},
					// 登录表单提交回调
					handleLoginFormSubmit : function(){
						var vue = this;
						this.$refs.loginForm.validate((valid) => {
							// 通过校验
							if(valid){


								// 检查token是否有效
								commonRequrest(config.SERVER + config.URLS.USER.INFO, 'get', null, true, function(isSuccess, data){
									// 登录成功
									if(isSuccess){
										config.TOKEN = vue.loginFormData.token;
										GM_setValue('token', config.TOKEN);
										// 关闭窗口
										vue.loginFormDialogVisible = false;

										// 如果有回调函数
										if(vue.loginFormData.nextCallback){
											vue.loginFormData.nextCallback();
										}
									}
									// 登录失败
									else{
										vue.$message({
											type : 'error',
											message : '口令错误',
										});
									}

								},{
									'Authorization' : `Token ${vue.loginFormData.token}`,
								});



							}
						});
					},

					// 抽奖表单提交回调
					handleLotteryFormSubmit : function(){

						var vue = this;

						function addOrUpdateLottery(){

							var isNew = !vue.lotteryFormData.id;
							// 设置状态
							vue.lotteryFormData.status = '未开始';
							// 设置开奖时间文字
							vue.lotteryFormData.startTimeText = moment(vue.lotteryFormData.startTime).format('HH:mm:ss');
							// 备选
							vue.lotteryFormData.candidates = {};
							vue.lotteryFormData.startCandidates = [];
							// 获奖者
							vue.lotteryFormData.winners = [];

							// 新增抽奖
							if(!vue.lotteryFormData.id){

								// 添加id
								vue.lotteryFormData.id = uuid.v4();

								vue.lotteryTableData.splice(0, 0, vue.lotteryFormData);

							}

							// 注册抽奖回调
							vue.registerLotteryCallback(vue.lotteryFormData);

							vue.lotteryFormDialogVisible = false;

							vue.$message({
								message : isNew?'添加抽奖成功':'修改抽奖信息成功',
								type : 'info',
								duration : 2000,
							});
						}

						this.$refs.form.validate((valid) => {
							// 通过校验
							if(valid){

								// 如果是稿件抽奖,查看是否有选中稿件
								if(this.lotteryFormData.source == 'douga' && this.lotteryFormData.dougaListActiveIndex==null){

									this.$message({
										message : '请选择稿件',
										type : 'error',
									});

									return;
								}

								// 稿件抽奖
								if(this.lotteryFormData.source=='douga'){

									var processMessage = null;;

									// 获取稿件评论
									this.getCommentList(this.lotteryFormData.dougaList[this.lotteryFormData.dougaListActiveIndex], true, function(isSuccess, isFinish, commentCount, page, totalPage){

										// 错误
										if(!isSuccess){

											vue.lotteryFormData.loading = false;

											vue.$message({
												message : '获取稿件评论信息错误',
												type : 'error',
											});
										}

										else{

											// 开始加载
											vue.lotteryFormData.loadingText = `正在加载 ${page}/${totalPage} 页评论`;
											vue.lotteryFormData.loading = true;

											// 加载完毕
											if(isFinish){

												vue.lotteryFormData.loading = false;
												addOrUpdateLottery();

											}


										}


									});

								}

								else{

									addOrUpdateLottery();
								}


							}
							else{

								this.$message({
									message : '提交失败,请检查是否填写正确',
									type : 'error',
								});
							}
						});
					},
					// 修改抽奖信息
					handleLotteryModify : function(lottery){
						this.addOrUpdateLottery(lottery);
					},
					// 复制抽奖
					handleLotteryCopy : function(lottery){
						this.addOrUpdateLottery(lottery, true);
					},
					// 查看候选人
					handleLotteryCandidatesCheck : function(lottery){
						var userTableData = [];
						for(var uid in lottery.candidates){
							var candidate = lottery.candidates[uid];
							userTableData.push(candidate);
						}

						this.userTableData = _.sortBy(userTableData, 'index');
						this.userTableDialogTitle = '候选名单';
						this.userTableDialogVisible = true;

					},
					// 查看中奖者
					handleLotteryWinnersCheck : function(lottery){

						this.userTableData = lottery.winners;
						this.userTableDialogTitle = '中奖名单';
						this.userTableDialogVisible = true;
					},
					login : function(callback){
						this.loginFormDialogVisible = true;

						if(_.isFunction(callback)){
							this.loginFormData.nextCallback = callback;
						}
						else{
							this.loginFormData.nextCallback = null;
						}

					},
					addOrUpdateLottery : function(lottery, copy){
						if(lottery && lottery.id){

							// 复制抽奖信息
							if(copy){
								this.lotteryFormData = {
									name : lottery.name,
									count : lottery.count,
									weight : lottery.weight,
									soucre : lottery.source,
									startTime : lottery.startTime,
									countdown : lottery.countdown,
									mutualLotteryList : _.cloneDeep(lottery.mutualLotteryList),
									joinMethod : _.cloneDeep(lottery.joinMethod),
									joinKeyword : lottery.joinKeyword,
									joinGiftList : _.cloneDeep(lottery.joinGiftList),
									candidates : {},
									startCandidates : [],
									winners : [],
									dougaType : lottery.dougaType,
									dougaList : lottery.dougaList,
									dougaListPage : lottery.dougaListPage,
									dougaListDisabled : lottery.dougaListDisabled,
									dougaListLoading : lottery.dougaListLoading,
									dougaListNoMore : lottery.dougaListNoMore,
									dougaListActiveIndex : lottery.dougaListActiveIndex,
								};
								this.lotteryFormDialogTitle = '添加抽奖';
							}
							// 修改抽奖信息
							else{
								this.lotteryFormData = lottery;
								this.lotteryFormDialogTitle = '修改抽奖';
							}

						}
						else{
							this.lotteryFormData = _.cloneDeep(this.lotteryFormDataDefault);
							this.lotteryFormDialogTitle = '添加抽奖';
						}
						this.lotteryFormDialogVisible = true;
					},
					// 注册抽奖回调
					registerLotteryCallback : function(lottery){

						var vue = this;

						function updateCandidates(){

							var candidates = {};
							lottery.dougaList[lottery.dougaListActiveIndex].commentList.forEach(function(comment, index){

								if(!(comment.uid in candidates)){
									candidates[comment.uid] = {
										index : -comment.floor,
										uid : comment.uid,
										userName : comment.userName,
										photo : comment.photo,
									};
								}

							});

							lottery.candidates = candidates;
						}

						// 如果是稿件抽奖
						if(lottery.source=='douga'){

							// 是否注册过数据回调
							if(lottery.messageHandler){
								window.clearInterval(lottery.messageHandler);
								lottery.messageHandler = null;

								// 清空候选
								lottery.candidates = {};
								lottery.startCandidates = [];
								lottery.winners = [];
							}


							// 更新候选名单
							updateCandidates();

							// 注册数据回调(每30秒执行)
							lottery.messageHandler = window.setInterval(function(){

								// 获取评论
								vue.getCommentList(lottery.dougaList[lottery.dougaListActiveIndex], true, function(isSuccess, isFinish, commentCount, page, totalPage){

									// 获取完毕
									if(isFinish){

										// 更新候选名单
										updateCandidates();


									}

								});

							}, 30 * 1000);


						}
						// 直播间抽奖
						else{
							// 是否注册过数据回调
							if(lottery.messageHandler){
								callbackManager.cancel(lottery.messageHandler);
								lottery.messageHandler = null;

								// 清空候选
								lottery.candidates = {};
								lottery.startCandidates = [];
								lottery.winners = [];

							}
							// 注册数据回调
							lottery.messageHandler = callbackManager.register('message', function(data){


								// 不符合参与方式
								if(!(
										(lottery.joinMethod.indexOf('danmaku')!=-1 && data.interaction.type=='danmaku') 
										|| (lottery.joinMethod.indexOf('gift')!=-1 && data.interaction.type=='gift')
										|| (lottery.joinMethod.indexOf('like')!=-1 && data.interaction.type=='like')
									)
								){
									return;
								}

								// 如果参与方式是弹幕
								if(data.interaction.type=='danmaku' && (lottery.joinKeyword && data.interaction.content.indexOf(lottery.joinKeyword)==-1)){
									return;
								}
								// 如果参与方式是礼物
								if(data.interaction.type=='gift' && (lottery.joinGiftList.length>0 && lottery.joinGiftList.indexOf(vue.giftNameMapper[data.interaction.giftName].id)==-1)){
									return;
								}

								var pass = true;
								// 如果设置了互斥抽奖
								if(lottery.mutualLotteryList && lottery.mutualLotteryList.length>0){


									_.filter(vue.lotteryTableData, function(o){return lottery.mutualLotteryList.indexOf(o.id)!=-1}).every(function(anotherLottery){

										if(_.findIndex(anotherLottery.winners, {uid:data.uid})!=-1){
											pass = false;
											return false;
										}
										else{
											return true;
										}

									});

								}

								if(!pass){
									return;
								}

								// 第一次被侦测
								if(!(data.uid in lottery.candidates)){
									lottery.candidates[data.uid] = {
										uid : data.uid,
										userName : data.userName,
										photo : data.photo,
										weight : 0,
										index : Object.keys(lottery.candidates).length,
									};
								}

								if(data.interaction.type=='danmaku'){
									lottery.candidates[data.uid].weight += 1;
								}
								else if(data.interaction.type=='gift'){
									lottery.candidates[data.uid].weight += vue.giftNameMapper[data.interaction.giftName].price * data.interaction.giftCount;
								}
								else if(data.interaction.type=='like'){
									lottery.candidates[data.uid].weight += 0.5;
								}


							});
						}

						var startLotteryTimeout = lottery.startTime - new Date();
						var countdownTimeout = startLotteryTimeout - lottery.countdown * 1000;

						// 是否已经注册过抽奖倒计时
						if(lottery.countdownHandler){
							window.clearTimeout(lottery.countdownHandler);
							lottery.countdownHandler = null;
						}

						if(lottery.countdown>0){
							lottery.countdownHandler = window.setTimeout(function(){

								lottery.countdownHandler = null;

								lottery.countdownText = `${lottery.countdown/60>=10?'':'0'}${_.floor(lottery.countdown/60)}:${lottery.countdown%60>=10?'':'0'}${lottery.countdown%60}`;
								vue.activeLottery = lottery;
								// 展示倒计时
								vue.showLotteryCountdown(lottery);


							}, countdownTimeout);
						}


						// 是否已经注册过抽奖
						if(lottery.startHandler){
							window.clearTimeout(lottery.startHandler);
							lottery.startHandler = null;
						}
						lottery.startHandler = window.setTimeout(function(){


							// 清除数据回调
							if(lottery.source=='douga'){
								window.clearInterval(lottery.messageHandler)
							}
							else{
								callbackManager.cancel(lottery.messageHandler);
							}
							lottery.messageHandler = null;
							lottery.startHandler = null;

							vue.activeLottery = lottery;
							// 展示结果
							vue.showLotteryStart(lottery);

						}, startLotteryTimeout);


					},

					// 返回抽奖表格行类名
					lotteryTableRowClassName : function({row}){
						if(row.status == '未开始'){
							return 'lottery-status-unstart';
						}
						if(row.status == '已结束'){
							return 'lottery-status-finish';
						}
					},

					// 开始倒计时
					showLotteryCountdown : function(lottery){

						var vue = this;

						this.lotteryStartDialogVisible = false;
						this.lotteryCountdownDialogVisible = true;
						this.$nextTick(function(){
							//circle start
							var progressBar = document.querySelector('.lottery-countdown-dialog .e-c-progress');
							var indicator = document.querySelector('.lottery-countdown-dialog #e-indicator');
							var pointer = document.querySelector('.lottery-countdown-dialog #e-pointer');
							var length = Math.PI * 2 * 100;

							progressBar.style.strokeDasharray = length;

							function update(value, timePercent) {
								var offset = - length - length * value / (timePercent);
								progressBar.style.strokeDashoffset = offset; 
								pointer.style.transform = `rotate(${360 * value / (timePercent)}deg)`; 
							};

							//circle ends
							const displayOutput = document.querySelector('.lottery-countdown-dialog .display-remain-time')

							var intervalTimer;
							var timeLeft;
							var wholeTime = lottery.countdown; // manage this to set the whole time 
							var isPaused = false;
							var isStarted = false;


							update(wholeTime,wholeTime); //refreshes progress bar
							displayTimeLeft(wholeTime);

							function changeWholeTime(seconds){
								if ((wholeTime + seconds) > 0){
									wholeTime += seconds;
									update(wholeTime,wholeTime);
								}
							}


							function timer (seconds){ //counts time, takes seconds
								var remainTime = Date.now() + (seconds * 1000);
								displayTimeLeft(seconds);
								
								intervalTimer = window.setInterval(function(){
									timeLeft = Math.round((remainTime - Date.now()) / 1000);

									// 倒计时结束
									if(timeLeft < 0){
										window.clearInterval(intervalTimer);
										isStarted = false;
										
										// 隐藏对话框
										vue.lotteryCountdownDialogVisible = false;

										return ;
									}
									displayTimeLeft(timeLeft);
								}, 1000);
							}
							function displayTimeLeft (timeLeft){ //displays time on the input
								var minutes = Math.floor(timeLeft / 60);
								var seconds = timeLeft % 60;
								var displayString = `${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
								displayOutput.textContent = displayString;
								update(timeLeft, wholeTime);
							}

							timer(wholeTime);

						});
					},
					// 开始抽奖
					showLotteryStart : function(lottery){

						var vue = this;
						var stop = false;
						var activeIndex = -1;

						this.lotteryCountdownDialogVisible = false;
						var rollIntervalHandler = null;

						// 候选人数小于等于抽奖人数,跳过抽奖动画
						if(Object.keys(lottery.candidates).length<=lottery.count){

							this.$message({
								type : 'info',
								message : '候选人数小于等于抽奖人数,跳过抽奖动画',
							});

							lottery.winners = _.flatMap(lottery.candidates);
							lottery.status = '已结束';
							this.handleLotteryWinnersCheck(lottery);

							return;

						}


						function roll(){
							if(stop){
								// 获取当前赢家
								vue.$refs.carousel.setActiveItem(_.findIndex(lottery.startCandidates, {uid:lottery.winners[lottery.winners.length-1].uid}));

							}
							else{
								vue.$refs.carousel.next();
							}
						}

						function changeRollIntervals(intervals, timeouts, callback){

							if(!timeouts){
								timeouts = 0;
							}

							if(!_.isArray(intervals)){
								intervals = [intervals];
							}
							if(!_.isArray(timeouts)){
								timeouts = [timeouts];

								if(timeouts.length>intervals.length){
									timeouts = timeouts.slice(0, intervals.length);
								}
								if(timeouts.length<intervals.length){
									var npads = intervals.length-timeouts.length;
									for(var i=0;i<npads;++i){
										timeouts.splice(0, 0, 0);
									}
								}

							}

							intervals.forEach(function(interval, index){
								window.setTimeout(function(){
									if(rollIntervalHandler!=null){
										window.clearTimeout(rollIntervalHandler);
									}
									if(interval != null){
										rollIntervalHandler = window.setInterval(roll, interval);
									}
									else{
										
										stop = true;
										// 获取当前赢家
										activeIndex = _.findIndex(lottery.startCandidates, {uid:lottery.winners[lottery.winners.length-1].uid});
										vue.$refs.carousel.setActiveItem(activeIndex);
										// 高亮
										lottery.startCandidates[activeIndex].highlight = true;
										vue.$forceUpdate();

										vue.$refs.carousel.$nextTick(function(){
											// 停止回调
											if(_.isFunction(callback)){
												callback();
											}
										});

									}
								}, timeouts[index]);

							});

						}

						// 当前滚动名单
						lottery.startCandidates = _.flatMap(lottery.candidates);
						
						this.$nextTick(function(){

							var startChoose = function(){

								// 获取中奖者
								lottery.winners.push(_.sample(lottery.startCandidates));
								vue.lotteryStartDialogVisible = true;
								stop = false;

								// 8秒内需要滚动完所有用户
								var interval = Math.min(Math.max(Math.floor(8000/lottery.startCandidates.length), 150), 350);

								// 高速转动
								// 10秒后停止转动
								changeRollIntervals(
									[interval, null],
									[0, 10000],
									// 转动结束后获取当前用户
									function(){

										// 等待2秒
										window.setTimeout(function(){

											// 去除高亮
											lottery.startCandidates[activeIndex].highlight = false;

											// 如果已经抽取结束
											if(lottery.winners.length >= lottery.count){

												lottery.status = '已结束';
												// 2秒后
												window.setTimeout(function(){
													// 关闭弹窗
													vue.lotteryStartDialogVisible = false;

													// 打开中奖名单
													vue.handleLotteryWinnersCheck(lottery);

												}, 2000);

											}
											// 进行下一个抽奖
											else{

												// 关闭弹窗
												vue.lotteryStartDialogVisible = false;
												vue.activeLottery = null;
												vue.$nextTick(function(){
													// 1秒后重新开始
													window.setTimeout(function(){
														// 去除中奖者并打乱顺序
														lottery.startCandidates = _.shuffle(_.filter(lottery.startCandidates, function(candidate){return candidate.uid != lottery.winners[lottery.winners.length-1].uid}));
														vue.$nextTick(function(){
															vue.activeLottery = lottery;
															startChoose();
														});
													}, 1000);
												});

											}


										}, 2000);

									},
								);

							};

							// 开始抽奖
							startChoose();



						});


					},
					// 导出中奖名单
					exportLottery : function(){

						var workbook = new ExcelJS.Workbook();
						var sheet = workbook.addWorksheet('中奖名单');
						sheet.columns = [
							{ key: 'userName', width: 30, },
							{ key: 'uid', width: 10, },
						];

						var rowIndex = 1;
						// 遍历所有已结束的抽奖
						this.lotteryTableData.forEach(function(lottery){

							if(lottery.status != '已结束'){
								return true;
							}

							// 添加标题
							sheet.addRow([lottery.name]);
							sheet.mergeCells(rowIndex,1,rowIndex,2);
							// 设置标题样式
							var titleRow = sheet.getRow(rowIndex);
							var titleCell = titleRow.getCell(1);
							// 文字居中
							titleCell.alignment = {vertical: 'middle', horizontal: 'center'};
							// 添加边框
							titleCell.border = {
								top: {style:'thin'},
								left: {style:'thin'},
								bottom: {style:'thin'},
								right: {style:'thin'},
							};
							// 加粗字体
							titleCell.font = {
								bold : true,
							};


							sheet.addRow({userName: '用户名', uid : '用户uid'});
							// 设置列名样式
							var headerRow = sheet.getRow(rowIndex + 1);
							for(var i=1;i<=2;++i){
								headerRow.getCell(i).alignment = {vertical: 'middle', horizontal: 'center'};
								headerRow.getCell(i).border = {
									top: {style:'thin'},
									left: {style:'thin'},
									bottom: {style:'thin'},
									right: {style:'thin'},
								};
							}

							// 遍历中奖用户
							lottery.winners.forEach(function(winner, index){
								sheet.addRow({userName: winner.userName, uid : winner.uid});

								// 设置记录样式
								var recordRow = sheet.getRow(rowIndex + 2 + index);
								for(var i=1;i<=2;++i){
									recordRow.getCell(i).alignment = {vertical: 'middle', horizontal: 'center'};
									recordRow.getCell(i).border = {
										top: {style:'thin'},
										left: {style:'thin'},
										bottom: {style:'thin'},
										right: {style:'thin'},
									};
								}
							});

							// 添加两个空白行
							sheet.addRow();
							sheet.addRow();

							rowIndex += 1 + 1 + lottery.winners.length + 2;

						});

						;(async function(){
							var buffer = await workbook.xlsx.writeBuffer();
							var file = new File([buffer], '中奖名单.xlsx');
							saveAs(file);
						})();

					},

					openAudioForm : function(){

						var vue = this;

						// 检测是否获取语音选项
						if(isNullOrEmpty(this.audioVoiceOptions)){

							vue.$message({
								type : 'info',
								message : '正在获取弹幕语音',
							});

							// 获取语音
							commonRequrest(config.SERVER + config.URLS.ALICLOUD.VOICE, 'get', null, false, function(isSuccess, data){

								// 获取失败
								if(!isSuccess){
									vue.$message({
										type : 'error',
										message : '弹幕语音获取失败',
									});
									return;
								}

								vue.audioVoiceOptions = data;

								vue.$message({
									type : 'info',
									message : '弹幕语音获取成功',
								});
								vue.audioFormDialogVisible = true;

							});
						}
						else{
							this.audioFormDialogVisible = true;
						}
					},

					// 语音配置表单提交
					handleAudioFormSubmit : function(){

						var vue = this;

						this.$refs.audioForm.validate((valid) => {
							// 通过校验
							if(valid){
								// 提交修改
								GM_setValue('audioFormData', JSON.stringify({
									voice : this.audioFormData.voice,
									enable : this.audioFormData.enable,
									speechRate : this.audioFormData.speechRate,
									speechVolume : this.audioFormData.speechVolume,
									joinMethod : this.audioFormData.joinMethod,
									danmakuFormat : this.audioFormData.danmakuFormat,
									likeFormat : this.audioFormData.likeFormat,
									giftFormat : this.audioFormData.giftFormat,
									enterroomFormat : this.audioFormData.enterroomFormat,
									followFormat : this.audioFormData.followFormat,
									danmakuTimeout : this.audioFormData.danmakuTimeout,
									likeTimeout : this.audioFormData.likeTimeout,
									giftTimeout : this.audioFormData.giftTimeout,
									enterroomTimeout : this.audioFormData.enterroomTimeout,
									followTimeout : this.audioFormData.followTimeout,

									consumeing : false,
									interactions : [],
									messageBuffer : {},

								}));

								this.handleAudioFormSubmitValid();

							}
						});

					},
					handleAudioFormSubmitValid : function(){
						var vue = this;
						// 检测当前是否有缓冲
						for(var bufferKey in this.audioFormData.messageBuffer){
							window.clearTimeout(this.audioFormData.messageBuffer[bufferKey].handler);
						}

						this.audioFormData.messageBuffer = {};

						// 检测是否已经添加了语音播报
						if(this.audioFormData.messageHandler){
							callbackManager.cancel(this.audioFormData.messageHandler);
							this.audioFormData.messageHandler = null;
						}

						// 开启播报
						if(this.audioFormData.enable){
							this.audioFormData.messageHandler = callbackManager.register('message', function(data){
								
								// 不是允许的互动类型
								if(vue.audioFormData.joinMethod.indexOf(data.interaction.type)==-1){
									return;
								}

								var bufferKey = null;
								var timeout = 0;
								if(data.interaction.type=='gift'){
									bufferKey = data.uid + data.interaction.type + data.interaction.giftName; 
									timeout = vue.audioFormData.giftTimeout;
								}

								// 不进行缓存,直接播报
								if(bufferKey==null || timeout == 0){
									data.interaction = [data.interaction];
									vue.consumeAudio(vue.audioFormData, data);
									return;
								}

								// 已有相同信息
								if(bufferKey in vue.audioFormData.messageBuffer){
									window.clearTimeout(vue.audioFormData.messageBuffer[bufferKey].handler);
									vue.audioFormData.messageBuffer[bufferKey].interaction.push(data.interaction);
								}
								else{
									vue.audioFormData.messageBuffer[bufferKey] = {
										uid : data.uid,
										userName : data.userName,
										interaction : [data.interaction],
									};
								}
								vue.audioFormData.messageBuffer[bufferKey].handler = window.setTimeout(function(){
									var data = vue.audioFormData.messageBuffer[bufferKey];
									vue.audioFormData.messageBuffer[bufferKey].handler = null;
									delete vue.audioFormData.messageBuffer[bufferKey];
									vue.consumeAudio(vue.audioFormData, data);
								}, timeout*1000);
							});
						}

						// 关闭弹窗
						this.audioFormDialogVisible = false;
					},

					// 弹幕配置表单提交
					handleInteractionFormSubmit : function(){

						var vue = this;

						this.$refs.interactionForm.validate((valid) => {
							// 通过校验
							if(valid){

								// 提交修改
								GM_setValue('interactionFormData', JSON.stringify({
									enable : this.interactionFormData.enable, 
									danmakuFormat : this.interactionFormData.danmakuFormat, 
									likeFormat : this.interactionFormData.likeFormat, 
									giftFormat : this.interactionFormData.giftFormat, 
									enterroomFormat : this.interactionFormData.enterroomFormat, 
									followFormat : this.interactionFormData.followFormat, 
								}));

								this.handleInteractionFormSubmitValid();

							}
						});

					},
					handleInteractionFormSubmitValid : function(){

						var vue = this;

						// 检测是否已经添加了弹幕监测
						if(this.interactionFormData.messageHandler){
							callbackManager.cancel(this.interactionFormData.messageHandler);
							this.interactionFormData.messageHandler = null;
						}

						if(this.interactionFormData.enable){
							// 启动监测
							this.interactionFormData.messageHandler = callbackManager.register('message', function(data){

								// 弹幕
								if(data.interaction.type=='danmaku'){
									data.node.querySelector('.comment-text').innerText = formatText(vue.interactionFormData.danmakuFormat, {'用户名':data.userName,'弹幕内容':data.interaction.content});	
								}
								// 点赞
								else if(data.interaction.type == 'like'){
									data.node.querySelector('.like-text').innerText = formatText(vue.interactionFormData.likeFormat, {'用户名':data.userName});
								}
								// 进入直播间
								else if(data.interaction.type == 'enterroom'){
									data.node.querySelector('.nickname').nextElementSibling.innerText = formatText(vue.interactionFormData.enterroomFormat, {'用户名':data.userName});
								}
								// 关注
								else if(data.interaction.type == 'follow'){
									data.node.querySelector('.follow-text').innerText = formatText(vue.interactionFormData.followFormat, {'用户名':data.userName});
								}
								// 礼物
								else if(data.interaction.type == 'gift'){
									data.node.querySelector('.nickname').nextElementSibling.innerText = formatText(vue.interactionFormData.giftFormat, {'用户名':data.userName, '礼物数量' : data.interaction.giftCount, '礼物名称' : data.interaction.giftName});
								}


							}, null, true);
						}

						this.interactionFormDialogVisible = false;
					},

					consumeAudio(audioFormData, interactionData){

						var vue = this;

						// 弹幕合并
						if(interactionData.interaction[0].type == 'danmaku'){
							interactionData.interaction = {
								type : 'danmaku',
								content : _.reduce(interactionData.interaction, function(text, interaction){
										return text + (text==''?'':'<break time=\"500ms\"/>') + interaction.content;
									}, ''),
							};

						}
						// 礼物合并
						else if(interactionData.interaction[0].type == 'gift'){
							interactionData.interaction = {
								type : 'gift',
								giftName : interactionData.interaction[0].giftName,
								giftCount : _.sumBy(interactionData.interaction, 'giftCount'),
							}

						}
						// 其他合并
						else{
							interactionData.interaction = interactionData.interaction[0];
						}

						audioFormData.interactions.push(interactionData);
						if(audioFormData.consumeing){
							return;
						}
						audioFormData.consumeing = true;

						new Promise(function(resolve, reject) {

							var readInteractionAudio = function(){
								if(audioFormData.interactions.length==0){
									audioFormData.consumeing = false;
									resolve();
									return;
								}

								var interactionData = audioFormData.interactions.splice(0, 1)[0];
								vue.readInteractionAudio(audioFormData, interactionData, readInteractionAudio);


							}

							readInteractionAudio();


						}).then(function(){

						}).catch(function(err){
						});


					},

					readInteractionAudio(audioFormData, interactionData, callback){


						// 弹幕
						if(interactionData.interaction.type == 'danmaku'){
							nls(`<speak>${audioFormData.danmakuFormat}</speak>`, audioFormData.voice[audioFormData.voice.length-1], audioFormData.speechRate - 500, audioFormData.speechVolume, {
								'用户名' : interactionData.userName + '<break time=\"500ms\"/>',
								'弹幕内容' : '<break time=\"500ms\"/>' + interactionData.interaction.content,
							}, callback);
						}
						// 礼物
						else if(interactionData.interaction.type == 'gift'){
							nls(`<speak>${audioFormData.giftFormat}</speak>`, audioFormData.voice[audioFormData.voice.length-1], audioFormData.speechRate - 500, audioFormData.speechVolume, {
								'用户名' : interactionData.userName + '<break time=\"500ms\"/>',
								'礼物数量' : interactionData.interaction.giftCount,
								'礼物名称' : interactionData.interaction.giftName,
							}, callback);
						}
						// 点赞
						else if(interactionData.interaction.type == 'like'){
							nls(`<speak>${audioFormData.likeFormat}</speak>`, audioFormData.voice[audioFormData.voice.length-1], audioFormData.speechRate - 500, audioFormData.speechVolume, {
								'用户名' : interactionData.userName + '<break time=\"500ms\"/>',
							}, callback);
						}
						// 进入直播间
						else if(interactionData.interaction.type == 'enterroom'){
							nls(`<speak>${audioFormData.enterroomFormat}</speak>`, audioFormData.voice[audioFormData.voice.length-1], audioFormData.speechRate - 500, audioFormData.speechVolume, {
								'用户名' : interactionData.userName + '<break time=\"500ms\"/>',
							}, callback);
						}
						// 关注
						else if(interactionData.interaction.type == 'follow'){
							nls(`<speak>${audioFormData.followFormat}</speak>`, audioFormData.voice[audioFormData.voice.length-1], audioFormData.speechRate - 500, audioFormData.speechVolume, {
								'用户名' : interactionData.userName + '<break time=\"500ms\"/>',
							}, callback);
						}
						else{
							callback();
						}

					},

					// 获取投稿数据
					getDougaList(){

						var vue = this;

						var pageSize = null;
						if(this.lotteryFormData.dougaType == 'video'){
							pageSize = 10;
						}
						else if(this.lotteryFormData.dougaType == 'article'){
							pageSize = 10;
						}

						var params = {
							'quickViewId' : `ac-space-${this.lotteryFormData.dougaType}-list`,
							'reqID': this.reqId,
							'ajaxpipe': 1,
							'type': this.lotteryFormData.dougaType,
							'order': 'newest',
							'page' : this.lotteryFormData.dougaListPage,
							'pageSize': pageSize,
						};

						this.reqId += 1;
						vue.lotteryFormData.dougaListLoading = true;
						commonRequrest(config.ACFUN_SERVER + config.URLS.ACFUN_USER.SPACE + `/${this.uid}`, 'get', params, true, function(isSuccess, data){
							

							// 获取成功
							if(isSuccess){


								document.querySelector('#douga-result').innerHTML = JSON.parse(data.replace('/*<!-- fetch-stream -->*/', ''))['html'];
				
								var dougaEleList = null;

								// 查看视频投稿
								if(params.type == 'video'){
									dougaEleList = document.querySelectorAll('#douga-result #ac-space-video-list a');	
								}
								// 查看文章投稿
								else if(params.type == 'article'){
									dougaEleList = document.querySelectorAll('#douga-result #ac-space-article-list article');	
								}
								

								// 无结果
								if(!dougaEleList || dougaEleList.length==0){
									vue.lotteryFormData.dougaListDisabled = true;
									vue.lotteryFormData.dougaListNoMore = true;
								}
								else{

									var dougaList = [];

									// 视频投稿
									if(params.type == 'video'){

										dougaEleList.forEach(function(dougaEle){

											dougaList.push({
												id : dougaEle.attributes.href.value.split('/').pop().replace('ac', ''),
												href : config.ACFUN_SERVER + dougaEle.attributes.href.value,
												cover : dougaEle.querySelector('img').src,
												title : dougaEle.querySelector('figcaption .title').title,
												uploadDateText : dougaEle.querySelector('figcaption .date').innerText,
												playCountText : dougaEle.querySelector('figcaption .play-info').innerText.match(/观看(?<count>[0-9\.万]+)/).groups['count'],
											});
										});

									}
									// 文章投稿
									else if(params.type == 'article'){

										dougaEleList.forEach(function(dougaEle){


											dougaList.push({
												id : dougaEle.querySelector('a').attributes.href.value.split('/').pop().replace('ac', ''),
												href : config.ACFUN_SERVER + dougaEle.querySelector('a').attributes.href.value,
												title : dougaEle.querySelector('a').title,
												uploadDateText : dougaEle.querySelector('.info').innerText.match(/发布于\s*(?<date>\d{4}\/\d{2}\/\d{2})/).groups['date'],
												playCountText : dougaEle.querySelector('.info').innerText.match(/(?<count>[0-9\.万]+)人围观/).groups['count'],
											});
										});
									}


									vue.lotteryFormData.dougaList.splice(vue.lotteryFormData.dougaList.length, 0, ...dougaList);

									vue.lotteryFormData.dougaListPage += 1;

								}


							}
							else{

								vue.lotteryFormData.dougaListDisabled = true;
								vue.lotteryFormData.dougaListNoMore = true;

							}

							vue.lotteryFormData.dougaListLoading = false;


						});
					},

					// 刷新投稿数据
					refreshDougaList(){

						this.lotteryFormData.dougaList = [];
						this.lotteryFormData.dougaListPage = 1;
						this.lotteryFormData.dougaListDisabled = false;
						this.lotteryFormData.dougaListLoading = false;
						this.lotteryFormData.dougaListNoMore = false;
						this.lotteryFormData.dougaListActiveIndex = null;
						this.getDougaList();

					},
					handleDougaListItemClick(dougaIndex){
						// 点击已选中投稿表示取消选中
						if(this.lotteryFormData.dougaListActiveIndex == dougaIndex){
							this.lotteryFormData.dougaListActiveIndex = null;
						}
						else{
							this.lotteryFormData.dougaListActiveIndex = dougaIndex;

						}
					},
					handleDougaListItemDetailClick(dougaIndex){
						window.open(this.lotteryFormData.dougaList[dougaIndex].href, '_blank');
					},

					// 获取投稿
					getCommentList(douga, all, callback){

						var vue = this;

						var params = {
							sourceId : douga.id,
							sourceType : 3,
							page : 1,
							pivotCommentId : 0,
							supportZtEmot : true,
						};

						var fetch = true;
						var commentList = [];
						var preCommentId = douga.commentList && douga.commentList.length>0?douga.commentList[0].id:null;
						
						var getData = function(){

							commonRequrest(config.ACFUN_SERVER + config.URLS.DOUGA.COMMENT, 'get', params, true, function(isSuccess, data){

								// 获取失败
								if(!isSuccess){
									callback(false, false, douga.commentCount, params.page, douga.commentListTotalPage);
									fetch = false;
								}

								else{

									data = JSON.parse(data);

									// 返回错误
									if(data.result != 0){
										fetch = false;
										return;
									}

									// 设置评论数量
									douga.commentCount = data.commentCount;
									douga.commentListTotalPage = data.totalPage;

									data.rootComments.every(function(comment, commentIndex){

										// 如果是已经获取过的评论,结束获取
										if(comment.commentId == preCommentId){
											fetch = false;
											return false;
										}

										commentList.push({
											id : comment.commentId,
											uid : comment.userId,
											userName : comment.userName,
											photo : comment.headUrl[0].url,
											content : comment.content.replace(/\[emot=[^\[\]]*\]/g, ''),
											floor : comment.floor,
											date : moment(comment.timestamp).toDate(),
											dateText : moment(comment.timestamp).format('MM-DD HH:mm'),
										});

										return true;

									});

									// 获取结束
									if(params.page == douga.commentListTotalPage){
										fetch = false;
									}


								}


								if(!all){
									fetch = false;
								}
								// 获取完毕
								else if(params.page == douga.commentListTotalPage){
									fetch = false;
								}

								// 继续获取
								if(fetch){
									params.page += 1;
									// 回调
									if(_.isFunction(callback)){
										callback(true, false, douga.commentCount, params.page, douga.commentListTotalPage);
									}

									getData();

								}
								// 获取结束
								else{

									// 添加评论
									if(!douga.commentList){
										douga.commentList = [];
									}

									if(commentList.length>0){
										douga.commentList.splice(0, 0, ...commentList);
									}

									// 回调
									if(_.isFunction(callback)){
										callback(true, true, douga.commentCount, params.page, douga.commentListTotalPage);
									}



								}




							});

						}

						// 获取数据
						getData();

					},

				},
				mounted : function(){
					var vue = this;

					this.giftList.forEach(function(gift){
						vue.giftNameMapper[gift.name] = gift;
					});

					async function loadData(){
						// 查看缓存的数据
						var audioFormData = await GM_getValue('audioFormData');
						if(audioFormData){
							vue.audioFormData = JSON.parse(audioFormData);
							vue.handleAudioFormSubmitValid();
						}
						var interactionFormData = await GM_getValue('interactionFormData');
						if(interactionFormData){
							vue.interactionFormData = JSON.parse(interactionFormData);
							vue.handleInteractionFormSubmit();
						}
					}
					loadData();



					// 热键,方向键右,表示增加语速
					key('right', function(){
						vue.audioFormData.speechRate = Math.min(1000, vue.audioFormData.speechRate + 100);
					});
					// 热键,方向键左,表示减小语速
					key('left', function(){
						vue.audioFormData.speechRate = Math.max(0, vue.audioFormData.speechRate - 100);
					});
					// 热键,方向键上,表示增加音量
					key('up', function(){
						vue.audioFormData.speechVolume = Math.min(100, vue.audioFormData.speechVolume + 10);
					});
					// 热键,方向键下,表示减小音量
					key('down', function(){
						vue.audioFormData.speechVolume = Math.max(0, vue.audioFormData.speechVolume + 10);
					});
				},
		});
	}


	disableVideos();
	
	
	window.onload = function(){
		addVupSign();

		var intervalHandler = window.setInterval(function(){
			if(loadVue()){
				window.clearInterval(intervalHandler);
			}
		}, 500);

	};
	
	
	
})();