<?php
$user = SESS::get('EVENTUserInfo');
//if(isn($user))exit();
$user = json_decode($user,true);
$canEdit = in_array($user['name'],$ROLES);

function fix2($v){
	$x = '00'.$v;
	return substr($x,-2);
}

$act = r('act');
$type = r('type');
if($act=='newevent'){
	$keys = array('start','end','game','allday','shour','smin','event','title');
	$dict=array();
	foreach($keys as $k){
		$dict[$k] = r($k);
	}
	$sql = DB::insert('calendar',$dict);
	DB::exe($sql);
	we('1');
}else if($act=='modievent'){
	$id = r('id');
	$keys = array('start','end','game','allday','shour','smin','event','title');
	$dict=array();
	foreach($keys as $k){
		$dict[$k] = r($k);
	}
	$sql = DB::update('calendar',$dict,"id='{$id}'");
	DB::exe($sql);
	we('1');
}else if($act=='movevent'){

	$id = r('id');
	$keys = array('start','end');
	$dict=array();
	foreach($keys as $k){
		$dict[$k] = r($k);
	}
	if(isn($dict['end']))$dict['end']=$dict['start'];
	$sql = DB::update('calendar',$dict,"id='{$id}'");
	DB::exe($sql);
	we('1');
}else if($act=='delevent'){
	$id = r('id');
	$sql = "delete from calendar where id='{$id}'";
	DB::exe($sql);
	we('1');
}else if($act=='getEventByid'){
	$id = r('id');
	$sql = "select * from calendar where id='{$id}'";
	$rs = DB::getOne($sql);
	we(json_encode($rs));
}else if($act=='getEvents'){
	$start = r('start');
	$end = r('end');
	$game = r('game');
	$where = "";
	
	if(!isn($game)){
		$where .=" and game='{$game}'";
	}

	$startDate = date('Y-m-d',$start);
	$endDate = date('Y-m-d',$end);
	$month = date('Y-m',($start+$end)/2);
	
	$sql = "select * from calendar where ((start>='{$startDate}' and start<='{$endDate}') or (end>='{$startDate}' and end<='{$endDate}'))  {$where}";
	$rss = DB::getArray($sql);
    $eventCount = array(
        '总更新&总修复'=>array(
            'dangerCount'=>0,
            'purpleCount'=>0
        )
    );

	$res = array();
	foreach($rss as $rs){
	    if (!$eventCount[$rs['game']]){
            $eventCount[$rs['game']] = array(
                    'dangerCount'=>0,
                    'purpleCount'=>0
            );
		}
		$class="light";
		if($rs['event']=='节点'){
			$class="success";
		}elseif($rs['event']=='打包'){
			$class="warning";
		}elseif($rs['event']=='版本更新'){
			$class="danger";
			if(strstr($rs['end'], $month)){
				$eventCount[$rs['game']]['dangerCount']+=1;
				$eventCount['总更新&总修复']['dangerCount']+=1;
			}
		}elseif($rs['event']=='上线'){
			$class="pink";
		}elseif($rs['event']=='修复外网'){
			$class="purple";
			if(strstr($rs['end'], $month)){
				$eventCount[$rs['game']]['purpleCount']+=1;
				$eventCount['总更新&总修复']['purpleCount']+=1;
			}
		}

		$gameName = $rs['game'];
		$row = array(
			'id' => $rs['id'],
			'title' => '【'.$gameName .'】'.$rs['event']."：".$rs['title'],
			'start' => $rs['start'],
			'end' => $rs['end'],
			'className' => 'label-'.$class,
		);
		$row['allDay'] = true;
		$res[] = $row;
	}
	$eventCharts = array(array('product','更新次数','修复次数'));
    $eventTable = array([],[]);
  	foreach ($eventCount as $key=>$value){
		if($eventCount[$key]['purpleCount']!=0 || $eventCount[$key]['dangerCount']!=0)
        	$eventCharts[] = array($key,$eventCount[$key]['dangerCount'],$eventCount[$key]['purpleCount']);
    }
    foreach ($eventCharts as $value){
		$eventTable[0][] = $value[0];
        $eventTable[1][0][] = $value[1];
        $eventTable[1][1][] = $value[2];
        if($eventCount[$value[0]]['dangerCount']==0)
            $eventTable[1][2][] = '0.00%';
        else
            $eventTable[1][2][] = number_format($eventCount[$value[0]]['purpleCount']*100/$eventCount[$value[0]]['dangerCount'],2).'%';
    }

	// we(json_encode(array('charts'=>$eventCharts,'table'=>$eventTable)));
	

	$json = array(
		'calendarData'=>$res
	);

	if(!isn($game)){
		$where =" and game='{$game}'";
		$sql = "select * from calendar where 1=1 {$where} order by end";
		$rss = DB::getArray($sql);
		$res = array();
		foreach($rss as $rs){
			$res[] = array(
				"end"=> $rs['end'],
				"gamename"=>$rs['game'],
				"event"=>$rs['event'],
				"title"=>$rs['title']
			);
		}
		$json["gameInfo"] = $res;
	}
	if($type=='charts')
		// we(json_encode($eventCharts));
		we(json_encode(array('charts'=>$eventCharts,'table'=>$eventTable)));
	else
		we(json_encode($json));
}
?>
<!DOCTYPE html>
<html lang="en">
	<head>
	<title>乐谷游戏管理系统</title>
	<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- basic styles -->
