{% extends "old/base.html" %}

{% block header%}
<title>统计列表</title>
<style>
.process_msg{
	margin-left:3px;
	border: 1px solid gray;
	padding:1px;
}
</style>
{% endblock %}

{% block content %}
<div class="bar">
	{% if log_type != 0 %}
	<a href="/log/log_define/list">日志类型列表-></a>
	{% endif %}
	统计列表
	<div class="buttons"><a href="/analysis/statistic/edit?log_type={{log_type}}" class="openDialog">添加</a> <a href="/log/list">返回</a> </div>
</div>

<div class="sub-menu-1">
	<form method="get">
        统计分组:
        <select name="query_result">
            <option value="0">全部</option>
            {% for item in query_result_list %}
            <option value="{{item.id}}" {% if item.id == qs_type %} selected="selected"{% endif %} >{{item.name}}</option>
            {%endfor%}
        </select>

		统计项:
		<select name="log_type">
			<option value="0">全部</option>
			{%for item in list_log%}
			<option value="{{item.id}}"{% if item.id == log_type %} selected="selected"{% endif %}>{{item.name}}</a>
				{%endfor%}
		</select>

		<input type="submit" value="切换" />
	</form>
</div>

<!-- 按钮工具条 -->
<div id='datatable_toolbar'>
			<div class="btn-toolbar pull-right">
				<div class="btn-group ">
					<a id="statistic-execute-btn" class="btn btn-sm btn-info ">
						<i class="icon-play-sign"></i>执行统计
					</a>
				</div>

			</div>
</div>

<table class="table table-bordered datatable" data-group-by-index="[3,4,6,7]">
	<thead>
	<tr>
		<th><input type="checkbox" checkbox-area="checkbox-area"></th>
		<th >ID</th>
		<th >名称</th>
		<th >类型</th>
		<th>表位置</th>
		<th>备注</th>
		<th >自动统计</th>
        <th >执行递减</th> 
		<th >上次执行时间</th>
		<th >操作1</th>
	</tr>
	</thead>
	<tbody id="checkbox-area">
	{%for item in list_model%}
	<tr>
		<td><input type="checkbox" name="statistic_id" {%if item.is_center_log%}is_center="true"{%endif%}  value="{{item.id}}" statistic_name="{{item.name}}"/></td>
		<td>{{item.id}}</td>
		<td><a href="/analysis/query/view?query_name=统计结果记录&statistic_id={{item.id}}&statistic_table={{item.save_table_name}}" class="openDialog">{{item.name}}</a></td>
		<td>{{item.log_typeName}}</td>
		<td>
			{%if item.is_center_log%}
				<b class="blue">中央服</b>
			{%else%}
				<b >分服</b>
			{%endif%} 
		</td>
		<td>{{item.remark|linebreaksbr}}</td>
		{%if item.is_auto_execute%}
		<td class="green">开启</td>
			{%else%}
		<td>关闭</td>
		{%endif%}
		<td>{{item.auto_exec_interval}}</td>
		<td id="last_time_{{item.id}}">{{item.last_exec_time| date("Y-m-d H:i:s") }}</td>
		<td>
			<a href="/analysis/statistic/test_query?statistic_id={{item.id}}" class="openDialog">[测试查询]</a>
			<a href="/analysis/statistic/edit?statistic_id={{item.id}}&log_type={{item.log_type}}&is_copy=true" class="openDialog">[复制]</a>
<!-- 			<a href="/result/clear?statistic_id={{item.id}}" class="red ask">[清除结果]</a> -->
			<a href="/analysis/statistic/edit?statistic_id={{item.id}}&log_type={{item.log_type}}" class="openDialog">[编辑]</a>
			<a href="/analysis/statistic/remove?statistic_id={{item.id}}" class='del' >[删除]</a>

		</td>
	</tr>
	{%endfor%}
	</tbody>
