let StepByStepProjectEditController = {
	pageName: 'StepByStepProjectEditController',
	idProject: '',
	project: null,
	userMail: null,
	leaderModal: null,
	leader: {},
	requestType: '',
	country: '',
	maxSize: 0,
	fileToUpload: [],
	fileToUploadDesc: '',
	filesToUploadInfo: [],
	useCPG: '',
	cpgList: '0',
	cpgActive: null,

	reset() {
		let self = this;

		self.idProject = sessionStorage['idProjectSBS'];
		self.project = null;
		self.userMail = null;
		self.leaderModal = null;
		self.leader = {};
		self.requestType = '';
		self.country = '';
		self.maxSize = 0;
		self.fileToUpload = [];
		self.fileToUploadDesc = '';
		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;

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

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

		addLoader();
		// Datos de proyecto creado
		self.getCMBPProjects();

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

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

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

	getCMBPProjects() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.project = ajaxReturn.result[0]
				$('#projectName').val(self.project.NombreProyecto);
				self.country = {
					isocode: self.project.country
				};
				$('#projectCountry').val(self.project.country);
				$('#projectLeader').val(self.project.LiderProyecto);
				$('#groupChat').prop('checked', (self.project.ChatGrupal == 1 ? true : false));
				$('#greeting').prop('checked', (self.project.notificarInclusion == 1 ? true : false));

				// CPG
				self.cpgList = self.project.cpgList == '' ? '0' : self.project.cpgList ;
				$('#cpgList').val(self.cpgList);
				$('#cpgList').attr('title', self.cpgList);

				// BRIEFING
				if(self.project.briefing.length > 0) {
					$('#ApplicantName').val(self.project.briefing[0].applicantName);
					$('#brandsInvolved').val(self.project.briefing[0].brandsInvolved);
					$('#projectDescription').val(self.project.briefing[0].projectDescription);
					$('#background').val(self.project.briefing[0].background);
					$('#businessObjective').val(self.project.briefing[0].businessObjective);
					$('#investigationObjective').val(self.project.briefing[0].investigationObjective);
					$('#actionStandard').val(self.project.briefing[0].actionStandard);
					$('#resultsFavorable').val(self.project.briefing[0].favorableResults);
					$('#resultsNotFavorable').val(self.project.briefing[0].notFavorableResults);
				}

				// Búsqueda de líder de proyecto
				let parameters = {
					country: '',
					consejero: '',
					enabled: '',
					staff: '1'
				};
				ajaxComunCallWithCallback('getAllUsers', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						let size = ajaxReturn.result.length;
						for(let i = 0; i < size; i++) {
							if(self.project.LiderProyectoEmail == ajaxReturn.result[i].email) {
								self.leader = ajaxReturn.result[i];
								break;
							}
						}

						if(self.leader == '') {
							let errorTitle = pf.const.language.RSC1616;
							let errorContent = pf.const.language.RSC1728;
							pf.utils.showInfoDialog(errorTitle, errorContent);
						}

						removeLoader();
					}
				}, false);

				// Documentos adicionales
				let sizeDocs = self.project.files.length;
				for(let n = 0; n < sizeDocs; n++) {
					let obj = {
						id: self.project.files[n].id,
						fecha: self.project.files[n].stampServer,
						admin: self.project.files[n].admin,
						documento: self.project.files[n].fileName,
						descripcion: self.project.files[n].descripcion,
						tamano: self.project.files[n].fileSize
					};
					self.filesToUploadInfo.push(obj);
				}

				self.additionalDocumentsTable();
			}
		}, false);
	},

	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.RSC225}"></th>
						<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
						<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.RSC56}">${pf.const.language.RSC56}</th>
						<th scope="col" title="${pf.const.language.RSC95}"></th>
					</tr>
				</thead>

				<thead class="filtersAdditionalDocuments">
					<tr>
						<td>editar</td>
						<td>fecha</td>
						<td>documento</td>
						<td>descripcion</td>
						<td>tamaño</td>
						<td>descargar</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 text-center" title="${pf.const.language.RSC225}">
						<span class="c-pointer editDescription" data-id="${self.filesToUploadInfo[i].id}" data-description="${self.filesToUploadInfo[i].descripcion}">
							${stcmbackend.svg.pencil}
						</span>
					</td>
					<td class="text-truncate" title="${self.filesToUploadInfo[i].fecha}">${self.filesToUploadInfo[i].fecha}</td>
					<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">
						<a href="${stcm.const.downloads + 'projects/' + self.idProject + '/' + self.filesToUploadInfo[i].documento}" class="btn btn-eye loadFile" download>
							${stcmbackend.svg.bigDownloadWithoutColor}
						</a>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteFilesToUpload" data-id="${self.filesToUploadInfo[i].id}" data-name="${self.filesToUploadInfo[i].documento}">
							${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 === 'editar' || 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', orderable: false, targets: 0},
				{width: '135px', targets: 2},
				{width: '70px', targets: 4},
				{width: '85px', orderable: false, targets: 5},
				{width: '30px', orderable: false, targets: 6}
			],
			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 id = $(this).data('id');
			let filename = $(this).data('name');

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

			let alertTitle = pf.const.language.RSC10;
			let alertText = pf.const.language.RSC2066;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteCMBPProjectsFileById(id, filename);
			}, function() {});
		});

		// Editar descripción
		$('.editDescription').off().on('click', function() {
			let id = $(this).data('id');

			// Alert con input
			let alertTitle = pf.const.language.RSC2062;

			let content = `
				<div class="form-group">
					<label for="documentDescription" class="fw-500">${pf.const.language.RSC178}</label>
					<input id="documentDescription" type="text" class="form-control" value="">
				</div>
			`;
			let objInfo = {
				accept: {
					text: pf.const.language.RSC225
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			pf.utils.showInfoDialogCustomWidthAcceptCancelNewStyle(alertTitle, content, objInfo, '500px', function() {
				let documentDescription = $('#documentDescription').val();

				self.updateCMBPProjectsFilesDesc(id, documentDescription);
			}, function() {});
		});
	},

	insertCMBPProjectsFile() {
		let self = this;

		let parameters = {
			id: self.idProject,
			admin: self.userMail,
			fileToUpload: self.fileToUpload,
			fileToUploadDesc: self.fileToUploadDesc
		};
		ajaxComunCallWithCallback('insertCMBPProjectsFile', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Archivo subido con éxito
				let successInsertTitle = pf.const.language.RSC10;
				let successInsertContent = pf.const.language.RSC2065;
				pf.utils.showInfoDialog(successInsertTitle, successInsertContent);

				// Vaciar variable de archivo
				self.fileToUpload = null;

				// Petición de archivos de proyecto
				self.getCMBPProjectsFiles();
			}
		});
	},

	getCMBPProjectsFiles() {
		let self = this;

		let parameters = {
			id: self.idProject
		};
		ajaxComunCallWithCallback('getCMBPProjectsFiles', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Archivos de proyecto
				self.filesToUploadInfo = [];
					
				let sizeFiles = ajaxReturn.result.length;
				for(let i = 0; i < sizeFiles; i++) {
					let obj = {
						id: ajaxReturn.result[i].id,
						fecha: ajaxReturn.result[i].stampServer,
						admin: ajaxReturn.result[i].admin,
						documento: ajaxReturn.result[i].fileName,
						descripcion: ajaxReturn.result[i].descripcion,
						tamano: ajaxReturn.result[i].fileSize
					};
					self.filesToUploadInfo.push(obj);
				}

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

	deleteCMBPProjectsFileById(id, filename) {
		let self = this;

		let parameters = {
			id: self.idProject,
			projectFiles: id,
			filename: filename
		};
		ajaxComunCallWithCallback('deleteCMBPProjectsFileById', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Documento eliminado con éxito
				let successDeleteTitle = pf.const.language.RSC10;
				let successDeleteContent = pf.const.language.RSC2067;
				pf.utils.showInfoDialog(successDeleteTitle, successDeleteContent);

				// Vaciar variable de archivo
				self.fileToUpload = null;

				// Petición de archivos de proyecto
				self.getCMBPProjectsFiles();
			}
		});
	},

	updateCMBPProjectsFilesDesc(id, documentDescription) {
		let self = this;

		let parameters = {
			id: id,
			descripcion: documentDescription,
			admin: self.userMail
		};
		ajaxComunCallWithCallback('updateCMBPProjectsFilesDesc', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Documento editado con éxito
				let successTitle = pf.const.language.RSC10;
				let successContent = pf.const.language.RSC2112;
				pf.utils.showInfoDialog(successTitle, successContent);

				// Petición de archivos de proyecto
				self.getCMBPProjectsFiles();
			}
		});
	},

	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;
		}
	},

	updateCMBPProjects() {
		let self = this;

		// 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',
			id: self.idProject,
			NombreProyecto: nombreProyecto,
			FechaProyecto: self.project.FechaProyecto,
			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,
			cpgList: self.cpgList
		};
		ajaxComunCallWithCallback('updateCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				sessionStorage.setItem('countryProjectSBS', self.country.isocode);
				sessionStorage.setItem('nameProjectSBS', nombreProyecto);
				sessionStorage.setItem('leaderSBS', JSON.stringify(self.leader));
				sessionStorage.setItem('cpgListSBS', self.cpgList);

				// Si ya se creó la misión, pasará a la edición de mision
				let stampMission = sessionStorage.getItem('stampMissionSBS');
				if(stampMission == '') {
					window.location.href = '#!step_by_step_mission_new';
				} else {
					window.location.href = '#!step_by_step_mission_edit';
				}
			}
		});
	}
};