<link href="assets/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="assets/css/font-awesome.min.css" />
<!--[if IE 7]>
<link rel="stylesheet" href="assets/css/font-awesome-ie7.min.css" />
<![endif]-->
<!--link rel="stylesheet" href="http://fonts.useso.com/css?family=Open+Sans:400,300" /-->
<!-- ace styles -->
<link rel="stylesheet" href="assets/css/ace.min.css" />
<link rel="stylesheet" href="assets/css/ace-rtl.min.css" />
<link rel="stylesheet" href="assets/css/ace-skins.min.css" />
<!--[if lte IE 8]>
<link rel="stylesheet" href="assets/css/ace-ie.min.css" />
<![endif]-->
<script src="assets/js/ace-extra.min.js?_veri=20151101"></script>
<!--[if lt IE 9]>
<script src="assets/js/html5shiv.js"></script>
<script src="assets/js/respond.min.js"></script>
<![endif]-->
<script src="assets/tmpl.js"></script>
<style>html,body,h1{font-family:"微软雅黑" !important}</style>



<!--[if !IE]> -->
<script type="text/javascript">
	window.jQuery || document.write("<script src='assets/js/jquery-2.0.3.min.js'>"+"<"+"script>");
</script>
<!-- <![endif]-->

<!--[if IE]>
<script type="text/javascript">
window.jQuery || document.write("<script src='assets/js/jquery-1.10.2.min.js'>"+"<"+"script>");
</script>
<![endif]-->

<script type="text/javascript">
if("ontouchend" in document) document.write("<script src='assets/js/jquery.mobile.custom.min.js'>"+"<"+"script>");
</script>

<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/typeahead-bs2.min.js"></script>

<!-- page specific plugin scripts -->

