stcmbackend.productoCriterio = {
	sharedEvents(self) {
		$('#searchAlgorithmSurvey').on('click', function() {
			$('#algorithmSurvey').show();
			$('#algorithmSegmentation').hide();
			$('#selectSurveys').click();
		});

		// Input radio segmentación
		$('#searchAlgorithmSegmentation').on('click', function() {
			$('#algorithmSurvey').hide();
			$('#algorithmSegmentation').show();
			$('#selectSegmentations').click();
		});

		// Aceptar segmentaciones
		$('#selectSegmentations').on('click', function() {
			$('#segmentationClose').trigger('click');

			//Limpieza de elementos html
			$('#resultTableTabs').html('');
			$('#resultTableTabsContent').html('');

			if(self.selectedSegmentations.length > 0) {
				// Inclusividad
				if(self.selectedSegmentations.length > 1) {
					$('#inclusiveContainer').show();
				} else {
					$('#inclusiveContainer').hide();
				}

				// Lanza la creación de las tablas de objetivos
				for(let r = 0; r < self.selectedSegmentations.length; r++) {
					self.renderSegmentationSegments(r);
				}

				// Añadido para Collapse
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');
				let collapseButton = `
					<button type="button" class="btn btn-link text-body text-decoration-none arrow" data-toggle="collapse" data-target="#resultTableCollapse" data-arrow="down">
						${stcmbackend.svg.chevronDown}
					</button>
				`;
				$('#targetsSurveyTable').append(collapseButton);

				// Collapse
				$('.arrow').on('click', function() {
					let arrow = $(this).attr('data-arrow');
					let direction = '';
					if(arrow == 'left') {
						direction = stcmbackend.svg.chevronDown;
						$(this).attr('data-arrow', 'down');
					} else {
						direction = stcmbackend.svg.chevronRight;
						$(this).attr('data-arrow', 'left');
					}
					$(this).html(direction);
					$(this).parent().parent().parent().parent().find('.collapse').collapse('toggle');
				});

				$('#segmentation').val(self.selectedIDSegmentations.toString());
				$('#segmentation').attr('title', self.selectedIDSegmentations.toString());
			} else {
				$('#inclusiveContainer').hide();
				$('#targetsSurveyTable').html(pf.const.language.RSC393 + ':');
				$('#segmentation').val('');
				$('#segmentation').attr('title', '');
			}
		});

		// Guardar Criterio
		$('#subsequentStep').off().on('click', function() {
			if($('#searchAlgorithmSurvey').prop('checked')) {
				self.productSetCMBPProjectsTargets();
			} else if($('#searchAlgorithmSegmentation').prop('checked')) {
				self.productSetCMBPProjectsTargetsSegmentation();
			}
		});

		// Volver a Encuesta o Misión
		$('#previousStep').off().on('click', function() {
			// Control de tipo de misión
			if(self.product.isSurvey == '1') {
				window.location.href = '#!producto_encuesta';
			} else {
				window.location.href = '#!producto_mision_edit';
			}
		});
	},

	renderSurveysProfiling(self) {
		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title=""></th>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>
					<th scope="col" title="${pf.const.language.RSC113}">${pf.const.language.RSC113}</th>
					<th scope="col" title="${pf.const.language.RSC114}">${pf.const.language.RSC114}</th>
					<th scope="col" title="${pf.const.language.RSC116}">${pf.const.language.RSC116}</th>
					<th scope="col" title="${pf.const.language.RSC117}">${pf.const.language.RSC117}</th>
					<th scope="col" title="${pf.const.language.RSC118}">${pf.const.language.RSC118}</th>
				</tr>
			</thead>

			<thead class="filters">
				<tr>
					<td>selector</td>
					<td>id</td>
					<td>name</td>
					<td>dateCreation</td>
					<td>enabled</td>
					<td>startDate</td>
					<td>endDate</td>
					<td>remuneration</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.surveysProfiling.length;
		for(let i = 0; i < size; i++) {
			let checked = '';
			for(let j = 0; j < self.selectedSurveys.length; j++) {
				if(self.selectedSurveys[j].sid == self.surveysProfiling[i].sid) {
					checked = 'checked';
				}
			}

			table += `
				<tr id="sid-${self.surveysProfiling[i].sid}" class="c-pointer" data-id="${i}" data-sid="${self.surveysProfiling[i].sid}">
					<td class="text-center">
						<div class="div-single-selection">
							<input type="checkbox" class="selectionSurvey" ${checked}>
						</div>
					</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].sid}" data-id="${i}" data-sid="${self.surveysProfiling[i].sid}">
						${self.surveysProfiling[i].sid}
					</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].surveyls_title}">${self.surveysProfiling[i].surveyls_title}</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].datecreated}">${self.surveysProfiling[i].datecreated}</td>
					<td class="text-center">
						<span class="d-none">${(self.surveysProfiling[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveysProfiling[i].active == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].startdate}">${self.surveysProfiling[i].startdate}</td>
					<td class="text-truncate" title="${self.surveysProfiling[i].expires}">${self.surveysProfiling[i].expires}</td>
					<td class="text-center" title="${self.surveysProfiling[i].remuneracion}">${self.surveysProfiling[i].remuneracion}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

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

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

		stcmbackend.productoCriterio.eventsSurveysProfiling(self);

		$('#tableSurvey').on('draw.dt', function() {
			stcmbackend.productoCriterio.eventsSurveysProfiling(self);
		});
	},

	eventsSurveysProfiling(self) {
		// Seleccionar encuesta por tr
		$('#tableSurvey tbody tr').off().on('click', function() {
			let index = $(this).data('id');
			let id = $(this).data('sid');
			let selSurSize = self.selectedSurveys.length;
			let checked = $(this).find('.selectionSurvey').prop('checked');

			if(!checked) {
				$(this).find('.selectionSurvey').prop('checked', true);
				if(selSurSize >= self.maxSurveysProfiling) {
					let alertTitle = pf.const.language.RSC398;
					let alertText = pf.const.language.RSC1735;
					pf.utils.showInfoDialog(alertTitle, alertText);
					$(this).find('.selectionSurvey').prop('checked', false);
					return false;
				}

				if(self.surveysProfiling[index].active != '1') {
					let alertTitle = pf.const.language.RSC398;
					let alertText = pf.const.language.RSC1365;
					pf.utils.showInfoDialog(alertTitle, alertText);
					$(this).find('.selectionSurvey').prop('checked', false);
					return false;
				}

				self.selectedSurveys.push(self.surveysProfiling[index]);
			} else {
				$(this).find('.selectionSurvey').prop('checked', false);
				for(let i = 0; i < selSurSize; i++) {
					if(self.selectedSurveys[i].sid == id) {
						self.selectedSurveys.splice(i, 1);
						break;
					}
				}
			}
		});

		// Seleccionar encuesta por checbox
		$('.selectionSurvey').off().on('click', function() {
			let checked = $(this).prop('checked');

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

	eventTargetsSurvey(index, self, isEdit = false) {
		// Valores de modal
		$('.searchValues').off().on('click', function() {
			if(isEdit) {
				let qid = $(this).attr('data-qid');
				let type = $(this).attr('data-type');
				let index = $(this).data('index');
				let survey = self.selectedSurveys[index].sid;
				self.columnName = $(this).attr('data-columnName');
				stcmbackend.productoCriterio.requestSurveyValues(qid, survey, self);
			} else {
				let qid = $(this).attr('data-qid');
				self.surveyByQIDIndex = $(this).data('index');
				let survey = self.selectedSurveys[index].sid;
				self.columnName = $(this).attr('data-columnName');
				stcmbackend.productoCriterio.requestSurveyValues(qid, survey, self);
			}
		});

		// Valores de modal para preguntas tipo '5'
		$('.fiveValues').off().on('click', function() {
			let index = $(this).data('index');
			self.surveyValues = [
				{code: '1', answer: '1'},
				{code: '2', answer: '2'},
				{code: '3', answer: '3'},
				{code: '4', answer: '4'},
				{code: '5', answer: '5'}
			];
			self.columnName = $(this).attr('data-columnName');
			stcmbackend.productoCriterio.renderSurveyValues(index, self);
		});

		// Valores de modal para preguntas tipo 'K'
		$('.KValues').off().on('click', function() {
			let index = $(this).data('index');
			self.columnName = $(this).attr('data-columnName');
			self.columnNameK = $(this).attr('data-columnNameK');
			let size = self.targetsSurvey[index].length;
			for(let i = 0; i < size; i++) {
				if(self.targetsSurvey[index][i].columnName == self.columnName) {
					self.surveyValues = self.targetsSurvey[index][i].values;
					break;
				}
			}

			stcmbackend.productoCriterio.renderSurveyValues(index, self);
		});

		// Valores de texto
		$('.typeValues').off().on('change', function() {
			let columnName = $(this).attr('data-columnName');
			let index = $(this).data('index');
			let type = $(this).attr('data-type');

			let size = self.targetsSurvey[index].length;
			let code = [];
			let value = [$(this).val()];
			$('#' + columnName).find('.inputValue').attr('title', $(this).val());
			if($(this).val().indexOf('-') != -1) {
				let valueArray = $(this).val().split('-');

				for(let i = parseInt(valueArray[0]); i <= valueArray[1]; i++) {
					code.push(i);
				}

				$('#' + columnName).attr('data-inputCode', code);
				$('#' + columnName).find('.inputCode').val(code);
				$('#' + columnName).find('.inputCode').attr('title', code);

				for(let i = 0; i < size; i++) {
					if(columnName == self.targetsSurvey[index][i].columnName) {
						self.targetsSurvey[index][i].value = value;
						self.targetsSurvey[index][i].code = code;
					}
				}
			} else {
				code.push(value[0]);
				$('#' + columnName).attr('data-inputCode', code);
				$('#' + columnName).find('.inputCode').val(code);
				$('#' + columnName).find('.inputCode').attr('title', code);

				for(let i = 0; i < size; i++) {
					if(columnName == self.targetsSurvey[index][i].columnName) {
						self.targetsSurvey[index][i].value = value;
						self.targetsSurvey[index][i].code = code;
					}
				}
			}
		});
	},

	requestSurveyValues(qid, survey, self) {
		let parameters = {
			survey: survey,
			qid: qid
		};
		ajaxComunCallWithCallback('getTargetsSurveyByQID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.surveyValues = ajaxReturn.result;

				stcmbackend.productoCriterio.renderSurveyValues(self.surveyByQIDIndex, self);
			}
		});
	},

	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" ${(false ? 'checked' : '')}>
					</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.productoCriterio.selectionMult(index, self);

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

	selectionMult(index, self) {
		// 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() {
			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');
			}
		});
	}
};