<?php namespace AloVoice; ?>
<style>
	.alv_table_lines .nowrp {
		white-space: nowrap;
	}
	.loadingline{
		display:none;
	}
</style>
<center>
	<h3 class="h3 card-body">Правила входящих звонков</h3> 
	<div class="loadingline"></div>
	<a href="#" onClick="addNewinRoute()" id="inroute_add_button" class="btn btn-primary title_line_button"><i class="fa fa-plus"></i> Добавить </a>
</center>
<br/>

<table class="table" id="stats_block_table">
	<thead>
		<tr id="inroutes_table_header"></tr>
	</thead>
	<tbody id="inroutes_table_body"> </tbody> 
</table>


<script>

var delOneDid = function(cid,did,me){
	if(typeof me != 'undefined'){
		$(me).html('<i class="fa fa-spinner fa-spin"></i> Удаление...');
	}
	doAloVoiceCmd('removeInroute', {"cidnum":cid,"extension":did}, function(res) {
		console.log("--== DEL inROUTE RES:",res);
		$("#inroutes-tab").click();
	});
};

var loadAlovoiceSounds = function(){
	
	loadAloVoiceInfo("alovoice_soundfiles_list",function(sounds){
		console.log("--== get sounds RES:",sounds);
	});
}

var loadAlVOperators = function(destination_code){
	$("#destination_code_container").html('<span>Загрузка...</span>');
	loadAloVoiceInfo("alovoice_get_operators_nums",function(operators){
		$("#destination_code_container").html('');
		$("#destination_code_container").append('<select id="inrt_destination_code" class="form-control inrouteinp"></select>');
		$.each( operators, function( num, operator ) {
			var selexttxt = (typeof destination_code != 'undefined' && destination_code==num) ? ' selected' : '';
			$("#inrt_destination_code").append( '<option value="'+num+'"'+selexttxt+'>'+num+' - '+operator.NAME+' '+operator.LAST_NAME+'</option>' );
		});
	});
}

var loadAlVQueues = function(destination_code){
	$("#destination_code_container").html('<span>Загрузка...</span>'); 
	loadAloVoiceInfo("alovoice_get_allqueues",function(queues){
		console.log("--== Loaded All QUEUEs:",queues);
		$("#destination_code_container").html('');
		$("#destination_code_container").append('<select id="inrt_destination_code" class="form-control inrouteinp"></select>');
		$.each( queues, function( queue, strategy ) {
			var selexttxt = (typeof destination_code != 'undefined' && destination_code==queue) ? ' selected' : '';
			$("#inrt_destination_code").append( '<option value="'+queue+'"'+selexttxt+'>'+queue+' - '+strategy+'</option>' );
		});
	});
}

var loadAlVDestinationCodeHTML = function(destination){
	$("#destination_code_container").html('<span>Загрузка...</span>'); 
	doAloVoiceCmd('loadDestinationsCodesListHtml', {dest:destination}, function(result) {
		console.log("--== Loaded List HTML:",result);
		$("#destination_code_container").html(result);
	});
	// loadAloVoiceInfo("alovoice_get_allqueues",function(queues){
		// console.log("--== Loaded All QUEUEs:",queues);
		// $("#destination_code_container").html('');
		// $("#destination_code_container").append('<select id="inrt_destination_code" class="form-control inrouteinp"></select>');
		// $.each( queues, function( queue, strategy ) {
			// var selexttxt = (typeof destination_code != 'undefined' && destination_code==queue) ? ' selected' : '';
			// $("#inrt_destination_code").append( '<option value="'+queue+'"'+selexttxt+'>'+queue+' - '+strategy+'</option>' );
		// });
	// });
}

var route_destination_change = function(me){
	var route_dest = $(me).val();
	console.log("--== Changed dest: ", route_dest);
	loadAlVDestinationCodeHTML(route_dest);
	// if(route_dest=="from-did-direct"){
		// loadAlVOperators();
	// }
	// if(route_dest=="ext-queues"){
		// loadAlVQueues();
	// }
	// if(route_dest=="timeconditions"){
		// $("#destination_code_container").html("");
	// }
	// if(route_dest=="hangup"){
		// $("#destination_code_container").html("");
	// }
}

