let PagosDetalleController = {
	data: null,
	country: '',
	startDate: '',
	startTime: '00:00',
	endDate: '',
	endTime: '23:59',
	missions: '',
	idmision: '',
	dateFormat: '',

	resetData() {
		let self = this;

		self.data = null;
		self.country = '';
		self.startDate = '';
		self.startTime = '00:00';
		self.endDate = '';
		self.endTime = '23:59';
		self.missions = '';
		self.idmision = '';
		self.dateFormat = '';
	},

	setEvents() {
		let self = this;
		self.resetData();

		// Información de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let userA = JSON.parse(JSONuser);
		self.dateFormat = userA.formatoFecha;

		// Ampliación de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC16 + ' - ' + pf.const.language.RSC504);

		// Opciones de header
		let jsonsubopt = {
			country: {
				id: 'country',
				deleteBtn: true,
				style: 'style="line-height: initial; padding-top: 1.75rem!important;"'
			},
			mision: {
				id: 'mission',
				style: 'style="line-height: initial; padding-top: 1.75rem!important; padding-right: 0;"',
				disabled: ''
			},
			refresh: 'previewTables',
			options: 'dateOptions',
			startEndDate: {
				class: 'form-group m-0 ml-1',
				style: 'max-width: 145px; line-height: initial;'
			},
			startEndTime: {
				class: 'form-group m-0 ml-1',
				style: 'min-width: 105px; line-height: initial;'
			}
		};

		let nav = `
			<div class="d-flex justify-content-end row m-0">
				${createSubOptionOptionsSelector(jsonsubopt.options)}
				${createSubOptionStartEndDateTime(jsonsubopt.startEndDate.class, jsonsubopt.startEndTime.class, jsonsubopt.startEndDate.style, jsonsubopt.startEndTime.style)}
				${createSubOptionCountry(jsonsubopt.country.id, jsonsubopt.country.deleteBtn, jsonsubopt.country.style)}
				${createSubOptionMision(jsonsubopt.mision.id, jsonsubopt.mision.style, jsonsubopt.mision.disabled)}
				<div class="pa-to-28">	
					${createSubOptionRefresh(jsonsubopt.refresh)}
				</div>
			</div>
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		// Botones secundarios
		$('#previewTables').addClass('secondary-button');

		$('#countryDelete').hide();
		$('#resultTableCard').hide();

		// Inputs de fecha y hora
		let now = new Date();
		let nYear = now.getFullYear();
		let nMonth = now.getMonth() + 1;
		if(nMonth < 10) {
			nMonth = '0' + nMonth;
		}
		let nDay = now.getDate();
		if(nDay < 10) {
			nDay = '0' + nDay;
		}
		self.today = nYear + '-' + nMonth + '-' + nDay;
		self.startDate = self.today;
		self.endDate = self.today;

		$('#startDate').val(self.startDate);
		$('#startTime').val(self.startTime);
		// Ocultar hora de inicio
		$('#startTime').parent().hide();
		$('#endDate').val(self.endDate);
		$('#endTime').val(self.endTime);
		// Ocultar hora de fin
		$('#endTime').parent().hide();

		self.loadLanguage();

		// País
		let countryModal = new TableCountries(0, 'pagosDetalle');
		$('#searchCountry').on('click', function() {
			countryModal.setEvents();
		});

		// Limpiar país
		$('#countryDelete').on('click', function() {
			self.country = '';
			$('#country').val('');
			$('#country').attr('title', '');
			$('#countryDelete').hide();
		});

		// Fecha de inicio
		$('#startDate').on('change', function() {
			self.startDate = $('#startDate').val();
			if(self.startDate > self.endDate) {
				$('#startDate').val(self.endDate);
				self.startDate = $('#startDate').val();
			}
		});

		// Hora de inicio
		$('#startTime').on('change', function() {
			self.startTime = $('#startTime').val();
		});

		// Fecha de fin
		$('#endDate').on('change', function() {
			self.endDate = $('#endDate').val();
			if(self.endDate < self.startDate) {
				$('#endDate').val(self.startDate);
				self.endDate = $('#endDate').val();
			}
		});

		// Hora de fin
		$('#endTime').on('change', function() {
			self.endTime = $('#endTime').val();
		});

		// Obtener pagos
		$('#previewTables').on('click', function() {
			$('#resultTableCard').show();

			self.getPayments();
		});

		// Misiones
		$('#searchMission').on('click', function() {
			// Objeto mision
			if(self.missions === '') {
				let JSONuser = sessionStorage['STCMBackEnd:user'];
				let user = JSON.parse(JSONuser);
				let idCliente = user.idCliente;

				// Parámetro de cliente
				let parameters = {
					idCliente: idCliente
				}
				ajaxComunCallWithCallback('getAllMisiones', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.missions = ajaxReturn.result;

						// Modal de misiones de encuesta
						self.renderSurveyMissions();
					}
				});
			} else {
				$('#missionTable').modal('show', true);
			}
		});

		// Collapse
		addEventArrowTableHeader();

		// Pintar texto de label
		changeLabelsColor();
	},

	loadLanguage() {
		pf.rsc.translateByTag('text');

		// TITLES
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	renderSurveyMissions() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
					<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
					<th scope="col" title="${pf.const.language.RSC171}">${pf.const.language.RSC171}</th>
					<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
					<th scope="col" title="${pf.const.language.RSC172}">${pf.const.language.RSC172}</th>
					<th scope="col" title="${pf.const.language.RSC145}">${pf.const.language.RSC145}</th>
				</tr>
			</thead>

			<thead class="filtersMissions">
				<tr>
					<td>idmision</td>
					<td>encuesta</td>
					<td>fechainicio</td>
					<td>horainicio</td>
					<td>fechafin</td>
					<td>horafin</td>
					<td>importe</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));

		let size = self.missions.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.missions[i].country) == -1 || self.missions[i].isSurvey != '1') {
				continue;
			}

			// Formato de fecha, el servicio devuelve DD/MM/AAAA#HH#MM:SS
			let startDate = '';
			let endDate = '';
			let dateTimeArrayStart = self.missions[i].fechahorainicio.split('#');
			let dateTimeArrayEnd = self.missions[i].fechahorafin.split('#');
			let dateStart = dateTimeArrayStart[0].replace(/-/g, '/');
			let dateEnd = dateTimeArrayEnd[0].replace(/-/g, '/');
			if(self.dateFormat === 'AAAAMMDD') {
				startDate = modifyDateFormat(dateStart);
				endDate = modifyDateFormat(dateEnd);
			} else {
				startDate = dateStart;
				endDate = dateEnd;
			}

			let startTimeArray = dateTimeArrayStart[2].split(':');
			let startTime = dateTimeArrayStart[1] + ':' + startTimeArray[0];

			let endTimeArray = dateTimeArrayEnd[2].split(':');
			let endTime = dateTimeArrayEnd[1] + ':' + endTimeArray[0];

			table += `
				<tr class="c-pointer missionSelect" data-mission="${self.missions[i].stampMision}" data-name="${self.missions[i].idmision}" data-survey="${self.missions[i].sid}">
					<td class="text-truncate" title="${self.missions[i].idmision}">${self.missions[i].idmision}</td>
					<td class="text-truncate" title="${self.missions[i].sid}">${self.missions[i].sid}</td>
					<td class="text-truncate" title="${startDate}">${startDate}</td>
					<td class="text-truncate" title="${startTime}">${startTime}</td>
					<td class="text-truncate" title="${endDate}">${endDate}</td>
					<td class="text-truncate" title="${endTime}">${endTime}</td>
					<td class="text-truncate" title="${self.missions[i].importe}">${self.missions[i].importe}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

		$('#tableMissions').html(table);

		// Setup - add a text input to each footer cell
		$('#tableMissions .filtersMissions td').each(function() {
			let value = `<input type="text" class="form-control form-control-sm">`;

			$(this).html(value);
		});

		let ObjetiveTable = $('#tableMissions').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '70px', targets: 1},
				{width: '120px', targets: 2},
				{width: '110px', targets: 3},
				{width: '110px', targets: 4},
				{width: '100px', targets: 5},
				{width: '70px', targets: 6}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			ObjetiveTable.columns.adjust();
		}, 200);

		// Ocultar botones de tabla
		hideTableButtons('tableMissions');

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filtersMissions');

		self.eventsSurveyMissions();

		$('#tableMissions').on('draw.dt', function() {
			self.eventsSurveyMissions();
		});
	},

	eventsSurveyMissions() {
		let self = this;

		$('.missionSelect').off().on('click', function() {
			$('#missionTable').modal('toggle');

			let nameMission = $(this).data('name');
			self.idmision = nameMission;
			$('#mission').val(nameMission);
			$('#mission').attr('title', nameMission);
		});
	},

	getPayments() {
		let self = PagosDetalleController;

		let filter = $('#dateOptions').val();
		let fechaInicio = self.startDate + ' ' + self.startTime;
		let fechaFin = self.endDate + ' ' + self.endTime;

		let parameters = {
			allRows: '0',
			country: self.country,
			filter: filter,
			dateinit: fechaInicio,
			datefin: fechaFin,
			idmision: self.idmision
		};
		ajaxComunCallWithCallback('getDetallePagos', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				self.renderTable();
				if(ajaxReturn.totalRows > ajaxReturn.result.length) {
					let errorTitle = pf.const.language.RSC1616;
					let errorContent = pf.const.language.RSC1730;
					pf.utils.showInfoDialog(errorTitle, errorContent);
				}
			}
		});
	},

	renderTable() {
		let self = this;

		let table = `
			<table id="tablePaymenyts" class="table table-hover tRegs tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC68}">${pf.const.language.RSC68}</th>
						<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
						<th scope="col" title="${pf.const.language.RSC505}">${pf.const.language.RSC505}</th>
						<th scope="col" title="${pf.const.language.RSC348}">${pf.const.language.RSC348}</th>
						<th scope="col" title="${pf.const.language.RSC349}">${pf.const.language.RSC349}</th>
						<th scope="col" title="${pf.const.language.RSC506}">${pf.const.language.RSC506}</th>
						<th scope="col" title="${pf.const.language.RSC1945}">${pf.const.language.RSC1945}</th>
						<th scope="col" title="${pf.const.language.RSC1335}">${pf.const.language.RSC1335}</th>
						<th scope="col" title="${pf.const.language.RSC1946}">${pf.const.language.RSC1946}</th>
					</tr>
				</thead>

				<thead class="filtersUser">
					<tr>
						<td>name</td>
						<td>user</td>
						<td>país</td>
						<td>sid</td>
						<td>concepto</td>
						<td>valor</td>
						<td>cobrado</td>
						<td>consecucion</td>
						<td>exportacion</td>
						<td>procesado</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.data[i].isopais) == -1) {
				continue;
			}

			let fullName = (self.data[i].userNombre != null ? self.data[i].userNombre : '-') + ' ' + (self.data[i].userApellidos && self.data[i].userApellidos != 'null' ? self.data[i].userApellidos : '') + ' ' + (self.data[i].userApellidos2 && self.data[i].userApellidos2 != 'null' ? self.data[i].userApellidos2 : '');

			let concepto = self.data[i].concepto.replace(/<[^>]*>?/g, '');

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let fechaCobro = '-';
			let fechaCobroOrder = '';
			if(self.data[i].fechaCobro != '') {
				// Para ordenación en columna
				fechaCobroOrder = self.data[i].fechaCobro.replace(' ', '');

				let dateTimeArray = self.data[i].fechaCobro .split(' ');
				let date = dateTimeArray[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					fechaCobro = modifyDateFormat(date) + ' ' + dateTimeArray[1];
				} else {
					fechaCobro = date + ' ' + dateTimeArray[1];
				}
			}

			let fechaExported = '-';
			let fechaExportedOrder = '';
			if(self.data[i].fechaExported != '') {
				// Para ordenación en columna
				fechaExportedOrder = self.data[i].fechaExported.replace(' ', '');

				let dateTimeArray = self.data[i].fechaExported .split(' ');
				let date = dateTimeArray[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					fechaExported = modifyDateFormat(date) + ' ' + dateTimeArray[1];
				} else {
					fechaExported = date + ' ' + dateTimeArray[1];
				}
			}

			let fechaProcesado = '-';
			let fechaProcesadoOrder = '';
			if(self.data[i].fechaProcesado != '') {
				// Para ordenación en columna
				fechaProcesadoOrder = self.data[i].fechaProcesado.replace(' ', '');

				let dateTimeArray = self.data[i].fechaProcesado .split(' ');
				let date = dateTimeArray[0].replace(/-/g, '/');
				if(self.dateFormat === 'DDMMAAAA') {
					fechaProcesado = modifyDateFormat(date) + ' ' + dateTimeArray[1];
				} else {
					fechaProcesado = date + ' ' + dateTimeArray[1];
				}
			}

			table += `
				<tr data-id="${i}">
					<td class="text-truncate" title="${fullName}">${fullName}</td>
					<td class="text-truncate" title="${self.data[i].user}">${(self.data[i].user != '' ? self.data[i].user : '-')}</td>
					<td class="text-truncate" title="${self.data[i].pais}">${((self.data[i].pais != '' && self.data[i].pais) ? self.data[i].pais : '-')}</td>
					<td class="text-truncate" title="${self.data[i].sid}">${(self.data[i].sid != '' ? self.data[i].sid : '-')}</td>
					<td class="text-truncate" title="${concepto}">${(concepto != '' ? concepto : '-')}</td>
					<td class="text-truncate" title="${self.data[i].valor}">${(self.data[i].valor != '' ? self.data[i].valor : '-')}</td>
					<td class="text-center">
						<span class="d-none">${(self.data[i].cobrado == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="activa" disabled ${(self.data[i].cobrado == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${fechaCobro}">
						<span class="d-none">${fechaCobroOrder}</span>
						${fechaCobro}
					</td>
					<td class="text-truncate" title="${fechaExported}">
						<span class="d-none">${fechaExportedOrder}</span>
						${fechaExported}
					</td>
					<td class="text-truncate" title="${fechaProcesado}">
						<span class="d-none">${fechaProcesadoOrder}</span>
						${fechaProcesado}
					</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

		$('#resultTable').html(table);

		// Setup - add a text input to each footer cell
		$('#tablePaymenyts .filtersUser td').each(function() {
			let title = $(this).text();
			let value = `<input type="text" class="form-control form-control-sm">`;

			if(title === 'cobrado') {
				value = optionsSelectAllYesNo();
			}

			$(this).html(value);
		});

		let tableUsers = $('#tablePaymenyts').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			scrollCollapse: true,
			scroller: false,
			columnDefs: [
				{width: '40px', targets: 2},
				{width: '40px', targets: 3},
				{width: '60px', targets: 6},
				{width: '140px', targets: 7},
				{width: '140px', targets: 8},
				{width: '140px', targets: 9}
			],
			paging: true,
			autoWidth: false,
			aaSorting: [],
			lengthChange: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC16,
				className: 'd-none',
				title: pf.const.language.RSC16,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

		// Ocultar botones de tabla
		hideTableButtons('tablePaymenyts');

		// Exportar tabla
		$('#exportdetails').prop('disabled', false);
		$('#exportdetails').off().on('click', function() {
			let self = PagosDetalleController;

			let filter = $('#dateOptions').val();
			let fechaInicio = self.startDate + ' ' + self.startTime;
			let fechaFin = self.endDate + ' ' + self.endTime;

			let parameters = {
				allRows: '1',
				country: self.country,
				filter: filter,
				dateinit: fechaInicio,
				datefin: fechaFin,
				idmision: self.idmision,
				dateFormat: self.dateFormat
			};
			ajaxComunCallWithCallback('getDetallePagos', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let urlFile = stcm.const.downloads + ajaxReturn.result;
					let date = new Date();
					let element = document.createElement('a');
					element.setAttribute('href', urlFile);
					element.setAttribute('download', 'PaymentDetail' + date.getFullYear() + date.getMonth() + date.getDate() + '.xlsx');
					element.style.display = 'none';
					document.body.appendChild(element);
					element.click();
					document.body.removeChild(element);
				}
			});
		});

		$('#tablePaymenyts_length').hide();

		// Apply the search
		applyTheSearch(tableUsers, 'filtersUser');
	},

	clickEvents(data) {
		let self = this;

		self.country = data.isocode;
		$('#country').val(data.descripcion);
		$('#country').attr('title', data.descripcion);
		$('#countryDelete').show();
	}
};