let ProductoProyectoEditController = {
	user: null,
	language: '',
	leader: '',
	requestType: '',
	country: '',
	leaderModal: null,
	maxSize: 0,
	fileToUpload: null,
	fileToUploadDesc: '',
	filesToUploadInfo: [],
	userMail: '',
	idProjectProduct: null,
	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.fileToUpload = null;
		self.fileToUploadDesc = '';
		self.filesToUploadInfo = [];
		self.userMail = '';
		self.idProjectProduct = sessionStorage['idProjectProduct'];
		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;

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

		// Control nuevo / editar
		if(sessionStorage['editProductProject'] == '1') {
			$('.elementControl').prop('disabled', true);
		} else {
			$('.elementControl').prop('disabled', false);
		}

		addLoader();
		self.getCMBPProjects();

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

		// Collapse
		addEventArrowTableHeader();

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

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

		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;

		stcmbackend.productoProyecto.sharedEvents(self, 'editProductProjectLeader', 'editProductProjectCountry');

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

				self.fileToUpload = inputElement.files[0];
				self.fileToUploadDesc = inputElementDesc;

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

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

	getCMBPProjects() {
		let self = this;

		let parameters = {
			id: self.idProjectProduct
		};
		ajaxComunCallWithCallback('getCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.project = ajaxReturn.result[0]
				$('#projectName').val(self.project.NombreProyecto);
				self.country = 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));
				let numberRecords = sessionStorage.getItem('numberRecords');
				if(numberRecords === '') {
					numberRecords = 0;
				}
				$('#numberRecords').val(numberRecords);
				let projectDateArray = self.project.FechaProyecto.split(' ');
				let projectDate = projectDateArray[0].split('/');
				$('#endDate').val(projectDate[2] + '-' + projectDate[1] + '-' + projectDate[0]);

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

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

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

	editProject() {
		let self = this;

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

		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) {
			if(self.leader == '') {
				let errorTitle = pf.const.language.RSC1616;
				let errorContent = pf.const.language.RSC1728;
				pf.utils.showInfoDialog(errorTitle, errorContent);
			} else {
				let title = pf.const.language.RSC78;
				let content = pf.const.language.RSC101;
				pf.utils.showInfoDialog(title, content);
			}
			return false;
		}

		let parameters = {
			producto_proyecto: '1',
			id: self.idProjectProduct,
			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
		};
		ajaxComunCallWithCallback('updateCMBPProjects', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				sessionStorage.setItem('countryProjectProduct', self.country);
				sessionStorage.setItem('numberRecords', $('#numberRecords').val());
				sessionStorage.setItem('leader', JSON.stringify(self.leader));

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

	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.idProjectProduct + '/' + 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: self.language,
			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');
			let description = $(this).data('description');

			// 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.idProjectProduct,
			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.idProjectProduct
		};
		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.idProjectProduct,
			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();
			}
		});
	}
};