stcmbackend.proyectos = {
	sharedEvents(self) {
		$('#back').on('click', function() {
			window.location.href = '#!proyectos';
		});

		// Modal de CPG's
		$('#searchCPG').off().on('click', function() {
			if(self.cpgActive === null) {
				ajaxComunCallWithCallback('getAllCPG', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						if(ajaxReturn.result == 'No CPG defined') {
							self.cpgActive = [];
						} else {
							self.cpgActive = ajaxReturn.result;
						}

						// Tabla de resultados
						stcmbackend.proyectos.renderAllCPG(self);
					}
				});
			} else {
				$('#cpgTable').modal('show', true);
			}
		});
	},

	renderAllCPG(self) {
		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title="">
						<div class="div-global-selection">
							<input type="checkbox" class="globalSelectionCPG">
						</div>
					</th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC550}">${pf.const.language.RSC550}</th>
					<th scope="col" title="${pf.const.language.RSC1540}">${pf.const.language.RSC1540}</th>
					<th scope="col" title="${pf.const.language.RSC1541}">${pf.const.language.RSC1541}</th>
					<th scope="col" title="${pf.const.language.RSC1542}">${pf.const.language.RSC1542}</th>
				</tr>
			</thead>

			<thead class="filtersCPG">
				<tr>
					<td>selector</td>
					<td>id</td>
					<td>pais</td>
					<td>razonSocial</td>
					<td>nombreComercial</td>
					<td>identFiscal</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Array de CPG's seleccionado
		let cpgListArray = self.cpgList.split(',');

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.cpgActive.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if((self.cpgActive[i].country != '' && allowedCountries.indexOf(self.cpgActive[i].country) == -1) || self.cpgActive[i].activo == '0') {
				continue;
			}

			let checked = '';
			if(cpgListArray.indexOf(self.cpgActive[i].idCPG) != -1) {
				checked = 'checked';
			}

			table += `
				<tr class="c-pointer check-select-cpg" data-id="${self.cpgActive[i].idCPG}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selectionCPG" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.cpgActive[i].idCPG}">${self.cpgActive[i].idCPG}</td>
					<td class="text-truncate" title="${self.cpgActive[i].country}">${self.cpgActive[i].country}</td>
					<td class="text-truncate" title="${self.cpgActive[i].razonSocial}">${self.cpgActive[i].razonSocial}</td>
					<td class="text-truncate" title="${self.cpgActive[i].nombreComercial}">${self.cpgActive[i].nombreComercial}</td>
					<td class="text-truncate" title="${self.cpgActive[i].identFiscal}">${self.cpgActive[i].identFiscal}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let tableCPG = $('#tableCPG').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0},
				{width: '30px', targets: 1},
				{width: '60px', targets: 2}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			tableCPG.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableCPG, 'filtersCPG');

		stcmbackend.proyectos.multiSelectTableEventsCPG();

		$('#tableCPG').on('draw.dt', function() {
			stcmbackend.proyectos.multiSelectTableEventsCPG();
		});

		$('#addCPG').off().on('click', function() {
			let addCPG = [];
			$('#tableCPG tr').each(function() {
				let cheked = $(this).find('.selectionCPG');
				if(cheked.prop('checked')) {
					let idCPG = $(this).data('id');
					addCPG.push(idCPG);
				}
			});

			self.cpgList = addCPG.toString();
			if(self.cpgList == '') {
				self.cpgList = sessionStorage['STCMBackEnd:idCPG'];
			}

			$('#cpgList').val(self.cpgList);
			$('#cpgList').attr('title', self.cpgList);

			$('#closeCPG').trigger('click');
		});
	},

	multiSelectTableEventsCPG() {
		inputControl();

		// Selección por tr
		$('#tableCPG tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selectionCPG').prop('checked');

			if(checkedComp) {
				$(this).find('.selectionCPG').prop('checked', false);
			} else {
				$(this).find('.selectionCPG').prop('checked', true);
			}

			inputControl();
		});

		// Selección por input check
		$('.selectionCPG').off().on('click', function() {
			let checkedComp = $(this).prop('checked');

			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			inputControl();
		});

		// Marcar desmarcar todo
		$('.globalSelectionCPG').off().on('change', function() {
			if($('.globalSelectionCPG').prop('checked')) {
				$('.selectionCPG').prop('checked', true);
			} else {
				$('.selectionCPG').prop('checked', false);
			}
		});

		function inputControl() {
			// Estado del input global con respecto a los inputs en página
			if($('.selectionCPG').length == $('.selectionCPG:checked').length && $('.selectionCPG').length > 0) {
				$('.globalSelectionCPG').prop('checked', true);
			} else {
				$('.globalSelectionCPG').prop('checked', false);
			}
		}
	},

	renderSurveyValues(index, self) {
		if(self.renderSurveyValuesFlag) {
			$('#tableValues').dataTable().fnDestroy();
		} else {
			self.renderSurveyValuesFlag = true;
		}

		// Nombre/code sacado del modal
		let table = `
			<thead>
				<tr>
					<th scope="col">
						${pf.const.language.RSC406}
						<input id="selectionAll" type="checkbox" class="align-middle">
					</th>
					<th scope="col">${pf.const.language.RSC127}</th>
				</tr>
			</thead>

			<thead class="filtersValue">
				<tr>
					<td>checkbox</td>
					<td>answerName</td>
				</tr>
			</thead>

			<tbody>
		`;

		let controlChecks = [];
		let typeK = false;
		let questionSize = self.targetsSurvey[index].length;
		for(let i = 0; i < questionSize; i++) {
			if(self.targetsSurvey[index][i].columnName == self.columnName && self.targetsSurvey[index][i].type != 'K' && self.targetsSurvey[index][i].type != 'A' && self.targetsSurvey[index][i].type != 'B') {
				controlChecks = self.targetsSurvey[index][i].code;
			} else if(self.targetsSurvey[index][i].columnName == self.columnName && (self.targetsSurvey[index][i].type == 'K' || self.targetsSurvey[index][i].type == 'A' || self.targetsSurvey[index][i].type == 'B')) {
				typeK = true;
				controlChecks = self.targetsSurvey[index][i].code[self.columnNameK];
			}
		}
		let size = self.surveyValues.length;
		for(let i = 0; i < size; i++) {
			let checked = false;
			if(typeK) {
				checked = (controlChecks.indexOf(String(self.surveyValues[i].code)) != -1 ? true : false);
			} else {
				checked = (controlChecks.indexOf(self.surveyValues[i].code) != -1 ? true : false);
			}

			let answer = self.surveyValues[i].answer;
			switch(answer) {
				case 'Y':
					answer = pf.const.language.RSC120;
					break;
				case 'N':
					answer = pf.const.language.RSC121;
					break;
				case 'M':
					answer = pf.const.language.RSC556;
					break;
				case 'F':
					answer = pf.const.language.RSC557;
					break;
			}
			let code = self.surveyValues[i].code || self.surveyValues[i].title;

			table += `
				<tr class="c-pointer check-select" data-value="${self.surveyValues[i].answer}" data-code="${code}">
					<td class="text-center">
						<span class="d-none">${(checked ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" class="selection" ${(checked ? 'checked' : '')}>
					</td>
					<td class="value">${answer}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let ObjetiveTable = $('#tableValues').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '130px', targets: 0}
			],
			ordering: false,
			aaSorting: []
		});

		setTimeout(function() {
			ObjetiveTable.columns.adjust();
		}, 200);

		// Apply the search
		applyTheSearch(ObjetiveTable, 'filtersValue');

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

		if($('.selection').length == $('.selection:checked').length) {
			$('#selectionAll').prop('checked', true);
		} else {
			$('#selectionAll').prop('checked', false);
		}

		// Selección de múltiples encuestas
		stcmbackend.proyectos.selectionMult(index, self, ObjetiveTable);

		$('#tableValues').on('draw.dt', function() {
			stcmbackend.proyectos.selectionMult(index, self, ObjetiveTable);
		});
	},

	selectionMult(index, self, ObjetiveTable) {
		// Selección por tr
		$('.check-select').off().on('click', function() {
			let checkedComp = $(this).find('.selection').prop('checked');
			if(checkedComp) {
				$(this).find('.selection').prop('checked', false);
			} else {
				$(this).find('.selection').prop('checked', true);
			}

			if($('.selection').length == $('.selection:checked').length) {
				$('#selectionAll').prop('checked', true);
			} else {
				$('#selectionAll').prop('checked', false);
			}
		});

		// Selección por input
		$('.selection').off().on('click', function() {
			let checkedComp = $(this).prop('checked');
			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			if($('.selection').length == $('.selection:checked').length) {
				$('#selectionAll').prop('checked', true);
			} else {
				$('#selectionAll').prop('checked', false);
			}
		});

		// La id del elemento principal modifica los elementos secundarios a través de su clase
		$('#selectionAll').on('click', function() {
			$('.selection').prop('checked', this.checked);
		});

		$('#selectValues').off().on('click', function() {
			ObjetiveTable.destroy();

			let valueArray = [];
			let codeArray = [];
			let nameArray = [];

			$('#tableValues tr').each(function() {
				let cheked = $(this).find('.selection');
				if(cheked.prop('checked')) {
					valueArray.push($(this).attr('data-value'));
					codeArray.push($(this).attr('data-code'));
					nameArray.push($(this).find('.value').text());
				}
			});

			let typeK = false;
			let size = self.targetsSurvey[index].length;
			for(let i = 0; i < size; i++) {
				if(self.columnName == self.targetsSurvey[index][i].columnName && self.targetsSurvey[index][i].type != 'K') {
					self.targetsSurvey[index][i].value = valueArray;
					self.targetsSurvey[index][i].code = codeArray;
				} else if(self.columnName == self.targetsSurvey[index][i].columnName && self.targetsSurvey[index][i].type == 'K') {
					typeK = true;
					self.targetsSurvey[index][i].value[self.columnNameK] = valueArray;
					self.targetsSurvey[index][i].code[self.columnNameK] = codeArray;
				}
			}

			if(typeK) {
				$('#' + self.columnNameK).find('.inputValue').val(nameArray);
				$('#' + self.columnNameK).find('.inputValue').attr('title', nameArray);
				$('#' + self.columnNameK).attr('data-inputCode', codeArray);
				$('#' + self.columnNameK).find('.inputCode').val(codeArray);
				$('#' + self.columnNameK).find('.inputCode').attr('title', codeArray);
				$('#closeValues').trigger('click');
			} else {
				$('#' + self.columnName).find('.inputValue').val(nameArray);
				$('#' + self.columnName).find('.inputValue').attr('title', nameArray);
				$('#' + self.columnName).attr('data-inputCode', codeArray);
				$('#' + self.columnName).find('.inputCode').val(codeArray);
				$('#' + self.columnName).find('.inputCode').attr('title', codeArray);
				$('#closeValues').trigger('click');
			}
		});
	},

	/* TTT En proceso JIRA 3252 */
	getCatalogacionesM(self) {
		if(self.catalogingValues.length == 0) {
			ajaxComunCallWithCallback('getCatalogacionesM', {}, function(ajaxReturn) {
				if(ajaxReturn) {
					self.catalogingValues = ajaxReturn.result;
					console.log(self.catalogingValues);

					// Tabla de resultados
					stcmbackend.proyectos.renderCataloging(self);
					$('#catalogingTable').modal('show');
				}
			});
		} else {
			$('#catalogingTable').modal('show');
		}
	},

	renderCataloging(self) {
		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title="">
						<div class="div-global-selection">
							<input type="checkbox" class="globalSelectionCataloging">
						</div>
					</th>
					<th scope="col" title="${pf.const.language.RSC187}">${pf.const.language.RSC187}</th>
					<th scope="col" title="${pf.const.language.RSC363}">${pf.const.language.RSC363}</th>
					<th scope="col" title="${pf.const.language.RSC365}">${pf.const.language.RSC365}</th>
				</tr>
			</thead>

			<thead class="filtersCataloging">
				<tr>
					<td>selector</td>
					<td>catalogacion</td>
					<td>desde</td>
					<td>hasta</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.catalogingValues.length;
		for(let i = 0; i < size; i++) {
			let checked = '';
			if(self.catalogingIdSelected.includes(self.catalogingValues[i].id)) {
				checked = 'checked';
			}

			table += `
				<tr class="c-pointer check-select-cpg" data-id="${self.catalogingValues[i].id}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selectionCataloging" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.catalogingValues[i].catalogacion}">${self.catalogingValues[i].catalogacion}</td>
					<td class="text-truncate" title="${self.catalogingValues[i].rangoDesde}">${self.catalogingValues[i].rangoDesde}</td>
					<td class="text-truncate" title="${self.catalogingValues[i].rangoHasta}">${self.catalogingValues[i].rangoHasta}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let tableCataloging = $('#tableCataloging').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			columnDefs: [
				{width: '25px', orderable: false, targets: 0}
			],
			autoWidth: false,
			aaSorting: []
		});

		setTimeout(function() {
			tableCataloging.columns.adjust();
		}, 200);

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

		// Apply the search
		applyTheSearch(tableCataloging, 'filtersCataloging');

		stcmbackend.proyectos.multiSelectTableEventsCataloging();

		$('#tableCataloging').on('draw.dt', function() {
			stcmbackend.proyectos.multiSelectTableEventsCataloging();
		});

		$('#addCataloging').off().on('click', function() {
			let addCataloging = [];
			$('#tableCataloging tr').each(function() {
				let cheked = $(this).find('.selectionCataloging');
				if(cheked.prop('checked')) {
					let idCataloging = $(this).data('id');
					addCataloging.push(idCataloging);
				}
			});

			self.catalogingIdSelected = addCataloging;

			$('#closeCataloging').trigger('click');
		});
	},

	multiSelectTableEventsCataloging() {
		inputControlCataloging();

		// Selección por tr
		$('#tableCataloging tbody tr').off().on('click', function() {
			let checkedComp = $(this).find('.selectionCataloging').prop('checked');

			if(checkedComp) {
				$(this).find('.selectionCataloging').prop('checked', false);
			} else {
				$(this).find('.selectionCataloging').prop('checked', true);
			}

			inputControlCataloging();
		});

		// Selección por input check
		$('.selectionCataloging').off().on('click', function() {
			let checkedComp = $(this).prop('checked');

			if(checkedComp) {
				$(this).prop('checked', false);
			} else {
				$(this).prop('checked', true);
			}

			inputControlCataloging();
		});

		// Marcar desmarcar todo
		$('.globalSelectionCataloging').off().on('change', function() {
			if($('.globalSelectionCataloging').prop('checked')) {
				$('.selectionCataloging').prop('checked', true);
			} else {
				$('.selectionCataloging').prop('checked', false);
			}
		});

		function inputControlCataloging() {
			// Estado del input global con respecto a los inputs en página
			if($('.selectionCataloging').length == $('.selectionCataloging:checked').length && $('.selectionCataloging').length > 0) {
				$('.globalSelectionCataloging').prop('checked', true);
			} else {
				$('.globalSelectionCataloging').prop('checked', false);
			}
		}
	}
	/* TTT En proceso JIRA 3252 */
};