let CDPController = {
	numPregPerf: '',
	cdp_endpoint_KEY: '',
	dataUsers: null,
	survey: '',
	surveyName: '',
	dataSurvey: null,
	dataSurveyLength: 0,
	dataComun: null,

	reset() {
		let self = this;

		self.numPregPerf = '';
		self.cdp_endpoint_KEY = '';
		self.dataUsers = '';
		self.survey = '';
		self.surveyName = '';
		self.dataSurvey = null
		self.dataSurveyLength = 0;
		self.dataComun = null;
	},

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

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

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

		let url = window.location.href;
		if(!url.includes('localhost') && !url.includes('membeer')) {
			$('#endPoint').hide();
			$('#endPointUsers').hide();
		}

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.numPregPerf = config.numPregPerfEnMostreo;
		self.cdp_endpoint_KEY = config.cdp_endpoint_KEY

		self.loadLang();
		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();
	},

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

		// TITLES
		$('.loadTitle').attr('title', pf.const.language.RSC46);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
		$('#endPoint').attr('title', pf.const.language.RSC1983);
		$('#endPointUsers').attr('title', pf.const.language.RSC1983);
	},

	applyEvents() {
		let self = this;

		// Cargar usuarios
		$('#loadUsers').off().on('click', function(e) {
			self.getDataIntegrationCDP();
		});

		// Abrir tabla encuestas
		let surveys = new TableSurveys(0, 'CDPSurvey');
		$('#searchSurvey').click(function() {
			surveys.setEvents('tableModal');
		});

		// Enviar data a CDP
		$('#endPoint').click(function() {
			let dataSurvey = '';
			if(self.dataSurveyLength > 10000) {
				let dataSurveyArray = self.dataSurvey.slice(0, 10000);
				dataSurvey = JSON.stringify(dataSurveyArray);
			} else {
				dataSurvey = JSON.stringify(self.dataSurvey);
			}

			let values = {
				action: 'sendCDPData',
				token: sessionStorage['STCMBackEnd:token'],
				dataSurvey: dataSurvey,
				dataSurveyLength: self.dataSurveyLength,
				cdp_endpoint_KEY: self.cdp_endpoint_KEY,
				abi_country_endpoint: self.dataComun.abi_country_endpoint,
				abi_survey_id: self.survey,
				abi_survey_title: self.surveyName,
				abi_earned_points: self.dataComun.abi_earned_points,
				abi_program_name: self.dataComun.abi_program_name
			};

			let sendCDPData = new SendCDPData(values);
			sendCDPData.start();
		});

		// Enviar data a CDP - Usuarios
		$('#endPointUsers').click(function() {
			let values = {
				action: 'sendCDPDataUsers',
				token: sessionStorage['STCMBackEnd:token'],
				dataUsers: JSON.stringify(self.dataUsers),
				cdp_endpoint_KEY: self.cdp_endpoint_KEY
			};

			let sendCDPData = new SendCDPData(values);
			sendCDPData.start();
		});

		// Exportar usuarios
		// Nombre y apellidos si gdpr = 0
		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		$('#exportUsers').off().on('click', function() {
			let parameters = {
				noLimited: '1',
				gdpr: gdpr
			};
			ajaxComunCallWithCallbackOne('getDataIntegrationCDP', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let resp = JSON.parse(ajaxReturn.resData.response);

					let urlFile = stcm.const.downloads + resp.result;
					let date = new Date();
					let element = document.createElement('a');
					element.setAttribute('href', urlFile);
					element.setAttribute('download', 'CDP' + date.getFullYear() + date.getMonth() + date.getDate() + '.xlsx');

					element.style.display = 'none';
					document.body.appendChild(element);
					element.click();
					document.body.removeChild(element);
				}
			});
		});

		// Exportar usuarios encuesta
		$('#exportSurveys').off().on('click', function() {
			let parameters = {
				noLimited: '1',
				numPreguntasPerfilacionEnAnalyticMostreo: self.numPregPerf,
				survey: self.survey,
				gdpr: gdpr
			};
			ajaxComunCallWithCallbackOne('getAnalyticsMuestraToExport_CDP', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					let resp = JSON.parse(ajaxReturn.resData.response);

					let urlFile = stcm.const.downloads + resp.result;
					let date = new Date();
					let element = document.createElement('a');
					element.setAttribute('href', urlFile);
					element.setAttribute('download', 'CDP' + date.getFullYear() + date.getMonth() + date.getDate() + '_' + self.survey + '.xlsx');

					element.style.display = 'none';
					document.body.appendChild(element);
					element.click();
					document.body.removeChild(element);
				}
			});
		});
	},

	getDataIntegrationCDP() {
		let self = this;

		let parameters = {
			noLimited: '0'
		};
		ajaxComunCallWithCallbackOne('getDataIntegrationCDP', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);

				if(resp.dataintegration_cdp == undefined) {
					self.dataUsers = [];
				} else {
					$('#groupNestBy').removeClass('d-none');
					$('#resultTable').removeClass('d-none');
					self.dataUsers = resp.dataintegration_cdp;
					if(resp.totalRows > resp.dataintegration_cdp.length) {
						let errorTitle = pf.const.language.RSC1616;
						let errorContent = pf.const.language.RSC1730;
						pf.utils.showInfoDialog(errorTitle, errorContent);
					}
				}

				if(resp.dataintegration_cdp.length > 0) {
					$('#endPointUsers').attr('disabled', false);
					self.renderDataUsers();
				} else {
					$('#endPointUsers').attr('disabled', true);
				} 
			}
		});
	},

	renderDataUsers() {
		let self = this;

		$('#resultTable').show();

		// Nombre y apellidos si gdpr = 0
		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="first_name">first_name</th>
			<th scope="col" title="last_name">last_name</th>
			<th scope="col" title="last_name2">last_name2</th>
		`;
		let nameSurnameFilter = `
			<td>abi_first_name</td>
			<td>abi_last_name</td>
			<td>abi_last_name2</td>
		`;

		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<table id="registers" class="table table-hover">
				<thead>
					<tr>
						${nameSurnameHead}
						<th scope="col" title="zone">zone</th>
						<th scope="col" title="country">country</th>
						<th scope="col" title="brand">brand</th>
						<th scope="col" title="email">email</th>
						<th scope="col" title="dateofbirth">dateofbirth</th>
						<th scope="col" title="gender">gender</th>
						<th scope="col" title="phone">phone</th>
						<th scope="col" title="address">address</th>
						<th scope="col" title="number">number</th>
						<th scope="col" title="complement">complement</th>
						<th scope="col" title="zipcode">zipcode</th>
						<th scope="col" title="neighborhood">neighborhood</th>
						<th scope="col" title="city">city</th>
						<th scope="col" title="marketingactivation">marketingactivation</th>
						<th scope="col" title="tcpp">tcpp</th>
						<th scope="col" title="creationDate">creationDate</th>
						<th scope="col" title="consent_date">consent_date</th>
						<th scope="col" title="campaign">campaign</th>
						<th scope="col" title="sended_on">sended_on</th>
						<th scope="col" title="sendDate">sendDate</th>
					</tr>
				</thead>

				<thead class="filtersResult">
					<tr>
						${nameSurnameFilter}
						<td>abi_zone</td>
						<td>abi_country</td>
						<td>abi_brand</td>
						<td>abi_email</td>
						<td>abi_dateofbirth</td>
						<td>abi_gender</td>
						<td>abi_phone</td>
						<td>abi_address</td>
						<td>abi_number</td>
						<td>abi_complement</td>
						<td>abi_zipcode</td>
						<td>abi_neighborhood</td>
						<td>abi_city</td>
						<td>abi_marketingactivation</td>
						<td>abi_tcpp</td>
						<td>creationDate</td>
						<td>abi_consent_date</td>
						<td>abi_campaign</td>
						<td>abi_sended_on</td>
						<td>sendData</td>
					</tr>
				</thead>

				<tbody>
		`;

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

		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.dataUsers[i].abi_country.toLowerCase()) == -1) {
				continue;
			}

			let send = pf.const.language.RSC121;
			let sendDate = '';
			let checkIcon = stcmbackend.svg.squareWithoutColor;

			if(self.dataUsers[i].abi_sended_on != '') {
				send = pf.const.language.RSC120;
				let sendDateArray = self.dataUsers[i].abi_sended_on.split('.');
				sendDate = sendDateArray[0];
				checkIcon = stcmbackend.svg.checkSquareWithoutColor;
			}

			let nameSurnameBody = `
				<td class="text-truncate" title="${self.dataUsers[i].abi_first_name}">${self.dataUsers[i].abi_first_name}</td>
				<td class="text-truncate" title="${self.dataUsers[i].abi_last_name}">${self.dataUsers[i].abi_last_name}</td>
				<td class="text-truncate" title="${self.dataUsers[i].abi_last_name2}">${self.dataUsers[i].abi_last_name2}</td>
			`;

			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${self.dataUsers[i].abi_zone}">${self.dataUsers[i].abi_zone}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_country}">${self.dataUsers[i].abi_country}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_brand}">${self.dataUsers[i].abi_brand}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_email}">${self.dataUsers[i].abi_email}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_dateofbirth}">${self.dataUsers[i].abi_dateofbirth}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_gender}">${self.dataUsers[i].abi_gender}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_phone}">${self.dataUsers[i].abi_phone}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_address}">${self.dataUsers[i].abi_address}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_number}">${self.dataUsers[i].abi_number}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_complement}">${self.dataUsers[i].abi_complement}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_zipcode}">${self.dataUsers[i].abi_zipcode}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_neighborhood}">${self.dataUsers[i].abi_neighborhood}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_city}">${self.dataUsers[i].abi_city}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_marketingactivation}">${self.dataUsers[i].abi_marketingactivation}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_tcpp}">${self.dataUsers[i].abi_tcpp}</td>
					<td class="text-truncate" title="${self.dataUsers[i].creationDate}">${self.dataUsers[i].creationDate}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_consent_date}">${self.dataUsers[i].abi_consent_date}</td>
					<td class="text-truncate" title="${self.dataUsers[i].abi_campaign}">${self.dataUsers[i].abi_campaign}</td>
					<td class="text-center">
						<span class="d-none">${send}</span>
						${checkIcon}
					</td>
					<td class="text-truncate" title="${sendDate}">${sendDate}</td>
				</tr>
			`;
		}

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

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

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

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			rowGroup: {
				endRender(rows, group) {
					return group + ': ' + pf.const.language.RSC146 + ' (' + rows.count() + ')';
				},
				dataSrc: 0
			},
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

		dataTable.rowGroup().disable().draw();
		$('#nestBy').hide();

		$('.dataTables_filter').css('float', 'none');
		$('#registers_wrapper button').removeClass('dt-button');

		// Creación de select principal de agrupamiento
		// Arrays de datos
		let name = [];

		$.each($('#registers thead th'), function() {
			name.push($(this).text());
		});

		let options1 = `<option value="-1">${pf.const.language.RSC130}</option>`;
		for(let i = 0; i < name.length; i++) {
			options1 += `<option value="${i}">${name[i]}</option>`;
		}
		$('#groupBy').html(options1);

		// Función de agrupamiento anidado
		function nestBy() {
			$('#nestBy').html('');
			let options2 = `<option value="-1">${pf.const.language.RSC131}</option>`;
			for(let i = 0; i < name.length; i++) {
				if(i == $('#groupBy').val()) {
					continue;
				} else {
					options2 += `<option value="${i}">${name[i]}</option>`;
				}
			}
			$('#nestBy').html(options2);

			// Evento de anidado
			$('#nestBy').off().on('change', function() {
				let valueGroup = $('#groupBy').val();

				if($('#nestBy').val() === '-1') {
					dataTable.rowGroup().dataSrc(valueGroup);
					dataTable.order([[valueGroup, 'asc']]).draw();
				} else {
					let valueNest = $('#nestBy').val();
					dataTable.rowGroup().dataSrc([valueGroup, valueNest]);
					dataTable.order([[valueGroup, 'asc'], [valueNest, 'asc']]).draw();
				}
			});
		}

		// Evento de agrupamiento
		$('#groupBy').on('change', function() {
			if($('#groupBy').val() === '-1') {
				dataTable.rowGroup().disable().draw();
				$('#nestBy').hide();
			} else {
				let value = $('#groupBy').val();

				dataTable.rowGroup().enable().draw();
				$('#nestBy').show();

				dataTable.rowGroup().dataSrc(value);
				dataTable.order([[value, 'asc']]).draw();

				// Recreación de agrupamiento secundario
				nestBy();
			}
		});

		// Ocultar botones
		$('#resultTable .dataTables_length').hide();
	},

	clickSurvey(survey) {
		let self = this;

		self.survey = survey.sid;
		self.surveyName = survey.surveyls_title;
		$('#surveyProfiling').val(survey.surveyls_title);
		$('#surveyProfiling').attr('title', survey.surveyls_title);

		let parameters = {
			noLimited: '0',
			numPreguntasPerfilacionEnAnalyticMostreo: self.numPregPerf,
			survey: self.survey
		};
		ajaxComunCallWithCallback('getAnalyticsMuestraToExport_CDP', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.dataSurvey = ajaxReturn.result;
				self.dataSurveyLength = self.dataSurvey.length;
				self.dataComun = ajaxReturn.resultComun;

				if(self.dataSurvey.length > 0) {
					$('#exportSurveys').attr('disabled', false);
					$('#endPoint').attr('disabled', false);
				}

				self.renderDataSurvey();
			}
		});
	},

	renderDataSurvey() {
		let self = this;

		// Nombre y apellidos si gdpr = 0
		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `
			<th scope="col" title="first_name">first_name</th>
			<th scope="col" title="last_name">last_name</th>
		`;
		let nameSurnameFilter = `
			<td>abi_first_name</td>
			<td>abi_last_name</td>
		`;

		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<table id="registersSurveys" class="table table-hover tRegs">
				<thead>
					<tr>
						${nameSurnameHead}
						<th scope="col" title="dateofbirth">dateofbirth</th>
						<th scope="col" title="email">email</th>
						<th scope="col" title="phone">phone</th>
						<th scope="col" title="gender">gender</th>
						<th scope="col" title="question">question</th>
						<th scope="col" title="response">response</th>
					</tr>
				</thead>

				<thead class="filtersResultSurvey">
					<tr>
						${nameSurnameFilter}
						<td>dateofbirth</td>
						<td>email</td>
						<td>phone</td>
						<td>gender</td>
						<td>question</td>
						<td>response</td>
					</tr>
				</thead>

				<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.dataSurvey.length;
		if(size > 10000) {
			size = 10000;

			let alertTitle = pf.const.language.RSC1982;
			//Se muestran 10000 de + size + registros
			let alertContent = pf.const.language.RSC2099 + ' ' + self.dataSurvey.length;
			pf.utils.showInfoDialog(alertTitle, alertContent);
		}
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.dataComun.abi_country.toLowerCase()) == -1) {
				continue;
			}

			let nameSurnameBody = `
				<td class="text-truncate" title="${self.dataSurvey[i].abi_first_name}">${self.dataSurvey[i].abi_first_name}</td>
				<td class="text-truncate" title="${self.dataSurvey[i].abi_last_name}">${self.dataSurvey[i].abi_last_name}</td>
			`;

			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr>
					${nameSurnameBody}
					<td class="text-truncate" title="${self.dataSurvey[i].abi_dateofbirth}">${self.dataSurvey[i].abi_dateofbirth}</td>
					<td class="text-truncate" title="${self.dataSurvey[i].abi_email}">${self.dataSurvey[i].abi_email}</td>
					<td class="text-truncate" title="${self.dataSurvey[i].abi_phone}">${self.dataSurvey[i].abi_phone}</td>
					<td class="text-truncate" title="${self.dataSurvey[i].abi_gender}">${self.dataSurvey[i].abi_gender}</td>
					<td class="text-truncate" title="${self.dataSurvey[i].abi_question}">${self.dataSurvey[i].abi_question}</td>
					<td class="text-truncate" title="${self.dataSurvey[i].abi_response}">${self.dataSurvey[i].abi_response}</td>
				</tr>
			`;
		}

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

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

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

			if(title == 'endPoint') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			}

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

		let registersSurveys = $('#registersSurveys').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(registersSurveys, 'filtersResultSurvey');
	}
};