<?php

$idioma = "es";
if (isset($_COOKIE["idioma"])) {
	$idioma = isset($_COOKIE["idioma"]) ? $_COOKIE["idioma"] : "es";
}

?>

<div id="mainTwo" v-cloak>
	<div class="container">
		<div class="col s12" style="padding-top: 0px; margin-top: 75px;">
			<div id="stemen" class="barrita col s12" style="position: absolute;left: 0;right: 0; top:38%; z-index: 100;">
				<center><img id='stemen' v-bind:src="classObject" src="<?= IMG_ADMIN; ?>spinner.gif"></center>
			</div>
			<div class="row black-text card-panel white z-depth-3 hoverable" style="padding-top: 2%;"
				v-bind:style="classObject">
				<div class="input-field col s2">
					<select id="Usuarios" class="browser-default">
					</select>
					<label class="active">{{i18n.gettext("Agentes")}}</label>
				</div>
				<div class="input-field col s2">
					<select id="campanas" class="browser-default">
					</select>
					<label class="active">{{i18n.gettext("Campañas")}}</label>
				</div>
				<div class="col s2">
					<label for="pickDate1">{{i18n.gettext("Fecha")}}</label>
					<input type="text" autocomplete="off" start-date="new Date()" class=" datepicker-here"
						data-range="true" data-multiple-dates-separator=" - " data-date-format="yyyy-mm-dd"
						data-language="<?= $idioma; ?>" class="datepicker-here" id="pickDate" />
				</div>
				<div class="col s2" style="margin-top:1%;">
					<button class="btn btn-success btnW" v-bind:title="traducirFrase('Generar reporte')"
						v-on:click="cargaPeticion()"><i class="material-icons">done</i></button>
					<a class="btn btnW" href="" id="descargar"
						v-bind:title="traducirFrase('Descargar reporte')"><span><i
								class="material-icons">get_app</i></span></a>
				</div>
				<div class="col s12">
					<label for='archived'>
						<input type="checkbox" id="archived" />
						<span>{{traducirFrase("Información archivada")}}</span>
					</label>
				</div>
			</div>

			<div class="card-panel white z-depth-5 hoverable row">
				<h4>{{i18n.gettext("Hoja de Horario por Agente")}}</h4>
				<!-- <div class='col s12'>
					<br>
					<ve-table 
						:columns="columns" 
						:table-data="tableData" 
						:sort-option="sortOption"
						:cell-style-option="cellStyleOption" 
						:border-around="true" 
						:border-x="false"
						:border-y="false"
					></ve-table>
				</div> -->
				<div class="col s12">
					<table>
						<thead>
							<tr>
								<th @click="ordenar('agente')" rowspan="2" colspan="1" class="table-header-cell-class2">
									<span style="display: flex; align-items: center; justify-content: center;">
										Agente
										<i class="material-icons">
											{{ iconKey("agente") }}
										</i>
									</span>
								</th>
								<th @click="ordenar('nombre')" rowspan="2" colspan="1" class="table-header-cell-class1">
									<span style="display: flex; align-items: center; justify-content: center;">
									Nombre
									<i class="material-icons">
										{{ iconKey("nombre") }}
									</i>
									</span>
								</th>
								<th rowspan="1" colspan="2" class="table-header-cell-class9">Tiempo en llamada</th>
								<th rowspan="1" colspan="2" class="table-header-cell-class3">Tiempo en pausa</th>
								<th rowspan="1" colspan="2" class="table-header-cell-class5">Tiempo en espera</th>
								<th rowspan="1" colspan="2" class="table-header-cell-class4">Tiempo en calificación</th>
								<th rowspan="1" colspan="2" class="table-header-cell-class6">Horario</th>
								<th @click="ordenar('total_format')" rowspan="2" colspan="1" class="table-header-cell-class">
									<span style="display: flex; align-items: center; justify-content: center;">
									Tiempo total conectado
									<i class="material-icons">
										{{ iconKey("total_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('jornada_format')" rowspan="2" colspan="1" class="table-header-cell-class7">
									<span style="display: flex; align-items: center; justify-content: center;">
									Jornada laboral
									<i class="material-icons">
										{{ iconKey("jornada_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('llamadas')" rowspan="2" colspan="1" class="table-header-cell-class8">
									<span style="display: flex; align-items: center; justify-content: center;">
									Total de Llamadas realizadas
									<i class="material-icons">
										{{ iconKey("llamadas") }}
									</i>
									</span>
								</th>
							</tr>
							<tr>
								<th @click="ordenar('talk_format')" rowspan="1" colspan="1" class="table-header-cell-class9">
									<span style="display: flex; align-items: center; justify-content: center;">
									Total
									<i class="material-icons">
										{{ iconKey("talk_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('talk_prom_format')" rowspan="1" colspan="1" class="table-header-cell-class9">
									<span style="display: flex; align-items: center; justify-content: center;">
									Promedio
									<i class="material-icons">
										{{ iconKey("talk_prom_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('pause_format')" rowspan="1" colspan="1"  class="table-header-cell-class3">
									<span style="display: flex; align-items: center; justify-content: center;">
									Total
									<i class="material-icons">
										{{ iconKey("pause_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('pause_prom_format')" rowspan="1" colspan="1"  class="table-header-cell-class3">
									<span style="display: flex; align-items: center; justify-content: center;">
									Promedio
									<i class="material-icons">
										{{ iconKey("pause_prom_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('wait_format')" rowspan="1" colspan="1"  class="table-header-cell-class5">
									<span style="display: flex; align-items: center; justify-content: center;">
									Total
									<i class="material-icons">
										{{ iconKey("wait_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('wait_prom_format')" rowspan="1" colspan="1"  class="table-header-cell-class5">
									<span style="display: flex; align-items: center; justify-content: center;">
									Promedio
									<i class="material-icons">
										{{ iconKey("wait_prom_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('wrapup_format')" rowspan="1" colspan="1"  class="table-header-cell-class4">
									<span style="display: flex; align-items: center; justify-content: center;">
									Total
									<i class="material-icons">
										{{ iconKey("wrapup_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('wrapup_prom_format')" rowspan="1" colspan="1"  class="table-header-cell-class4">
									<span style="display: flex; align-items: center; justify-content: center;">
									Promedio
									<i class="material-icons">
										{{ iconKey("wrapup_prom_format") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('primer_login')" rowspan="1" colspan="1"  class="table-header-cell-class6">
									<span style="display: flex; align-items: center; justify-content: center;">
									Primer Login
									<i class="material-icons">
										{{ iconKey("primer_login") }}
									</i>
									</span>
								</th>
								<th @click="ordenar('ultimo_logout')" rowspan="1" colspan="1"  class="table-header-cell-class6">
									<span style="display: flex; align-items: center; justify-content: center;">
									Último logout
									<i class="material-icons">
										{{ iconKey("ultimo_logout") }}
									</i>
									</span>
								</th>
							</tr>
						</thead>
						<tbody v-for="(item, i) in datos" class="tbody-class">
							<tr @click="mostrarFechas(i)" >
								<td v-for="(key, k) in headerKeys" :class="'table-body-cell-class ' + (i % 2 == 0 ? '' : 'table-body-cell-class1')">
									<span style="display: flex; justify-content: center; align-items: center;">
										{{ item[key] ?? "" }}
										<i class="material-icons" v-if="k == 0">
											{{ datos.mostrarFechas ? 'arrow_drop_up' : 'arrow_drop_down'}}
										</i>
									</span>
								</td>
							</tr>
							<tr v-if="item.mostrarFechas" v-for="(dia, j) in item.porDia" class="tr-alt">
								<td v-for="key in headerKeys" :class="'table-body-cell-class ' + ((i + j) % 2 == 0 ? '' : 'table-body-cell-class2')">
									{{ dia[key] ?? "" }}
								</td>
							</tr>
						</tbody>
					</table>
				</div>
				<div
					id="containerDona1" 
					class="col s12 tablitasW"
					style="margin-top:0;height:400px;padding-bottom: 2rem;"
				></div>
			</div>
		</div>
	</div>
</div>

<!-- END MAIN -->
<!-- //////////////////////////////////////////////////////////////////////////// -->
<!-- START FOOTER -->
<?php require_once UTILS_PATH . 'footer.php'; ?>
<!-- END FOOTER -->
<!-- ================================================
	Scripts
	================================================ -->
<!-- jQuery Library -->
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>jquery-3.2.1.min.js"></script>
<!--materialize js-->
<script type="text/javascript" src="<?= JS_ADMIN; ?>materialize.min.js"></script>
<!--scrollbar-->
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>perfect-scrollbar/perfect-scrollbar.min.js"></script>
<!-- chartjs -->
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>chartjs/chart.min.js"></script>
<!-- sparkline -->
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>sparkline/jquery.sparkline.min.js"></script>
<!-- google map api -->
<script type="text/javascript" src="<?= JS_ADMIN; ?>maps.js"></script>
<!--jvectormap-->
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<script type="text/javascript" src="<?= VENDORS_ADMIN; ?>jvectormap/vectormap-script.js"></script>
<!--google map-->

<!--plugins.js - Some Specific JS codes for Plugin Settings-->
<script type="text/javascript" src="<?= JS_ADMIN; ?>plugins.js"></script>
<!--card-advanced.js - Page specific JS-->
<script type="text/javascript" src="<?= JS_ADMIN; ?>scripts/dashboard-analytics.js"></script>
<!--custom-script.js - Add your own theme custom JS
	<script type="text/javascript" src="<?= JS_ADMIN; ?>custom-script.js"></script>-->
<script src="<?= JS_ADMIN; ?>vue.js"></script>
<script src="<?= JS_ADMIN; ?>Chart.min.js"></script>
<script src="<?= JS_ADMIN; ?>gauge.min.js"></script>
<script src="<?= JS_ADMIN; ?>raphael.js"></script>
<script src="<?= JS_ADMIN; ?>justgage.js"></script>
<script src="<?= JS_ADMIN; ?>datepicker.js"></script>
<script src="<?= JS_ADMIN; ?>i18n/datepicker.es.js"></script>
<script src="<?= JS_ADMIN; ?>i18n/datepicker.en.js"></script>

<script src="<?= LIB_JS; ?>highcharts/stock/highstock.js"></script>
<script src="<?= LIB_JS; ?>highcharts/highcharts-more.js"></script>
<script src="<?= LIB_JS; ?>highcharts/stock/modules/data.js"></script>
<script src="<?= LIB_JS; ?>highcharts/stock/modules/exporting.js"></script>
<script src="<?= LIB_JS; ?>highcharts/highcharts-3d.js"></script>
<script src="<?= LIB_JS; ?>highcharts/modules/cylinder.js"></script>
<script src="<?= LIB_JS; ?>highcharts/modules/funnel.js"></script>
<script src="<?= LIB_JS; ?>highcharts/modules/more.js"></script>
<script src="<?= LIB_JS; ?>highcharts/modules/pyramid.js"></script>
<script src="<?= LIB_JS; ?>highcharts/modules/exporting.js"></script>
<script src="<?= LIB_JS; ?>highcharts/modules/export-data.js"></script>

<script src="<?= VENDORS_ADMIN; ?>easytable/easytable.js"></script>

<script>
	var a = document.getElementById('idioma');
	if (a.value == "es") {
		<?php if (defined("BANDERA_ES")) { ?>
			document.getElementById('banderaPais').innerHTML = '<span class="flag-icon flag-icon-<?php echo BANDERA_ES; ?>"></span>&nbsp;';
		<?php } else { ?>
			document.getElementById('banderaPais').innerHTML = '<span class="flag-icon flag-icon-mx"></span>&nbsp;';
		<?php } ?>
	} else {
		document.getElementById('banderaPais').innerHTML = '<span class="flag-icon flag-icon-um"></span>&nbsp;';
	}

	var Inicial = true;

	function dIni(date) {
		return date.slice(0, 10);
	}

	function dEnd(date) {
		var fecF = date.slice(13, 23);

		if (fecF == "") {
			fecF = date.slice(0, 10)
		}

		return fecF;
	}

	var app = new Vue({
		el: '#main',
		data: {
			ls: localStorage.getItem('background'),
			flagCampanas: true,
			flagUsuario: false,
			flagPeticion: false,
			Registro: {
				Resultados: [],
				TotalTiempoCharla: 0,
				TotalTiempoPausa: 0,
				TotalTiempoWrapup: 0,
				TotalTiempoEspera: 0,
				TotalTiempoEnActivo: 0,
			},
			i18n: i18n,
			sortOption: {
				sortAlways: true,
				sortChange: (params) => {
					console.log("sortChange::", params);
					app.sortChange(params);
				},
			},
			cellStyleOption: {
				headerCellClass: ({
					column,
					rowIndex
				}) => {
					return {
						"agente": "table-header-cell-class2",
						"nombre": "table-header-cell-class1",
						"tiempoenllamada": "table-header-cell-class9",
						"teltotal": "table-header-cell-class9",
						"telpromedio": "table-header-cell-class9",
						"tiempoenpausa": "table-header-cell-class3",
						"teptotal": "table-header-cell-class3",
						"teppromedio": "table-header-cell-class3",
						"tiempoenespera": "table-header-cell-class5",
						"teetotal": "table-header-cell-class5",
						"teepromedio": "table-header-cell-class5",
						"tiempoencalificacion": "table-header-cell-class4",
						"tectotal": "table-header-cell-class4",
						"tecpromedio": "table-header-cell-class4",
						"horario": "table-header-cell-class6",
						"primerilogin": "table-header-cell-class6",
						"ultimologout": "table-header-cell-class6",
						"totalenactivo": "table-header-cell-class",
						"totalllamadasrealizadas": "table-header-cell-class7",
						"": "table-header-cell-class8",
					}[column.field] ?? "teal"
				},
				bodyCellClass: ({
					row,
					column,
					rowIndex
				}) => {
					if (rowIndex % 2 == 1) {
						return "table-body-cell-class1";
					}

					return ""
				},
			},
			columns: [
				{
					field: "agente",
					key: "agente",
					title: "Agente",
					width: "10%",
					sortBy: "",
				},
				{
					field: "nombre",
					key: "nombre",
					title: "Nombre",
					width: "10%",
					sortBy: "",
				},
				{
					title: "Tiempo en Llamada",
					children: [{
							field: "teltotal",
							key: "teltotal",
							title: "Total",
							sortBy: ""
						},
						{
							field: "telpromedio",
							key: "telpromedio",
							title: "Promedio",
							width: "6%",
							sortBy: ""
						},
					],
					field: "tiempoenllamada"
				},
				{
					title: "Tiempo en Pausa",
					children: [{
							field: "teptotal",
							key: "teptotal",
							title: "Total",
							sortBy: ""
						},
						{
							field: "teppromedio",
							key: "teppromedio",
							title: "Promedio",
							width: "6%",
							sortBy: ""
						},
					],
					field: "tiempoenpausa"
				},
				{
					title: "Tiempo en Espera",
					children: [{
							field: "teetotal",
							key: "teetotal",
							title: "Total",
							sortBy: ""
						},
						{
							field: "teepromedio",
							key: "teepromedio",
							title: "Promedio",
							width: "6%",
							sortBy: ""
						},
					],
					field: "tiempoenespera"
				},
				{
					title: "Tiempo en Calificación",
					children: [{
							field: "tectotal",
							key: "tectotal",
							title: "Total",
							sortBy: ""
						},
						{
							field: "tecpromedio",
							key: "tecpromedio",
							title: "Promedio",
							width: "6%",
							sortBy: ""
						},
					],
					field: "tiempoencalificacion"
				},
				{
					title: "Horario",
					children: [{
							field: "primerlogin",
							key: "primerilogin",
							title: "Primer Login",
							width: "12%",
							sortBy: ""
						},
						{
							field: "ultimologout",
							key: "ultimologout",
							title: "Último Logout",
							width: "12%",
							sortBy: ""
						},
					],
					field: "horario"
				},
				{
					field: "totalenactivo",
					key: "totalenactivo",
					title: "Tiempo Total Conectado",
					sortBy: ""
				},
				{
					field: "jornadalaboral",
					key: "jornadalaboral",
					title: "Jornada laboral",
					sortBy: ""
				},
				{
					field: "totalllamadasrealizadas",
					key: "totallamadasrealizadas",
					title: "Total de Llamadas Realizadas",
					width: "8%",
					sortBy: ""
				},

			],
			tableData: [],

			// ? Nueva tabla
			columnas: {
				"agente": ["agente", "s", 'asc'],
				"nombre": ["nombre", "s", 'asc'],
				"talk_format": ["talk", "n", 'asc'],
				"talk_prom_format": ["talk_prom", "n", 'asc'],
				"pause_format": ["pause", "n", 'asc'],
				"pause_prom_format": ["pause_prom", 'asc'],
				"wait_format": ["wait", "n", 'asc'],
				"wait_prom_format": ["wait_prom", "n", 'asc'],
				"wrapup_format": ["wrapup", "n", 'asc'],
				"wrapup_prom_format": ["wrapup_prom", "n", 'asc'],
				"primer_login": ["primer_login", "d", 'asc'],
				"ultimo_logout": ["ultimo_logout", "d", 'asc'],
				"total_format": ["total", "n", 'asc'],
				"jornada_format": ["jornada", "n", 'asc'],
				"llamadas": ["llamadas", "n", 'asc']
			},
			datos: []
		},
		mounted: function() {
			var today = new Date();
			var dd = today.getDate();
			var mm = today.getMonth() + 1; //January is 0!
			var yyyy = today.getFullYear();
			if (dd < 10) {
				dd = '0' + dd;
			}
			if (mm < 10) {
				mm = '0' + mm;
			}
			var today = yyyy + '-' + mm + '-' + dd;
			$('#pickDate').val(today + " - " + today);

			M.toast({
				html: i18n.gettext("Cargando datos, por favor espere") + "."
			});
			this.getUsuarios();
			this.getCampanas();
		},
		methods: {
			formatDate: function(time) {
				if (time == null) {
					time = 0;
				}
				time = parseFloat(time);
				var Horas = Math.floor(time / 3600);
				time -= Horas * 3600;
				var Minutos = Math.floor(time / 60);
				time -= Minutos * 60;
				var Segundos = Math.floor(time);
				time = (Horas < 10 ? "0" + Horas : Horas) + ":" + (Minutos < 10 ? "0" + Minutos : Minutos) + ":" + (Segundos < 10 ? "0" + Segundos : Segundos);
				return time;
			},
			sortChange(params) {  
				let sortType = 1;
				let sortKey = "agente";
				Object.keys(params).forEach(k => {
					if (params[k] !== "") {
						sortType = params[k] == "asc" ? 1 : -1
						sortKey = k
					}
				})
				app.tableData.sort(function (a, b) {
					if (a.end) return sortType
					if (b.end) return -1 * sortType

					switch(sortKey) {
						case "agente":
							return (a.localeCompare(b.localeCompare)) * sortType
					}
				})
				if (params.agente) {
					if (params.agente === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return a.agente.localeCompare(b.agente);
						});
					} else {
						app.tableData.sort((a, b) => {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							if (a.agente > b.agente)
								return -1;
							if (a.agente < b.agente)
								return 1;
							return 0;
						});
					}
				} else if (params.nombre) {
					if (params.nombre === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return a.nombre.localeCompare(b.nombre);
						});
					} else {
						app.tableData.sort((a, b) => {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							if (a.nombre > b.nombre)
								return -1;
							if (a.nombre < b.nombre)
								return 1;
							return 0;
						});
					}
				} else if (params.teltotal) {
					if (params.teltotal === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.teltotal2) - parseInt(b.teltotal2);
						});
					}
					if (params.teltotal === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.teltotal2) - parseInt(a.teltotal2);
						});
					}
				} else if (params.telpromedio) {
					if (params.telpromedio === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseFloat(a.telpromedio2) - parseFloat(b.telpromedio2);
						});
					}
					if (params.telpromedio === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseFloat(b.telpromedio2) - parseFloat(a.telpromedio2);
						});
					}
				} else if (params.teptotal) {
					if (params.teptotal === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.teptotal2) - parseInt(b.teptotal2);
						});
					}
					if (params.teptotal === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.teptotal2) - parseInt(a.teptotal2);
						});
					}
				} else if (params.teppromedio) {
					if (params.teppromedio === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.teppromedio2) - parseInt(b.teppromedio2);
						});
					}
					if (params.teppromedio === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.teppromedio2) - parseInt(a.teppromedio2);
						});
					}
				} else if (params.teetotal) {
					if (params.teetotal === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.teetotal2) - parseInt(b.teetotal2);
						});
					}
					if (params.teetotal === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.teetotal2) - parseInt(a.teetotal2);
						});
					}
				} else if (params.teepromedio) {
					if (params.teepromedio === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.teepromedio2) - parseInt(b.teepromedio2);
						});
					}
					if (params.teepromedio === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.teepromedio2) - parseInt(a.teepromedio2);
						});
					}
				} else if (params.tectotal) {
					if (params.tectotal === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.tectotal2) - parseInt(b.tectotal2);
						});
					}
					if (params.tectotal === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.tectotal2) - parseInt(a.tectotal2);
						});
					}
				} else if (params.tecpromedio) {
					if (params.tecpromedio === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.tecpromedio2) - parseInt(b.tecpromedio2);
						});
					}
					if (params.tecpromedio === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.tecpromedio2) - parseInt(a.tecpromedio2);
						});
					}
				} else if (params.totalenactivo) {
					if (params.totalenactivo === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.totalenactivo2) - parseInt(b.totalenactivo2);
						});
					}
					if (params.totalenactivo === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.totalenactivo2) - parseInt(a.totalenactivo2);
						});
					}
				} else if (params.jornadalaboral) {
					if (params.jornadalaboral === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}

							return parseInt(a.jornadalaboral2) - parseInt(b.jornadalaboral2);
						});
					}
					if (params.jornadalaboral === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}

							return parseInt(b.jornadalaboral2) - parseInt(a.jornadalaboral2);
						});
					}
				} else if (params.totalllamadasrealizadas) {
					if (params.totalllamadasrealizadas === "asc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(a.totalllamadasrealizadas) - parseInt(b.totalllamadasrealizadas);
						});
					}
					if (params.totalllamadasrealizadas === "desc") {
						app.tableData.sort(function(a, b) {
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return parseInt(b.totalllamadasrealizadas) - parseInt(a.totalllamadasrealizadas);
						});
					}
				} else if (params.primerlogin) {
					if (params.primerlogin === "asc") {
						app.tableData.sort(function(a, b) {
							let dateAArray = app.getDateValues(a.primerlogin);
							let dateA = new Date(dateAArray[0], dateAArray[1], dateAArray[2], dateAArray[3], dateAArray[4], dateAArray[5]);
							let dateBArray = app.getDateValues(b.primerlogin);
							let dateB = new Date(dateBArray[0], dateBArray[1], dateBArray[2], dateBArray[3], dateBArray[4], dateBArray[5]);
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return dateA - dateB

						});
					}
					if (params.primerlogin === "desc") {
						app.tableData.sort(function(a, b) {
							let dateAArray = app.getDateValues(a.primerlogin);
							let dateA = new Date(dateAArray[0], dateAArray[1], dateAArray[2], dateAArray[3], dateAArray[4], dateAArray[5]);
							let dateBArray = app.getDateValues(b.primerlogin);
							let dateB = new Date(dateBArray[0], dateBArray[1], dateBArray[2], dateBArray[3], dateBArray[4], dateBArray[5]);
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return dateB - dateA
						});
					}
				} else if (params.ultimologout) {
					if (params.ultimologout === "asc") {
						app.tableData.sort(function(a, b) {
							let dateAArray = app.getDateValues(a.ultimologout);
							let dateA = new Date(dateAArray[0], dateAArray[1], dateAArray[2], dateAArray[3], dateAArray[4], dateAArray[5]);
							let dateBArray = app.getDateValues(b.ultimologout);
							let dateB = new Date(dateBArray[0], dateBArray[1], dateBArray[2], dateBArray[3], dateBArray[4], dateBArray[5]);
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return dateA - dateB

						});
					}
					if (params.ultimologout === "desc") {
						app.tableData.sort(function(a, b) {
							let dateAArray = app.getDateValues(a.ultimologout);
							let dateA = new Date(dateAArray[0], dateAArray[1], dateAArray[2], dateAArray[3], dateAArray[4], dateAArray[5]);
							let dateBArray = app.getDateValues(b.ultimologout);
							let dateB = new Date(dateBArray[0], dateBArray[1], dateBArray[2], dateBArray[3], dateBArray[4], dateBArray[5]);
							if (a.lostotales) {
								return 1
							}
							if (b.lostotales) {
								return -1
							}
							return dateB - dateA
						});
					}
				}
			},
			getUsuarios: function() {
				if (!app.flagUsuario) {
					var Anterior = $("#Usuarios").val();
					if (Anterior == null || Anterior == '') {
						Anterior = -1;
					}
					app.flagUsuario = true;
					$.ajax({
						url: "<?= MODULOS; ?>usuarios/getAgentSelect",
						type: "GET",
						dataType: "text",
						async: false,
						success: function(result) {
							var res = JSON.parse(result);
							if (res.Estado == 'ok') {
								$("#Usuarios").html("<option value='-1' id='todosus'>" + traducirFrase("Todos los agentes") + "</option>");
								for (var i = 0; i < res.usuarios.length; i++) {
									var otraFlag = false;
									if (Anterior === res.usuarios[i].user) {
										otraFlag = true;
									}
									if (Anterior == "" || Anterior == null) {
										Anterior = res.usuarios[i].user;
										otraFlag = true;
									}
									$("#Usuarios").append("<option value='" + res.usuarios[i].user + "'>" + res.usuarios[i].user + "--" + res.usuarios[i].full_name + "</option>");
								}
								$("#Usuarios").val(Anterior);
								app.flagUsuario = false;
							} else {
								M.toast({
									html: res.Descripcion
								});
							}
						},
						error: function(error) {
							console.log(error);
						}
					});
				}
			},
			getDateValues: function(date) {
				let year = date.slice(0, 4);
				let month = date.slice(5, 7);
				let day = date.slice(8, 10);
				let hour = date.slice(11, 13);
				let minute = date.slice(14, 16);
				let second = date.slice(17, 19);

				return [parseInt(year), parseInt(month), parseInt(day), parseInt(hour), parseInt(minute), parseInt(second)]

			},
			getCampanas: function() {
				if (app.flagCampanas) {
					var Anterior = $("#campanas").val();
					if (Anterior == null || Anterior == '') {
						Anterior = -1;
					}
					app.flagCampanas = false;
					$.ajax({
						url: "/<?= RUTA_MAESTRA; ?>/index.php/campanas/getCampaignsSelect",
						type: "GET",
						dataType: "text",
						async: false,
						success: function(result) {
							app.flagCampanas = true;
							var resp = JSON.parse(result)
							if (resp.Estado == 'ok') {
								$("#campanas").html("<option value='-1' id='todascamp'>Todas las campañas</option>");
								cambioManual("todascamp", "Todas las campañas");
								for (var i = 0; i < resp.Campanas.length; i++) {
									$("#campanas").append("<option value='" + resp.Campanas[i].campaign_id + "'>" + resp.Campanas[i].campaign_name +
										"</option>");
								}
								$("#campanas").val(Anterior);
							} else {
								M.toast({
									'html': resp.Descripcion
								});
							}
						},
						error: function(error) {
							console.log(error);
						}
					});
				}
			},
			cargaPeticion: function() {

				if (!app.flagPeticion) {
					app.flagPeticion = true;
					$('.barrita').show();
					var parametros = {
						fechaInicial: dIni($("#pickDate").val()),
						fechaFinal: dEnd($("#pickDate").val()),
						agente: $("#Usuarios").val(),
						campana: $("#campanas").val(),
						campoOrdenamiento: "nombre",
						tipoOrdenamiento: "DESC",
						archived: document.getElementById('archived').checked ? '1' : '0'
					};

					const [fechaInicial, fechaFinal] = $('#pickDate').val().split(' - ')

					$("#descargar").attr("href", "<?php echo MODULOS; ?>reporteHorarioAgente/agentTimeSheet?csv=true&fechaInicial=" + fechaInicial + "&fechaFinal=" + (fechaFinal ? fechaFinal : fechaInicial) + "&agente=" + $("#Usuarios").val() + "&campana=" + $("#campanas").val() + '&archived=' + parametros.archived);
					$.ajax({
						url: "<?php echo MODULOS; ?>reporteHorarioAgente/agentTimeSheet",
						type: "GET",
						dataType: "text",
						data: parametros,
						success: function(result) {
							var res = JSON.parse(result);
							console.log(res);
							if (res.Estado == 'ok') {
								$("#titulos").html("");

								console.log("WolfEsp: ");
								console.log(res);

								app.Registro = res;
								var bla;

								console.log("Ay drake");
								console.log(app.Registro.Resultados);

								app.tableData = [];

								app.datos = res.Resultados.registros.map(v => Object.assign(v, {
									mostrarFechas: false
								}))
								Object.keys(app.columnas).forEach(k => {
									app.columnas[k][2] = 'asc';
								})

								creaPie1(app.datos.map(v => ({
									nombre: v.nombre,
									total: v.llamadas
								})))

								app.datos.push(Object.assign(res.Resultados.total, {
									end: true
								}))

								/*
									app.Registro.Resultados.forEach(element => {
										let totalJornada = 0
										element.HoraEntradaSalida.forEach(v => {
											if (v.Diferencia.split(":")[0] > 24) {
												return;
											}

											totalJornada += v.DiferenciaTiempo
										})


										app.tableData.push({
											agente: element.usuario ? element.usuario : 'Sin información',
											nombre: element.nombre ? element.nombre : 'Sin información',
											teltotal: app.formatDate(element.tiempoCharla),
											telpromedio: app.formatDate(element.promedioTiempoCharla),
											teptotal: app.formatDate(element.tiempoPausa),
											teppromedio: app.formatDate(element.promedioTiempoPausa),
											teetotal: app.formatDate(element.tiempoEspera),
											teepromedio: app.formatDate(element.promedioTiempoEspera),
											tectotal: app.formatDate(element.tiempoWrapup),
											tecpromedio: app.formatDate(element.promedioTiempoWrapup),
											primerlogin: element.HoraEntradaSalida[0] ? element.HoraEntradaSalida[0].minimo : '',
											ultimologout: element.HoraEntradaSalida[0] ? element.HoraEntradaSalida[0].maximo : '',
											totalenactivo: app.formatDate(element.tiempoTotalEnActivo),
											totalllamadasrealizadas: element.total,
											teltotal2: element.tiempoCharla,
											telpromedio2: element.promedioTiempoCharla,
											teptotal2: element.tiempoPausa,
											teppromedio2: element.promedioTiempoPausa,
											teetotal2: element.tiempoEspera,
											teepromedio2: element.promedioTiempoEspera,
											tectotal2: element.tiempoWrapup,
											tecpromedio2: element.promedioTiempoWrapup,
											totalenactivo2: element.tiempoTotalEnActivo,
											//Debemos validar que el formato de HH:MM:SS no sea mayor a 24 horas, si es mayor a 24 horas, se debe mostrar un mensaje de error
											jornadalaboral: (element.HoraEntradaSalida.length == 0) ? "No se pudo calcular" : app.formatDate(totalJornada),
											jornadalaboral2: (element.HoraEntradaSalida.length == 0) ? "No se pudo calcular" : totalJornada,
										});
									});

									if (app.tableData.length > 0) {
										app.tableData.push({
											agente: "",
											nombre: "",
											teltotal: app.formatDate(app.Registro.TotalTiempoCharla),
											telpromedio: "",
											teppromedio: "",
											teptotal: app.formatDate(app.Registro.TotalTiempoPausa),
											teppromedio: "",
											teetotal: app.formatDate(app.Registro.TotalTiempoEspera),
											teepromedio: "",
											tectotal: app.formatDate(app.Registro.TotalTiempoWrapup),
											tecpromedio: "",
											primerlogin: "",
											ultimologout: "",
											totalenactivo: app.formatDate(app.Registro.TotalTiempoEnActivo),
											totalllamadasrealizadas: "",
											lostotales: true
										});
									}

									creaPie1(res.Resultados);
								*/

								function cambiarAOscuro() {

									for (let i = 0; i < bla.length; i++) {
										bla[i].classList.remove('white');
										bla[i].classList.add('grey');
										bla[i].classList.add('lighten-1');
										bla[i].style.filter = 'invert(100%)';
									}
								}

								if (localStorage.getItem('background') == "black") {
									bla = document.getElementsByClassName('card-panel')
									bla = Array.prototype.slice.call(bla)
									cambiarAOscuro();
								}
								$('.barrita').hide();

							} else {
								M.toast({
									html: resp.Descripcion
								});
							}
							app.flagPeticion = false;
						},
						error: function(error, textStatus, err) {
							console.log(error);
							console.log(textStatus);
							console.log(err);
						}
					});
				}
			},
			ordenar(key) {
				let [realKey, dataType, sortType] = this.columnas[key]
				sortType = sortType == 'asc' ? -1 : 1;

				Object.keys(this.columnas).forEach(k => {
					this.columnas[k][2] = 'asc'
				})
				this.columnas[key][2] = sortType < 0 ? 'desc' : 'asc'

				console.log(sortType, this.columnas)

				this.datos.sort((a, b) => {
					if (a.end) return 1
					if (b.end) return 1

					if (dataType === "n") {
						return (a[realKey] - b[realKey]) * sortType
					}

					return ("" + a[realKey]).localeCompare("" + b[realKey]) * sortType
				})
			},
			mostrarFechas(item) {
				this.datos = this.datos.map((v, i) => Object.assign(v, {
					mostrarFechas: i === item ? !v.mostrarFechas : v.mostrarFechas
				}))
			},
			iconKey(key) {
				return this.columnas[key][2] == 'asc' ? 'arrow_drop_up' : 'arrow_drop_down'
			}
		},
		computed: {
			classObject: function() {
				if (this.ls == 'black') {
					return {
						filter: 'invert(100%)'
					}
				}
			},
			headerKeys: function() {
				return Object.keys(this.columnas)
			}
		},
		created: function() {
			$('.barrita').hide();
			app.getUsuarios();
			app.getCampanas();
		}
	});
	if (localStorage.getItem('background') == "black") {
		document.getElementById('stemen').style.filter = 'invert(100%)'
	}

	setInterval(function() {
		app.getUsuarios();
		app.getCampanas();
		if (document.getElementById("pickDate").value == "") {
			var d = new Date();
			document.getElementById("fechaIni").value = d.getFullYear() + "-" + ((d.getMonth() + 1) >= 10 ? (d.getMonth() + 1) :
				("0" + (d.getMonth() + 1))) + "-" + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
			document.getElementById("fechaFin").value = d.getFullYear() + "-" + ((d.getMonth() + 1) >= 10 ? (d.getMonth() + 1) :
				("0" + (d.getMonth() + 1))) + "-" + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
		}

	}, 60000);
	app.getUsuarios();
	app.getCampanas();
	if (document.getElementById("pickDate").value == "") {
		var d = new Date();
		document.getElementById("fechaIni").value = d.getFullYear() + "-" + ((d.getMonth() + 1) >= 10 ? (d.getMonth() + 1) :
			("0" + (d.getMonth() + 1))) + "-" + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
		document.getElementById("fechaFin").value = d.getFullYear() + "-" + ((d.getMonth() + 1) >= 10 ? (d.getMonth() + 1) :
			("0" + (d.getMonth() + 1))) + "-" + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
	}
	app.cargaPeticion();

	function creaPie1(data) {

		var dataE = [];

		console.log("WolfRep: ");
		console.log(data);

		$.each(data, function(index, value) {

			dataE.push({
				name: value.nombre,
				y: parseInt(value.total)
			});



		});

		/*Highcharts.chart('containerDona1', {
			chart: {
				type: 'pie',
				options3d: {
					enabled: true,
					alpha: 45,
					beta: 0
				}
			},
			title: {
				text: ' '
			},
			tooltip: {
				pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
			},
			plotOptions: {
				pie: {
					allowPointSelect: true,
					cursor: 'pointer',
					depth: 35,
					dataLabels: {
						enabled: true,
						format: '{point.name}'
					}
				}
			},
			series: [{
				type: 'pie',
				name: 'Porcentaje',
				data: dataE
			}]
		});*/

		Highcharts.chart('containerDona1', {
			chart: {
				type: 'pyramid3d',
				options3d: {
					enabled: true,
					alpha: 10,
					depth: 50,
					viewDistance: 50
				}
			},
			title: {
				text: ' '
			},
			plotOptions: {
				series: {
					dataLabels: {
						enabled: true,
						format: '',
						allowOverlap: true,
						x: 10,
						y: -5
					},
					width: '30%',
					height: '80%',
					center: ['50%', '45%']
				}
			},
			series: [{
				name: traducirFrase("Agente"),
				data: dataE
			}]
		});


	}
</script>

</body>

<!-- Mirrored from pixinvent.com/materialize-material-design-admin-template/html/horizontal-menu/ by HTTrack Website Copier/3.x [XR&CO'2014], Tue, 07 Aug 2018 16:55:15 GMT -->

</html>