let ProductoProyectoNewController = {
	user: null,
	language: '',
	leader: {},
	requestType: '',
	country: '',
	leaderModal: null,
	maxSize: 0,
	filesToUpload: [],
	filesToUploadInfo: [],
	userMail: '',
	project: null,

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.leader = {};
		self.requestType = '';
		self.country = '';
		self.leaderModal = null;
		self.maxSize = 0;
		self.filesToUpload = [];
		self.filesToUploadInfo = [];
		self.userMail = '';
		self.project = null;
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.userMail = user.email;
		let user_split = self.userMail.split('@');
		self.user = user_split[0].replace('.', '_');

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

		// Lider de proyecto
		if(config.SYSMisionsUserName != '' && config.SYSMisionsUser != '') {
			self.leader = {
				nameUser: config.SYSMisionsUserName,
				userApellidos: null,
				userApellidos2: null,
				email: config.SYSMisionsUser
			}
			$('#projectLeader').val(self.leader.nameUser);
		}

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

		let isSurvey = atob(sessionStorage.getItem('productToCreateIsSurvey'));

		// Footer
		$('#previousStep').html('');
		$('#previousStep').attr('title', '');
		$('#previousStep').hide(); // Ocultar botón de previo

		// Pasos
		let footerSteps = `
			<span class="font-weight-bold d-inline-block mx-3 text-decoration main-color-text p-2">1. ${pf.const.language.RSC2095}</span>
			<span class="font-weight-bold d-inline-block mx-3">2. ${pf.const.language.RSC2094}</span>
			<span class="font-weight-bold d-inline-block mx-3">3. ${pf.const.language.RSC110}</span>
			<span class="font-weight-bold d-inline-block mx-3">4. ${pf.const.language.RSC2096}</span>
			<span class="font-weight-bold d-inline-block mx-3">5. ${pf.const.language.RSC2097}</span>
		`;
		if(isSurvey != '1') {
			footerSteps = `
				<span class="font-weight-bold d-inline-block mx-3 text-decoration main-color-text p-2">1. ${pf.const.language.RSC2095}</span>
				<span class="font-weight-bold d-inline-block mx-3">2. ${pf.const.language.RSC2094}</span>
				<span class="font-weight-bold d-inline-block mx-3">3. ${pf.const.language.RSC2096}</span>
				<span class="font-weight-bold d-inline-block mx-3">4. ${pf.const.language.RSC2097}</span>
			`;
		}
		$('#stepContainer').html(footerSteps);

		// Botón de siguiente
		$('#subsequentStep').html(pf.const.language.RSC2094 + stcmbackend.svg.arrowRightShortWithoutColor28);
		$('#subsequentStep').attr('title', pf.const.language.RSC2094);

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

		// Añadir textos
		$('#greetingTooltip').attr('title', pf.const.language.RSC1258);

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

		// Collapse
		addEventArrowTableHeader();

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

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

		let arrObj = ['RSC393'];
		pf.rsc.translateByTagHTMLFormat(':', arrObj);

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

	applyEvents() {
		let self = this;

		// Fecha
		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;
		}
		let today = nYear + '-' + nMonth + '-' + nDay;

		$('#endDate').val(today);

		stcmbackend.productoProyecto.sharedEvents(self, 'newProductProjectLeader', 'newProductProjectCountry');

		// Añadir registro documento externo
		$('#importAdditionalDocuments').off().on('click', function() {
			let content = `
				<div class="mb-3">
					<label for="externalFile" class="form-label fw-500">${pf.const.language.RSC167}</label>
					<input id="externalFile" type="file" class="form-control pa-bo-36">
				</div>

				<div class="mb-0">
					<label for="externalFileDesc" class="form-label fw-500">${pf.const.language.RSC178}</label>
					<input id="externalFileDesc" type="text" class="form-control">
				</div>

				<script>
					$('#externalFile').change(function(evt) {
						let file = evt.target.files[0];
						if(file.size > ${self.maxSize}) {
							let title = pf.const.language.RSC1959;
							let content = pf.const.language.RSC1337;

							pf.utils.showInfoDialog(title, content);
							document.getElementById('externalFile').value = '';
						}
					});
				</script>
			`;

			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC2064;
			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				let inputElement = document.getElementById('externalFile');
				let inputElementDesc = $('#externalFileDesc').val();

				if(!inputElement.files[0]) {
					$('#externalFile').addClass('is-invalid');
					$('[for="externalFile"]').addClass('is-invalid');
					return false;
				}

				let obj = {
					admin: self.userMail,
					documento: inputElement.files[0].name,
					tamano: inputElement.files[0].size,
					descripcion: inputElementDesc
				};
				self.filesToUploadInfo.push(obj);
				self.filesToUpload.push(inputElement.files[0]);

				self.additionalDocumentsTable();
			}, function() {});
		});

		// Guardar Proyecto y pasar a misión
		$('#subsequentStep').off().on('click', function() {
			self.createProject();
		});
	},

	clickEvents(data, dType = null) {
		let self = this;

		if(data == undefined || data == '') {
			return false;
		}

		if(dType) {
			self.requestType = dType;
		}

		switch(self.requestType) {
			case 'leader':
				self.leader = data;
				$('#projectLeader').val(self.leader.nameUser + ' ' + self.leader.userApellidos + ' ' + self.leader.userApellidos2);
				break;
			case 'country':
				self.country = data.isocode;
				self.leaderModal.data = null;
				$('#projectCountry').val(self.country);
				break;
		}
	},

	additionalDocumentsTable() {
		let self = this;

		let excelTitle = pf.const.language.RSC2062;

		let table = `
			<table id="tableAdditionalDocuments" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
						<th scope="col" title="${pf.const.language.RSC1313}">${pf.const.language.RSC1313}</th>
						<th scope="col" title="${pf.const.language.RSC95}"></th>
					</tr>
				</thead>

				<thead class="filtersAdditionalDocuments">
					<tr>
						<td>documento</td>
						<td>descripcion</td>
						<td>tamaño</td>
						<td>borrar</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.filesToUploadInfo.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].documento}">${self.filesToUploadInfo[i].documento}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].descripcion}">${self.filesToUploadInfo[i].descripcion}</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].tamano}">${self.filesToUploadInfo[i].tamano}</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteFilesToUpload" data-index="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

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

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

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

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

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

		let recordedTable = $('#tableAdditionalDocuments').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 5,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 3}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(recordedTable, 'filtersAdditionalDocuments');

		// Exportar tabla
		$('#exportAdditionalDocuments').off().on('click', function() {
			$('#additionalDocumentsCollapse .buttons-excel').trigger('click');
		});

		self.tableAdditionalDocumentsEvents();

		$('#tableAdditionalDocuments').on('draw.dt', function() {
			self.tableAdditionalDocumentsEvents();
		});
	},

	tableAdditionalDocumentsEvents() {
		let self = this;

		// Eliminar registro
		$('.deleteFilesToUpload').off().on('click', function() {
			let index = $(this).data('index');
			self.filesToUploadInfo.splice(index, 1);
			self.filesToUpload.splice(index, 1);
			self.additionalDocumentsTable();
		});
	},

	createProject() {
		let self = this;

		// El ID del proyecto se genera en servidor
		let nombreProyecto = $('#projectName').val().trim();
		let projectNameValidator = true;
		// Validación nombre de proyecto
		if(nombreProyecto === '') {
			$('#projectName').addClass('is-invalid');
			$('[for="projectName"]').addClass('is-invalid');
			projectNameValidator = false;
		} else {
			$('#projectName').removeClass('is-invalid');
			$('[for="projectName"]').removeClass('is-invalid');
			projectNameValidator = true;
		}

		let country = self.country;
		// Validación país de proyecto
		let projectCountryValidator = true;
		if(country === '') {
			$('#projectCountry').addClass('is-invalid');
			$('#projectCountry-group').addClass('group-invalid');
			$('[for="projectCountry"]').addClass('is-invalid');
			projectCountryValidator = false;
		} else {
			$('#projectCountry').removeClass('is-invalid');
			$('#projectCountry-group').removeClass('group-invalid');
			$('[for="projectCountry"]').removeClass('is-invalid');
			projectCountryValidator = true;
		}

		let surname1 = self.leader.userApellidos ? ' ' + self.leader.userApellidos : '';
		let surname2 = self.leader.userApellidos2 ? ' ' + self.leader.userApellidos2 : '';
		let liderProyecto = self.leader.nameUser + surname1 + surname2;
		let liderProyectoEmail = self.leader.email;
		let projectLeaderValidator = true;

		// Validación líder de proyecto
		if(liderProyecto === 'undefined') {
			$('#projectLeader').addClass('is-invalid');
			$('#projectLeader-group').addClass('group-invalid');
			$('[for="projectLeader"]').addClass('is-invalid');
			projectLeaderValidator = false;
		} else {
			$('#projectLeader').removeClass('is-invalid');
			$('#projectLeader-group').removeClass('group-invalid');
			$('[for="projectLeader"]').removeClass('is-invalid');
			projectLeaderValidator = true;
		}

		let chatGrupal = ($('#groupChat').prop('checked') === true ? 1 : 0);

		let notificarInclusion = ($('#greeting').prop('checked') === true ? 1 : 0);

		let endDateArray = $('#endDate').val().split('-');
		let endDate = endDateArray[2] + '/' + endDateArray[1] + '/' + endDateArray[0];
		let endDateValidator = true;
		// Validación fecha de vencimiento
		if($('#endDate').val() === '') {
			$('#endDate').addClass('is-invalid');
			$('[for="endDate"]').addClass('is-invalid');
			endDateValidator = false;
		} else {
			$('#endDate').removeClass('is-invalid');
			$('[for="endDate"]').removeClass('is-invalid');
			endDateValidator = true;
		}

		if(!projectCountryValidator || !projectNameValidator || !projectLeaderValidator || !endDateValidator) {
			let title = pf.const.language.RSC78;
			let content = pf.const.language.RSC101;
			pf.utils.showInfoDialog(title, content);

			return false;
		}

		let parameters = {
			producto_proyecto: '1',
			NombreProyecto: nombreProyecto,
			FechaProyecto: endDate,
			LiderProyecto: liderProyecto,
			LiderProyectoEmail: liderProyectoEmail,
			Resultados: $('#resultsFavorable').val().trim(),
			country: country,
			ChatGrupal: chatGrupal,
			ListaDistribucion: '1',
			notificarInclusion: notificarInclusion,
			applicantName: $('#ApplicantName').val().trim(),
			brandsInvolved: $('#brandsInvolved').val().trim(),
			projectDescription: $('#projectDescription').val().trim(),
			background: $('#background').val().trim(),
			businessObjective: $('#businessObjective').val().trim(),
			investigationObjective: $('#investigationObjective').val().trim(),
			actionStandard: $('#actionStandard').val().trim(),
			favorableResults: $('#resultsFavorable').val().trim(),
			notFavorableResults: $('#resultsNotFavorable').val().trim(),
			admin: self.userMail,
			filesToUploadInfo: JSON.stringify(self.filesToUploadInfo)
		};

		let elementSize = self.filesToUpload.length;
		for(let i = 0; i < elementSize; i++) {
			parameters['element' + i] = self.filesToUpload[i];
		}

		ajaxComunCallWithCallback('insertCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				sessionStorage.setItem('idProjectProduct', ajaxReturn.result);
				sessionStorage.setItem('countryProjectProduct', self.country);
				sessionStorage.setItem('numberRecords', $('#numberRecords').val());
				sessionStorage.setItem('leader', JSON.stringify(self.leader));

				window.location.href = '#!producto_mision_new';
			}
		});
	}
};