var addNewoutRoute  = function(vars){
}
var addNewinRoute = function(vars){
	console.log("Begin adding inRoute ........");
	var nowTime = Math.round(new Date().getTime()/1000);
	
	var description = (typeof vars != 'undefined' && typeof vars.description != 'undefined' && vars.description.length > 2) ? vars.description : 'Все '+nowTime;
	var extension = (typeof vars != 'undefined' && typeof vars.extension != 'undefined' && vars.extension.length) ? vars.extension : 'Все';
	var cidnum = (typeof vars != 'undefined' && typeof vars.cidnum != 'undefined' && vars.cidnum.length) ? vars.cidnum : 'Все';
	var mohclass = (typeof vars != 'undefined' && typeof vars.mohclass != 'undefined' && vars.mohclass.length) ? vars.mohclass : 'default';
	var destination = (typeof vars != 'undefined' && typeof vars.destination != 'undefined' && vars.destination.length) ? vars.destination : 'default';
	var destination_code = (typeof vars != 'undefined' && typeof vars.destination_code != 'undefined') ? vars.destination_code : '';
	
	
	doAloVoiceCmd('loadDestinationsList', {}, function(dests) {
		
		console.log("--===Loaded Dests:",dests);
		var allDestsTxt = '<option value="">Выберите направление...</option>';
		 $.each( dests, function( key, value ) {
			var seltxt = (destination==value) ? ' selected' : '';
			allDestsTxt += '<option value="'+key+'"'+seltxt+'>'+value+'</option>';
		});
		
		
			
		aloModal({
			label: "Добавить входящий маршрут",
			body: '<form>'
				
				+'<div class="form-group">'
				+'<input type="text" class="form-control inrouteinp" id="inrt_description" placeholder="Введите названия" value="'+description+'">'
				+'</div>'
				
				+'<div class="form-row">'
					+'<div class="col form-group">'
						+'<label>Звонок на: (DID)</label>'
						+'<input type="text" class="form-control inrouteinp" id="inrt_extension" value="'+extension+'">'
					+'</div>'
					
					+'<div class="col form-group">'
						+'<label>Кто звонит (CallerID)</label>'
						+'<input type="text" class="form-control inrouteinp" id="inrt_cidnum" value="'+cidnum+'">'
					+'</div>'
				+'</div>'
				
				+'<div class="form-group">'
					+'<label>Мелодия в ожидании</label>'
					+'<input type="text" class="form-control inrouteinp" id="inrt_mohclass" value="'+mohclass+'" disabled>'
				+'</div>'
				
				+'<div class="form-group">'
					+'<label>Направление</label>'
					+'<select class="form-control inrouteinp" id="inrt_destination" onChange="route_destination_change(this)">'+allDestsTxt+'</select>'
				+'</div>'
				
				+'<div class="form-group" id="destination_code_container"></div>'
				
				// +'<div class="form-group">'
				// +'<label for="alv_sound_file" class="btn btn-primary afilelabel">Выберите файл записи - *.mp3</label>'
				// +'<input type="file" class="sound-file-input myfileinput" id="alv_sound_file" name="alv_sound_file" required accept=".mp3" onChange="doUpload(this)">'
				// +'</div>'
				
				+'</form>',
			btn: "Сохранить",
			nohide: true,
			callback: function(){
				
				var saveElements = {};
				saveElements["cmd"] = "saveInroute";
				
				$(".inrouteinp").each(function(){
					var inRouteInpId = $(this).attr('id');
					var inRouteInpCode = inRouteInpId.substr(5);
					var inRouteInpVal = $(this).val();
					saveElements[inRouteInpCode] = inRouteInpVal;
				});

				console.log("TEST saveElements: ", saveElements);
				
				$("#alvModalFooter").html('<i class="fa fa-spinner fa-spin"></i> Сохранение...');
				// $("#modalCloseBtn").attr("disabled",true);
				// $("#alvModalSendBtn").attr("disabled",true);
				loadAloVoiceInfo(saveElements,function(res){
					console.log("Save RES: ",res);
					$('#alvModal').modal('hide');
					$("#inroutes-tab").click();
				});

			}
		});
	});
};

var afterLoadPage = function(){
	var isHeadered = false;

	var inroutesUpdate = function(){
	
		
		doAloVoiceCmd('loadInroutesList', {}, function(res) {
         
			console.log("AloVoice Trunks RES:",res);
			
			if(!isHeadered){
				if(typeof res.headers != 'undefined' ){
					isHeadered = true;
					$("#inroutes_table_header").html('');
					
					$.each( res.headers, function( key, value ) {					
						console.log("Each Header:",key, value);
						$("#inroutes_table_header").append('<th id="hd_'+key+'">'+value+'</th>');
					});
				}
			}
			
			if(typeof res.datas != 'undefined' ){
				$("#inroutes_table_body").html('');
				$.each( res.datas, function( irkey, inroute ) {
					console.log("Each Trunk:",inroute);
					/*
					'name' => 'Название',
					'route_cid' => 'Кто звонит',
					'route_did' => 'Куда звонит',
					'route_goto' => 'Назначение',
					'route_moh' => 'Мелодия в ожидании',
					*/
					
					var lineHTML = '<tr class="alv_table_lines" id="inroute_'+irkey+'_" data-cid="'+inroute.route_cid+'" data-did="'+inroute.route_cid+'">'
						+'<td class="nowrp" > <span>'+inroute.name+'</span></td>'
						+'<td class="nowrp" > <b>'+inroute.route_cid+'</b></td>'
						+'<td class="nowrp" >'+inroute.route_did +'</td>'
						+'<td class="nowrp" >'+inroute.route_goto +'</td>'
						+'<td class="nowrp" >'+inroute.route_moh +'</td>'

						+'<td class="nowrp" ><a href="#" onClick="delOneDid(\''+inroute.route_cid+'\',\''+inroute.route_did+'\',this);"><i class="fa fa-trash"></i> Удалить</a></td>'
						+'</tr>';
					
					$("#inroutes_table_body").append(lineHTML);
				});
			}
			
			//setTimeout(donglesUpdate,100000);
		}); 
		
		
	}
	
	inroutesUpdate();
};

</script>