</table>
<div id="statistic-execute-div" class="dialog-div" >
	<div class="row" style="min-width:90%">
		<div class="col-sm-8">
						开始日期:<input type="text" name="sdate" class="Wdate" value="{{sdate}}" />
						-
						结束日期:<input type="text" name="edate" class="Wdate" value="{{edate}}" />
		</div>
		<div class="col-sm-2">
			<label title="统计日期是否按每日分割">
				<input id="cut_date-checkbox"  type="checkbox" >统计日期分割
			</label>

			<label>中央统计:
				<input id="is_center-checkbox" class="ace ace-switch ace-switch-5" type="checkbox">
				<span class="lbl"></span>
			</label>
		</div>
		<div class="col-sm-2">
			<div class="">
				<a id="statistic-execute-sure-btn" class="btn btn-sm btn-success ">
					<i class="cus-accept"></i>确定
				</a>
			</div>
		</div>
		<div class="hr hr-24"></div>
		<div id="statistic-select-server-div" class="col-sm-12">
            {% with group_servers_dict=group_servers_dict %}
			{%include "game_manage/widgets/group_server.html" %}
            {% endwith %}
		</div>

	</div>
</div>

<div id="statistic-process-div" class="dialog-div" >
	<div class="row" style="min-width:90%">
		<table id="statistic-process-table" class="table table-bordered">
			<thead>
				<tr><th>服务器ID</th><th>状态</th></tr>
			</thead>
			<tbody  id="statistic-process-table-cont">

			</tbody>
		</table>
	</div>
</div>


<script type="text/javascript">
var execute_url = '/statistic/execute'