<!--[if lte IE 8]>
<script src="assets/js/excanvas.min.js"></script>
<![endif]-->
<script src="assets/js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="assets/js/jquery.ui.touch-punch.min.js"></script>
<script src="assets/js/jquery.slimscroll.min.js"></script>
<script src="assets/js/jquery.easy-pie-chart.min.js"></script>
<script src="assets/js/jquery.sparkline.min.js"></script>
<script src="assets/js/flot/jquery.flot.min.js"></script>
<script src="assets/js/flot/jquery.flot.pie.min.js"></script>
<script src="assets/js/flot/jquery.flot.resize.min.js"></script>
<!-- ace scripts -->
<script src="assets/js/ace-elements.min.js"></script>
<script src="assets/js/ace.min.js"></script>
<script src="assets/jedate.js"></script>
<script src="assets/doT.js"></script>
<script src="assets/echarts.min.js"></script>
<script src="assets/public.js?_=123"></script>
<!-- inline scripts related to this page -->

	<link rel="stylesheet" href="assets/css/fullcalendar.css" />
	</head>

	<body>

		<div class="main-container" id="main-container">
			<script type="text/javascript">
				try{ace.settings.check('main-container' , 'fixed')}catch(e){}
			</script>

			<div class="main-container-inner">
				
				<div class="main-content">
					<div class="page-content">
						<div class="page-header">
							<h1>LeGu Event</h1>
						</div>
						<div id="gamesbtn">
							筛选：
                            <?php if($canEdit){?><a href="./?app=edit"  class='btn btn-minier btn-pink'>编辑游戏</a><?}?>
							<button value='' onclick='onlyShowGame(this)' class='btn btn-minier btn-info'>显示全部</button> 
							<?php
							foreach($GAMES as $g){
								echo "<button value='{$g}' onclick='onlyShowGame(this)' class='btn btn-minier'>{$g}</button> ";
							}?>

							<div class="space-6"></div>

						</div>
						
						<style>
						.datarepair { z-index:1000000; 
							width:100px; 
							height: 40px; 
							position:relative; 
							top:40px; 
							color:#6fb3e0;
							margin: 0 auto;
							cursor:pointer; 
							font-size: 16px; 
							display: flex;
						}
						.datarepair img { width:20px; height:20px; margin-right:5px; margin-top:3px;}
						#gameinfo{margin:15px 0}
						#gameinfo li{  
							padding: 0px 0 0 20px;   
							line-height: 40px;  
							background: #50abe4;  
							display: inline-block;   
							color: #fff;  
							position: relative;
							display:inline-block;
							margin:5px
				
						}
						#gameinfo li:after{  
							 content: '';  
							display: block;  
							border-top: 20px solid transparent;  
							border-bottom: 20px solid transparent;  
							border-left: 20px solid #50abe4;  
							position: absolute;   
							right: -20px;   
							top: 0;  
							z-index: 10; 
						}
						#gameinfo li:before{  
							content: '';  
							display: block;  
							border-top: 20px solid transparent;  
							border-bottom: 20px solid transparent;  
							border-left: 20px solid #fff;  
							position: absolute;   
							left: 0px;   
							top: 0;  
						}
						.fc-header {
							position:relative;
							top: -40px;
						}
						</style>

						<div id="gameinfo" style="display:block">
							<ul>
								
							</ul>
						</div>



						<style>
						.fc-event{border:none}
						.data_box { display: none; }
						</style>
						<div class='datarepair' id="datarepair" onclick="datarepair()">
							<img src='assets/images/xiazai.png' />	修复数据
						</div>
						<div class='data_box' id='data_box' >

							<div id="chart" class="chartbox" style="width:100%;height:400px; margin-top:50px;"></div>

							<div class="card-body">
								<table class="table table-bordered table-striped">
									<thead id="thead-title" class="thead"> </thead>
									<tbody id="tbody-content"> </tbody>
								</table>
							</div>

						</div>
						
						<div class="col-xm-12" id="calendardiv">
							<div id="calendar"></div>
						</div>
					</div>
				</div>
				
			</div>

			<a href="#" id="btn-scroll-up" class="btn-scroll-up btn btn-sm btn-inverse">
				<i class="icon-double-angle-up icon-only bigger-110"></i>
			</a>
		</div>
		<link rel="stylesheet" href="assets/css/jquery.gritter.css" />
		<script src="assets/js/jquery.gritter.min.js"></script>

		<script src="assets/js/bootbox.min.js"></script>
		<script src="assets/js/fullcalendar.min.js"></script>

		<link rel="stylesheet" href="assets/css/daterangepicker.css" />
		<script src="assets/js/date-time/moment.min.js"></script>
		<script src="assets/js/date-time/daterangepicker.min.js"></script>

	<script type="text/x-dot-template" id="thead-dot">
		<tr>
			{{~it:item:index}}
		
				<th>{{=item}}</th>
		
			{{~}}
		</tr>
	</script>

	<script type="text/x-dot-template" id="tbody-dot">
		{{ for(var i in it) { }}
			<tr>
				{{ for(var k in it[i]) { }}
					<td>{{= it[i][k]}}</td>
				{{ } }}
			</tr>
		{{ } }}
	</script>
	<script>
	var showGame="";
	var starttime , endtime;
	function onlyShowGame(o){
		if(o.value != ''){
			$('#datarepair').hide();
		}else {
			$('#datarepair').show();
		}
		showGame=(o.value);
		calendar.fullCalendar('refetchEvents');
		$('#gamesbtn button').removeClass('btn-purple').removeClass('btn-info');
		$(o).addClass('btn-info');
	}

	function fix2(v){
		var v = '00'+v;
		return v.substr(v.length-2,2);
	}

	$(function(){
		/* initialize the calendar
	-----------------------------------------------------------------*/
		
		var date = new Date();
		var d = date.getDate();
		var m = date.getMonth();
		var y = date.getFullYear();
		var dict={};

		var calendar = window.calendar = $('#calendar').fullCalendar({
			buttonText: {
				prev: '<i class="icon-chevron-left"></i>',
				next: '<i class="icon-chevron-right"></i>',
				prevYear: '去年', 
				nextYear: '明年', 
				today:'今天', 
				month:'月', 
				week:'周', 
				day:'日' 
			},
			timeFormat: 'H:mm',
			monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
			dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
		
			header: {
				left: 'prev,next today',
				center: 'title',
				right: 'month,agendaWeek,agendaDay'
			},
			//events: './?app=calendar&act=getEvents&game='+showGame,
			events : function(start, end, callback){
				starttime = start;
				endtime = end;
				

				$.ajax({
					url: './?app=pmcalendar&act=getEvents',
					dataType: 'json',
					data: {
						start: Math.round(start.getTime() / 1000),
						end: Math.round(end.getTime() / 1000),
						game:showGame
					},
					success: function(doc) {
						callback(doc.calendarData);
						// console.log(doc);
						if(doc.gameInfo && doc.gameInfo.length>0){
							var _html = [];
							for(var i=0;i<doc.gameInfo.length;i++){
								var _v = doc.gameInfo[i];
								_html.push("<li>"+ _v.end +" " +_v.event+" " + _v.title +"</li>");
							}
							
							$('#gameinfo ul').html(_html.join(''));
						}else{
							$('#gameinfo ul').html('');
						}
					}
				});
			},

			eventRender: function (event, element) {
				element.html(event.title);
			},
			
			editable: <?=$canEdit?"true":"false"?>,
			eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
				
				dict={id:event.id};
				dict.start = $.fullCalendar.formatDate(event.start,'yyyy-MM-dd');
				dict.end =  $.fullCalendar.formatDate(event.end,'yyyy-MM-dd');
				loading.show();
				$.post('./?app=pmcalendar&act=movevent',dict,function(txt){
					loading.hide();
					if(txt=='1'){
						calendar.fullCalendar('refetchEvents'); 
					}
				});
				return false;
			}
			,
			selectable: true,
			selectHelper: true,
			select: function(start, end, allDay) {
				if("<?=$canEdit?>"!="1")return;
				dict = {};
				console.log('select',start, end, allDay);

				dict.start = $.fullCalendar.formatDate(start,'yyyy-MM-dd');
				dict.end =  $.fullCalendar.formatDate(end,'yyyy-MM-dd');
				
				showEventInfo(dict.start,{
					"save" : {
						"label" : "<i class='icon-check'></i> 保存",
						"className" : "btn-sm btn-success",
						"callback": function() {
							dict.game = $('#game').val();
							dict.allday = 1;

							dict.title = $('#title').val();
							dict.event = $('#event').val();

							if(dict.game=='' || dict.title=='')return;
							
							loading.show();
							$.post('./?app=pmcalendar&act=newevent',dict,function(txt){
								loading.hide();
								if(txt=='1'){
									calendar.fullCalendar('refetchEvents'); 
								}
							});
						}
					} ,
					"close" : {
						"label" : "<i class='icon-remove'></i> Close",
						"className" : "btn-sm"
					} 
				},'new');
				calendar.fullCalendar('unselect');
			}
			,
			eventClick: function(calEvent, jsEvent, view) {
				// if("<?=$canEdit?>"!="1")return;
				console.log(1111);
				console.log('calEvent',calEvent,jsEvent,view);

				dict={};
				$.post('./?app=pmcalendar&act=getEventByid',{id:calEvent.id},function(txt){
					var j = JSON.parse(txt);
					dict.start = j.start;
					dict.end = j.end;
					dict.id = calEvent.id;
					$('#game').val(j.game);
					$('#hour').val(j.shour);
					$('#min').val(j.smin);
					$('#event').val(j.event);
					$('#title').val(j.title);
					hourChange($('#hour'));
				});
				var dstr = $.fullCalendar.formatDate(calEvent.start,'yyyy-MM-dd');
				showEventInfo(dstr,{
					"save" : {
						"label" : "<i class='icon-check'></i> 保存",
						"className" : "btn-sm btn-success",
						"callback": function() {
							
							dict.game = $('#game').val();
							dict.allday = 1;

							dict.event = $('#event').val();
							dict.title = $('#title').val();

							if(dict.game=='' || dict.event=='')return;
							
							loading.show();
							$.post('./?app=pmcalendar&act=modievent',dict,function(txt){
								loading.hide();
								if(txt=='1'){
									calendar.fullCalendar('refetchEvents');
								}
							});
						}
					} ,
					"delete" : {
						"label" : "<i class='icon-trash'></i> 删除事件",
						"className" : "btn-sm btn-danger",
						"callback": function() {
							if(confirm('确认要【删除】这个事件吗？')){
								loading.show();
								$.post('./?app=pmcalendar&act=delevent',{id:calEvent.id},function(txt){
									loading.hide();
									if(txt=='1'){
										calendar.fullCalendar('refetchEvents');
									}
								});
							}
						}
					},
					
					"close" : {
						"label" : "<i class='icon-remove'></i> Close",
						"className" : "btn-sm"
					} 
				},'modify');
			}
			
		});
	
	});

	function datarepair(){
			var dis = $("#data_box").css('display');
			if(dis == 'none'){
				$('#data_box').show();
				$('#calendardiv').hide();
				$.ajax({
					url: './?app=pmcalendar&act=getEvents',
					dataType: 'json',
					data: {
						start: Math.round(starttime.getTime() / 1000),
						end: Math.round(endtime.getTime() / 1000),
						game:showGame,
						type: 'charts'
					},
					
					success:function(res){
						var myChart = echarts.init(document.getElementById('chart'));
						var chartsdata = res.charts;
						
						var option = {
							legend: {},
							tooltip: {},
							grid: {
								left: '0',  
								right: '0',  
								bottom: '5%',  
								containLabel: true  
							},
							color: ['#ff0000','#7030a0'],
							dataset: {
								source: chartsdata
							},
							xAxis: {type: 'category'},
							yAxis: {
								"axisLine":{       //y轴
								"show":true
								},
								"axisTick":{       //y轴刻度线
								"show":true
								},
								"splitLine": {     //网格线
								"show": false
								}
							},
							// Declare several bar series, each will be mapped
							// to a column of dataset.source by default.
							series: [
								{
								type: 'bar',
								itemStyle: {
									normal: {
											label: {
												show: true, //开启显示
												position: 'top', //在上方显示
												textStyle: { //数值样式
													color: '#000',
													fontSize: 13
												}
											}
										}
									}
								},
								{
								type: 'bar',
								itemStyle: {
								normal: {
										label: {
											show: true, //开启显示
											position: 'top', //在上方显示
											textStyle: { //数值样式
												color: '#000',
												fontSize: 13
											}
										}
									}
								}
								}
							]
						};
						myChart.setOption(option);

						var titleAdd = res.table[0];
						titleAdd[0]="";
						var tbdyArr = res.table[1];
						tbdyArr[2][0] = '占比';
						tmpltxt=doT.template(document.getElementById("thead-dot").innerHTML);//生成模板方法
						document.getElementById("thead-title").innerHTML=tmpltxt(titleAdd);//数据渲染

						tmpltxt=doT.template(document.getElementById("tbody-dot").innerHTML);//生成模板方法
						document.getElementById("tbody-content").innerHTML=tmpltxt(tbdyArr);//数据渲染  

					},
					error:function(){
						alert('数据异常,请稍后重试!!!')
					}
				});

			}else {
				$('#data_box').hide();
				$('#calendardiv').show();
			}

		}

	function showEventInfo(start,btns,stype){
		var form = $("<form class=''><label>选择游戏和事件类型 ("+ start +")</label><div class='space-1'></div></form>");
		form.append('<?=gameGameListSelect('game')?>&nbsp<select id="event"><option value="打包">打包</option><option value="版本更新">版本更新</option><option value="修复外网">修复外网</option><option value="上线">上线</option><option value="节点">节点</option></select>');
		form.append("<div class='space-5'></div><label for='form-field-mask-1'>事件内容</label><input class='form-control' id='title' autocomplete=off type=text value='' /> ");
		
		var div = bootbox.dialog({
			message: form,
			buttons: btns
		});
		

		form.on('submit', function(){
			//calEvent.title = form.find("input[type=text]").val();
			//calendar.fullCalendar('updateEvent', calEvent);
			div.modal("hide");
			return false;
		});
	};
	function hourChange(o){
		if($(o).val()=='-1'){
			$('#min').hide();
		}else{
			$('#min').show();
		}
	}

	</script>
	</body>
</html>