let StepByStepProjectNewController = {
	pageName: 'StepByStepProjectNewController',
	userMail: null,
	leaderModal: null,
	leader: {},
	todayEndDate: '',
	requestType: '',
	country: '',
	maxSize: 0,
	filesToUpload: [],
	filesToUploadInfo: [],
	useCPG: '',
	cpgList: '0',
	cpgActive: null,

	reset() {
		let self = this;

		self.userMail = null;
		self.leaderModal = null;
		self.leader = {};
		self.todayEndDate = '';
		self.requestType = '';
		self.country = '';
		self.maxSize = 0;
		self.filesToUpload = [];
		self.filesToUploadInfo = [];
		self.useCPG = sessionStorage['STCMBackEnd:multicpg'];
		self.cpgList = '0';
		self.cpgActive = null;
	},

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

		// 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);
		}

		// Fecha actual
		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.todayEndDate = nDay + '/' + nMonth + '/' + nYear;

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

		// Control de uso de CPG
		if(self.useCPG == '0' || sessionStorage['STCMBackEnd:idCPG'] != '0') {
			self.cpgList = sessionStorage['STCMBackEnd:idCPG'];
			$('#searchCPG').prop('disabled', true);
			$('#cpgList').val(self.cpgList);
			$('#cpgList').attr('title', self.cpgList);
		}

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

		// Documentos adicionales
		self.additionalDocumentsTable();

		// Control de países permitidos por el administrador si solo hay uno
		let countries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		if(countries.length === 1) {
			self.country = {
				isocode: countries[0]
			};

			$('#projectCountry').val(self.country.isocode);
		}

		// Collapse
		addEventArrowTableHeader();

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

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

		// Títulos comunes
		StepByStepSharedController.commonTitles();
	},

	applyEvents() {
		let self = this;

		StepByStepSharedController.sharedEventscommon(self);
		StepByStepSharedController.sharedEventsProjects(self);

		// Guardar Proyecto
		$('#nextSBS').on('click', function() {
			self.createProject();
		});
	},

	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: pf.const.language_table,
			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();
		});
	},

	clickEvents(data) {
		let self = this;

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

		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;
				self.leaderModal.data = null;
				$('#projectCountry').val(self.country.isocode);
				break;
		}
	},

	createProject() {
		let self = this;

		// El ID se genera en servidor

		// Validación nombre de proyecto
		let nombreProyecto = $('#projectName').val().trim();
		let projectNameValidator = true;
		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;
		}

		// Validación país de proyecto
		let country = self.country.isocode;
		let projectCountryValidator = true;
		if(country === undefined) {
			$('#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;
		}

		// Validación líder de proyecto
		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;
		if(liderProyecto == 'undefined' || 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;
		}

		// Control de uso de CPG
		let cpgValidator = true;
		if(self.useCPG == '1' && sessionStorage['STCMBackEnd:idCPG'] == '0') {
			if(self.cpgList == '') {
				$('#cpgList').addClass('is-invalid');
				$('#cpgList-group').addClass('group-invalid');
				$('[for="cpgList"]').addClass('is-invalid');
				cpgValidator = false;
			} else {
				$('#cpgList').removeClass('is-invalid');
				$('#cpgList-group').removeClass('group-invalid');
				$('[for="cpgList"]').removeClass('is-invalid');
				cpgValidator = true;
			}
		}

		if(!projectNameValidator || !projectCountryValidator || !projectLeaderValidator || !cpgValidator) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let parameters = {
			proyectoSBS: '1',
			NombreProyecto: nombreProyecto,
			FechaProyecto: self.todayEndDate,
			LiderProyecto: liderProyecto,
			LiderProyectoEmail: liderProyectoEmail,
			Resultados: $('#resultsFavorable').val().trim(),
			country: country,
			ChatGrupal: ($('#groupChat').prop('checked') === true ? '1' : '0'),
			ListaDistribucion: '1',
			notificarInclusion: ($('#greeting').prop('checked') === true ? '1' : '0'),
			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),
			cpgList: self.cpgList,
			targetTotalPanel: '1'
		};

		// Documentos
		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('idProjectSBS', ajaxReturn.result);
				sessionStorage.setItem('nameProjectSBS', nombreProyecto);
				sessionStorage.setItem('countryProjectSBS', self.country.isocode);
				sessionStorage.setItem('leaderSBS', JSON.stringify(self.leader));
				sessionStorage.setItem('cpgListSBS', self.cpgList);
				sessionStorage.setItem('criterionSBS', '0');

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