function StatisticExcute(){

	var This = this
	this.statistic_execute_cont = $('#statistic-execute-div')
	this.select_server_cont = $('#statistic-select-server-div')
	this.process_cont =  $('#statistic-process-div')
	this.statistic_process_table = $('#statistic-process-table')
	this.process_table_cont  = $('#statistic-process-table-cont')
	this.is_center = false
	this.params_list = []
	this.statistic_name_map = {}
	this.server_name_map = {0:"中央服"}
	this.sdate_cont = this.statistic_execute_cont.find('[name="sdate"]')
	this.edate_cont = this.statistic_execute_cont.find('[name="edate"]')
	this.runing = false
	// 按日分割日期数组
	function get_date_range_list(){
		var is_cut_date = This.statistic_execute_cont.find('#cut_date-checkbox').is(':checked')
		var date_array = []
		var sdate = This.sdate_cont.val(),
			edate = This.edate_cont.val()
		var sdate_obj = new Date(sdate),
			edate_obj = new Date(edate)
		if ( is_cut_date ){
			var date_diff_val = sdate_obj.dateDiff('d',edate_obj)

			for (var i=1;i<=date_diff_val;i++){
				var sdate_str = sdate_obj.Format('yyyy-MM-dd hh:mm:ss')
				var edate_str = sdate_obj.Format('yyyy-MM-dd 23:59:59')
				date_array.push({'sdate':sdate_str,'edate':edate_str})
				sdate_obj = sdate_obj.dateAdd('d',1)
			}

		}else{
			date_array.push({'sdate':sdate,'edate':edate})
		}
		return date_array


	}


	function make_tr_for_server_id(server_id){
		return '<tr><td>' +This.server_name_map[server_id]+ '</td><td class="process_'+server_id+'"></td></tr>'
	}

	function add_status_to_table(param){
		var statistic_name = This.statistic_name_map[param.statistic_id]
		var span_class_name = 'process_'+ param.server_id + '_' + statistic_name
		var server_process_cont = This.process_table_cont.find('.process_'+param.server_id)
		if (server_process_cont.find('.'+span_class_name).length == 0){
			var span_ele = $('<span>',{class:'process_msg '+ span_class_name,html:statistic_name,num:0})
			server_process_cont.append(span_ele)
		}
	}

	function change_process_status(param,msg,color){
		var statistic_name = This.statistic_name_map[param.statistic_id]
		var process_cont = $('.process_'+param.server_id+'_'+statistic_name)
		var num = parseInt(process_cont.attr('num')) + 1
		process_cont.addClass(color)
		process_cont.html(statistic_name +'(' + num + '):'+ linebreaksbr(msg))
		process_cont.attr('num',num)
	}

	this.get_statistic_ids = function(){
		var statistic_ids = []
		$('#checkbox-area :checked').each(function(i,ele){
			var $ele = $(ele)
			var is_center_statistic = $ele.attr('is_center')
			This.statistic_name_map[ele.value] = $ele.attr('statistic_name')
			if ((This.is_center && is_center_statistic) || (!This.is_center && !is_center_statistic)) {
				statistic_ids.push(ele.value)
			} 
		})
		return statistic_ids
	}

	this.set_param_list = function() {

		var date_array = get_date_range_list()
		console.dir(date_array)

		var server_ids = this.is_center ? [0] : get_server_ids()
		var statistic_ids = this.get_statistic_ids()
		if (statistic_ids.length<=0) {
			alert('没有勾选匹配统计项目!')
			return 
		}

		var param_list = []
		this.statistic_process_table.dataTable().fnDestroy()
		this.statistic_process_table.width('100%')
		this.process_table_cont.html('')
		
		for (var i=0;i<server_ids.length;i++){
			var server_id = server_ids[i]
			this.server_name_map[server_id] = get_server_name(server_id)
			for (var j=0;j<statistic_ids.length;j++){
				var statistic_id = statistic_ids[j]

				for (var ii in date_array){
					var param = {"server_id":server_id,
								"statistic_id":statistic_id
							}
					var date_param = date_array[ii]
					param = $.extend(true,param,date_param)
					console.dir(param)
					param_list.push(param)
				}
			}
			this.process_table_cont.append(make_tr_for_server_id(server_id))
		}
		this.params_list = param_list
		console.dir(param_list)

		return true
	}

	this.change_statistic_type = function(is_center) {
		this.is_center = is_center
		if (is_center) {
			this.select_server_cont.hide()
		} else {
			this.select_server_cont.show()
		}
	}

	this.show = function() {
		this.statistic_execute_cont.dialog({"title":"选择条件:"})
	}

	this.excute = function(){
		
		if (This.set_param_list()) {
			This.process_cont.dialog({"lock":true,"left":"25%","close":function(){
				if(confirm('关闭后将停止运行统计！')){
					This.runing = false
					return true
				} else{
					return false
				}
				
			}})

			console.dir(This.params_list)
			This.runing = true
			This.ajax_do( This.params_list.pop())
		}

	}


	this.check_finish = function(){
			if(This.params_list.length>0) {
					This.ajax_do(This.params_list.pop())
			} else {
				This.runing = false
				$('#statistic-process-table').dataTable()
			}	
	}
	this.ajax_do = function(params,error_count){
		error_count = error_count ? error_count : 0
		if(!params){
			return
		}
		if (!This.runing ){
			return
		}

		add_status_to_table(params)
		$.ajax({
			url: execute_url,
			type: 'POST',
			dataType: 'json',
			data: params,
			timeout:800000,
		})
		.done(function(data) {
			var msg = data.msg,
				color = null
			if (data.code == 0){
				msg = 'OK'
				color = 'green'
			}
			change_process_status(params,msg,color)
			This.check_finish()
		})
		.fail(function(o,x,text) {
			error_count += 1
			if (error_count<1) {
				This.ajax_do(params,error_count)
			} else {
				change_process_status(params,x+'-'+o.responseText,'red')
				This.check_finish()
			}
			
		})		


		
	}


}


var statistic_excute = new StatisticExcute()

$('#statistic-execute-btn').click(function(){
	statistic_excute.show()
	
})

$('#is_center-checkbox').click(function(){
	var is_checked = $(this).is(":checked")
	statistic_excute.change_statistic_type(is_checked)
})

$('#statistic-execute-sure-btn').click(function(){
	statistic_excute.excute()

})

</script>
{% endblock %}