let SegmentacionesEditController = {
	user: null,
	language: '',
	segmentationID: '',
	survey: '',
	attTableArray: [],
	segTableArray: [],
	segStringArray: [],
	questionFlag: false,
	questions: [],
	optionFlag: false,
	options: [],
	editSegmentation: {},
	segmentationResult: '',
	country: '',
	disabled: '',
	dNone: '',

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.segmentationID = atob(sessionStorage.getItem('idSegmentacion'));
		self.survey = '';
		self.attTableArray = [];
		self.segTableArray = [];
		self.segStringArray = [];
		self.questionFlag = false;
		self.questions = [];
		self.optionFlag = false;
		self.options = [];
		self.editSegmentation = {
			descripcion: '',
			sid: '',
			attributos: [],
			segmentos: []
		};
		self.segmentationResult = '';
		self.country = '';
		self.disabled = '';
		self.dNone = '';
	},

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

		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		let userMail = user.email;
		let user_split = userMail.split('@');
		self.user = user_split[0].replace('.', '_');

		let editSegmentation = sessionStorage['STCMBackEnd:editSegmentation'];
		if(editSegmentation == '0') {
			self.disabled = 'disabled';
			$('.editNone').prop('disabled', true);
			self.dNone = 'd-none';
		}

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

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC1741 + ' - ' + pf.const.language.RSC225);

		// Opciones de header
		let jsonsubopt = {
			back: 'back',
			save: 'save',
			run: 'run'
		};

		let nav = `
			<div class="row mx-0">
				${createSubOptionExecuteSeg(jsonsubopt.run)}
				${createSubOptionSave(jsonsubopt.save)}
			</div>

			${createSubOptionBack(jsonsubopt.back)}
		`;

		// Acciones de página (flex-row-reverse)s
		$('#page-actions').html(nav);

		// Botón principal
		$('#save').addClass('main-button');

		// Botones secundarios
		$('#back').addClass('secondary-button');
		$('#run').addClass('secondary-button');

		// Ocultación de la sección de Resultado de la segmentación
		$('#segResult').hide();

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

		self.getSegmentacion();

		// Collapse
		addEventArrowTableHeader();

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

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

		// TITLES
		$('.addTitle').attr('title', pf.const.language.RSC93);
		$('.exportTitle').attr('title', pf.const.language.RSC47);
	},

	applyEvents() {
		let self = this;

		stcmbackend.segmentaciones.sharedEvents(self, 'editSegmentCountry', 'editSegmentation');

		// Añadir atributos
		$('#newAttribute').off().on('click', function() {
			let obj = {
				name: '',
				question: '',
				columnName: '',
				answer: '',
				code: ''
			};
			self.attTableArray.push(obj);

			self.tableAtt();
		});

		// Añadir segmentos
		$('#newSegment').off().on('click', function() {
			// Cantidad actual de segmentos
			let segSize = self.segStringArray.length;

			// Nuevo array para segmentos
			let newSegTableArray = [];

			// Contador para usar los diferentes nombre de atributos
			let attCount = 0

			for(let i = 0; i < self.segTableArray.length; i++) {
				// Segmento ya existente
				newSegTableArray.push(self.segTableArray[i]);

				if((i + 1) % segSize === 0) {
					let obj = {
						name: '',
						value: 0,
						attributoDesc: (self.attTableArray[attCount] === undefined ? '0' : self.attTableArray[attCount].name)
					};
					// Inserción de nuevo segmento con el nombre de atributo que le corresponde
					newSegTableArray.push(obj);
					attCount++;
				}
			}
			self.segTableArray = newSegTableArray;
			self.segStringArray.push('');

			self.tableSeg();
			self.tableVal();
		});

		// Guardar segmentación editada
		$('#save').off().on('click', function() {
			self.checkSegmentation(false);
		});

		// Ejecutar segmentación
		$('#run').off().on('click', function() {
			self.checkSegmentation(true);
		});
	},

	getSegmentacion() {
		let self = this;

		let parameters = {
			idSegmentacion: self.segmentationID
		};
		ajaxComunCallWithCallback('getSegmentacion', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resSeg = ajaxReturn.result[0];
				// Nombre / Descripción
				$('#name').val(resSeg.Descripcion);

				// País
				self.country = resSeg.country
				$('#segmentCountry').val(self.country);

				// Identificador de encuesta
				self.survey = resSeg.sid;
				$('#surveyProfiling').val(self.survey);

				// Nombre de encuesta
				$('#surveyProfilingName').val(resSeg.surveyls_title);

				// Atributos
				let attSize = resSeg.attributes.length;
				for(let i = 0; i < attSize; i++) {
					let obj = {
						name: resSeg.attributes[i].Descripcion,
						question: resSeg.attributes[i].qidDescription,
						columnName: resSeg.attributes[i].qid,
						answer: resSeg.attributes[i].qidOptionDescription,
						code: resSeg.attributes[i].qidOption
					};
					self.attTableArray.push(obj);
				}

				// Segmentos
				let segSize = resSeg.segmentos.length;
				for(let i = 0; i < segSize; i++) {
					let obj = {
						name: resSeg.segmentos[i].Descripcion,
						value: resSeg.segmentos[i].value,
						attributoDesc: resSeg.segmentos[i].attributoDesc
					};
					self.segTableArray.push(obj);
					if(self.segStringArray.indexOf(resSeg.segmentos[i].Descripcion) === -1) {
						self.segStringArray.push(resSeg.segmentos[i].Descripcion);
					}
				}

				// Resultados de la segmentación
				if(ajaxReturn.segmentationResult.length > 0) {
					$('#segResult').show();
					self.segmentationResult = ajaxReturn.segmentationResult;
					self.tableSegResult();
				}

				self.tableAtt();
				self.tableSeg();
				self.tableVal();
			}
		});
	},

	clickEvents(data) {
		let self = this;

		self.country = data.isocode;
		$('#segmentCountry').val(self.country);
	},

	clickSurvey(survey) {
		let self = this;

		self.attTableArray = [];
		self.segTableArray = [];
		self.segStringArray = [];

		self.survey = survey.sid;
		$('#surveyProfiling').val(survey.sid);
		$('#surveyProfilingName').val(survey.surveyls_title);
		self.tableAtt();
		self.tableSeg();
		self.tableVal();
	},

	tableAtt() {
		let self = this;

		$('#attTable').html('');

		let table = `
			<table id="tableAttTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}<span class="text-danger">*</span></th>
						<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}<span class="text-danger">*</span></th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.attTableArray.length;
		if(size < 1) {
			let obj = {
				name: '',
				question: '',
				columnName: '',
				answer: '',
				code: ''
			};
			self.attTableArray.push(obj);
			size = 1;
		}

		for(let i = 0; i < size; i++) {
			let disabledQ = self.survey == '' ? 'disabled' : '';
			let disabledO = self.attTableArray[i].question == '' ? 'disabled' : '';
			let qid = '';
			if(self.attTableArray[i].columnName !== '') {
				let qidArray = self.attTableArray[i].columnName.split('X');
				qid = qidArray.pop();
			}
			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span id="valueAttrName${i}" class="d-none">${self.attTableArray[i].name}</span>
						<input id="valueAttrNameInput${i}" type="text" class="form-control valueNameInput" value="${self.attTableArray[i].name}" title="${self.attTableArray[i].name}" ${self.disabled}>
					</td>
					<td class="text-truncate tableName p-1">
						<span class="d-none">${self.attTableArray[i].question}</span>
						<div class="form-group mb-0">
							<div class="input-group new-input-style">
								<input id="question_${i}" type="text" class="form-control" value="${self.attTableArray[i].question}" title="${self.attTableArray[i].question}" disabled>
								<div class="input-group-append">
									<button id="btn-question_${i}" type="button" class="btn btn-outline-secondary btn_question" data-toggle="modal" data-target="#modalQuestions" ${disabledQ} ${self.disabled}>
										${stcmbackend.svg.threeDots}
									</button>
								</div>
							</div>
						</div>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteAttrTables ${self.dNone}" data-id="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

		let tableAttTables = $('#tableAttTables').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 2}
			],
			ordering: false,
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1747,
				className: 'd-none',
				title: pf.const.language.RSC1747,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Exportar tabla
		$('#attributeExport').off().on('click', function() {
			$('#attTable .buttons-excel').trigger('click');
		});

		self.tableAttEvents();
	},

	tableAttEvents() {
		let self = this;

		// Input nombre
		$('.valueNameInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('valueAttrNameInput', '');
			let value = $(this).val();
			let attNameOld = self.attTableArray[index].name;
			// Actualizar nombre de atributo
			self.attTableArray[index].name = value;

			if(attNameOld === '') {
				// Añadir nuevos segmentos para el nuevo atributo
				for(let i = 0; i < self.segStringArray.length; i++) {
					let obj = {
						name: self.segStringArray[i],
						value: 0,
						attributoDesc: value
					};
					self.segTableArray.push(obj);
				}
			} else {
				// Actualizar segmentos con el nuevo nombre de atributo
				for(let i = 0; i < self.segTableArray.length; i++) {
					if(self.segTableArray[i].attributoDesc === attNameOld) {
						self.segTableArray[i].attributoDesc = value;
					}
				}
			}

			self.tableVal();
		});

		stcmbackend.segmentaciones.tableAttEvents(self);

		// Modal de Preguntas
		$('.btn_question').off().on('click', function() {
			let index = $(this).attr('id').replace('btn-question_', '');
			if(self.questionFlag) {
				$('#tableQuestions').dataTable().fnDestroy();
			} else {
				self.questionFlag = true;
			}
			self.getQuestionsSurvey(index);
		});

		// Modal de Opciones
		$('.btn_option').off().on('click', function() {
			let index = $(this).attr('id').replace('btn-option_', '');
			let qid = $(this).data('qid');
			if(self.optionFlag) {
				$('#tableOptions').dataTable().fnDestroy();
			} else {
				self.optionFlag = true;
			}
			self.getAllPosibleAnswersByQID(index, qid);
		});

		// Eliminar registro
		$('.deleteAttrTables').off().on('click', function() {
			let index = $(this).data('id');
			let name = self.attTableArray[index].name;

			// Nuevo array para segmentos eliminando los segmentos del atributo a borrar
			let newSegTableArray = [];
			for(let i = 0; i < self.segTableArray.length; i++) {
				if(self.segTableArray[i].attributoDesc !== name) {
					newSegTableArray.push(self.segTableArray[i]);
				}
			}
			self.segTableArray = newSegTableArray;

			self.attTableArray.splice(index, 1);
			self.tableAtt();
			self.tableVal();
		});
	},

	getQuestionsSurvey(index) {
		let self = this;

		let parameters = {
			survey: self.survey
		};
		ajaxComunCallWithCallback('getQuestionsSurvey', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				// Array de tipos de preguntas para mostrar
				let questFilterArray = ['6', ':', 'F', 'K', 'R', '!', '3', '4', 'N', 'L', '5', 'O'];
				self.questions = [];

				let size = ajaxReturn.result.length;
				let objAux;
				for(let i = 0; i < size; i++) {
					objAux = ajaxReturn.result[i];
					// Control de que solo muestre las preguntas del tipo indicado
					if(questFilterArray.indexOf(objAux.type) === -1) {
						continue;
					}

					let question = objAux.question.replace(/<[^>]*>?/g, '');
					if(objAux.type == 'K' || (objAux.type == 'F' && objAux.valuesSQ.length > 0)) {
						let sizeK = objAux.valuesSQ.length;
						for(let j = 0; j < sizeK; j++) {
							let valuesSQArray = objAux.valuesSQ[j].split('|');
							let columnNameK = valuesSQArray[0];
							let questionK = question.trim() + '<br>' + valuesSQArray[1].replace(';', '');
							let obj = {
								question: questionK,
								columnName: columnNameK,
								sid: objAux.sid,
								gid: objAux.gid,
								qid: objAux.qid2,
								title: objAux.title,
								type: objAux.type
							};
							self.questions.push(obj);
						}
					} else if(objAux.type == '6') {
						let size6 = objAux.valuesSQ.length - 1;
						let valuesSQArray = objAux.valuesSQ[size6].split('|');
						let columnName6 = valuesSQArray[0];
						let question6 = question.trim() + '<br>' + valuesSQArray[1].replace(';', '');
						let obj = {
							question: question6,
							columnName: columnName6,
							sid: objAux.sid,
							gid: objAux.gid,
							qid: objAux.qid2,
							title: objAux.title,
							type: objAux.type
						};
						self.questions.push(obj);
					} else {
						let obj = {
							question: question,
							columnName: objAux.columnName,
							sid: objAux.sid,
							gid: objAux.gid,
							qid: objAux.qid2,
							title: objAux.title,
							type: objAux.type
						};
						self.questions.push(obj);
					}
				}

				self.renderQuestions(index);

				if(self.questions.length === 0) {
					let warningTitle = pf.const.language.RSC1741;
					let warningContent = pf.const.language.RSC1774;
					pf.utils.showInfoDialog(warningTitle, warningContent);
				}
			}
		});
	},

	renderQuestions(index) {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC366}">${pf.const.language.RSC366}</th>
					<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
				</tr>
			</thead>

			<thead class="filtersQuest">
				<tr>
					<td>columnName</td>
					<td>question</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.questions.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-order="${i}">
					<td class="columnName" title="${self.questions[i].columnName}">${self.questions[i].columnName}</td>
					<td class="question" title="${self.questions[i].question}">${self.questions[i].question}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableQuestions, 'filtersQuest');

		$('#tableQuestions tbody').off().on('click', 'tr', function() {
			let indexQuest = $(this).data('order')

			$('#question_' + index).val(self.questions[indexQuest].question);
			$('#question_' + index).attr('title' ,self.questions[indexQuest].question);
			$('#btn-option_' + index).data('qid' ,self.questions[indexQuest].qid);
			self.attTableArray[index].question = self.questions[indexQuest].question;
			self.attTableArray[index].columnName = self.questions[indexQuest].columnName;
			$('#btn-option_' + index).prop('disabled', false);
			$('#closeQuestions').trigger('click');
			self.tableVal();
		});
	},

	getAllPosibleAnswersByQID(index, qid) {
		let self = this;

		let parameters = {
			survey: self.survey,
			qid: qid,
			title: $('#surveyProfilingName').val(),
			Pregunta: self.attTableArray[index].columnName
		};
		ajaxComunCallWithCallback('getAllPosibleAnswersByQID', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.options = ajaxReturn.result;
				self.renderOptions(index);
			}
		});
	},

	renderOptions(index) {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC437}">${pf.const.language.RSC437}</th>
					<th scope="col" title="${pf.const.language.RSC127}">${pf.const.language.RSC127}</th>
				</tr>
			</thead>

			<thead class="filtersOptions">
				<tr>
					<td>code</td>
					<td>answer</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.options.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr class="c-pointer" data-order="${i}">
					<td title="${self.options[i].code}">${self.options[i].code}</td>
					<td title="${self.options[i].answer}">${self.options[i].answer}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableOptions, 'filtersOptions');

		$('#tableOptions tbody').off().on('click', 'tr', function() {
			let indexOption = $(this).data('order')

			$('#option_' + index).val(self.options[indexOption].answer);
			$('#option_' + index).attr('title' ,self.options[indexOption].answer);
			self.attTableArray[index].answer = self.options[indexOption].answer;
			self.attTableArray[index].code = self.options[indexOption].code;
			$('#closeOptions').trigger('click');
			self.tableVal();
		});
	},

	tableSeg() {
		let self = this;

		$('#segTable').html('');

		let table = `
			<table id="tableSegTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}<span class="text-danger">*</span></th>
						<th scope="col" title=""></th>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.segTableArray.length;
		if(size < 1) {
			let obj = {
				name: '',
				value: 0,
				attributoDesc: 0
			};
			self.segTableArray.push(obj);
		}

		let sizeString = self.segStringArray.length;
		if(sizeString < 1) {
			self.segStringArray.push('');
			sizeString = 1;
		}

		for(let i = 0; i < sizeString; i++) {
			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span id="valueSegName${i}" class="d-none">${self.segStringArray[i]}</span>
						<input id="valueSegNameInput${i}" type="text" class="form-control valueSegNameInput" value="${self.segStringArray[i]}" title="${self.segStringArray[i]}" ${self.disabled}>
					</td>
					<td class="text-truncate text-center" title="${pf.const.language.RSC226}">
						<span class="c-pointer deleteSegTables ${self.dNone}" data-id="${i}">
							${stcmbackend.svg.bigTrash}
						</span>
					</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

		let tableSegTables = $('#tableSegTables').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			columnDefs: [
				{width: '30px', targets: 1}
			],
			ordering: false,
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC1748,
				className: 'd-none',
				title: pf.const.language.RSC1748,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Exportar tabla
		$('#segmentExport').off().on('click', function() {
			$('#segTable .buttons-excel').trigger('click');
		});

		self.tableSegEvents();
	},

	tableSegEvents() {
		let self = this;

		// Input nombre
		$('.valueSegNameInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('valueSegNameInput', '');
			let value = $(this).val();

			// Control para que no se repitan los nombres de los segmentos
			let size = self.segTableArray.length;
			for(let i = 0; i < size; i++) {
				if(value == self.segTableArray[i].name && value !== '' && i != index) {
					let warningTitle = pf.const.language.RSC1748;
					let warningContent = pf.const.language.RSC1793;
					pf.utils.showInfoDialog(warningTitle, warningContent);
					$(this).val('');
					return false;
				}
			}

			let quantity = self.segStringArray.length;
			for(let i = parseInt(index); i < self.segTableArray.length; i += quantity) {
				self.segTableArray[i].name = value;
			}

			self.segStringArray[index] = value;
			self.tableVal();
		});

		// Restricciones de carácteres por tecla
		$('.valueSegNameInput').off().on('keypress', function(e) {
			// Parámetros: tecla, warningTitle, warningContent y pattern si no es el general
			let result = characterRestrictionsPerKey(e.keyCode, pf.const.language.RSC375, pf.const.language.RSC1762);

			return result;
		});

		// Restricciones de carácteres por pegado
		$('.valueSegNameInput').on('paste', function() {
			// Parámetros: elemento, warningTitle, warningContent y pattern si no es el general
			characterRestrictionsPerPaste($(this), pf.const.language.RSC375, pf.const.language.RSC1762);
		});

		// Eliminar registro
		$('.deleteSegTables').off().on('click', function() {
			let index = $(this).data('id');
			let value = self.segStringArray[index];
			let delIndex = [];

			for(let i = 0; i < self.segTableArray.length; i++) {
				if(self.segTableArray[i].name === value) {
					delIndex.push(i);
				}
			}

			for(let d = 0; d < delIndex.length; d++) {
				self.segTableArray.splice((delIndex[d] - d), 1);
			}

			self.segStringArray.splice(index, 1);

			self.tableSeg();
			self.tableVal();
		});
	},

	tableVal() {
		let self = this;

		let headValues = '';

		let segSize = self.segStringArray.length;
		for(let i = 0; i < segSize; i++) {
			if(self.segStringArray[i] === '') {
				continue;
			}

			headValues += `<th scope="col" title="${self.segStringArray[i]}">${self.segStringArray[i]}</th>`;
		}

		let table = `
			<table id="tableValTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC1750}">${pf.const.language.RSC1750}</th>
						<th scope="col" title="${pf.const.language.RSC111}">${pf.const.language.RSC111}</th>
						${headValues}
					</tr>
				</thead>

				<tbody>
		`;

		let counter = 0;
		let attSize = self.attTableArray.length;
		for(let i = 0; i < attSize; i++) {
			if(self.attTableArray[i].name === '') {
				continue;
			}
			let bodyValues = '';

			let segSize = self.segStringArray.length;
			for(let j = 0; j < segSize; j++) {
				if(self.segTableArray[counter].name === '') {
					counter++;
					continue;
				}

				bodyValues += `
					<td class="text-truncate p-1">
						<span id="valValue_${counter}" class="d-none">${self.segTableArray[counter].value}</span>
						<input id="valValueInput_${counter}" type="number" class="form-control valValueInput" value="${self.segTableArray[counter].value}" title="${self.segTableArray[counter].value}" ${self.disabled}>
					</td>
				`;

				counter++;
			}

			table += `
				<tr data-id="id${i}">
					<td class="text-truncate p-1">
						<span class="d-none">${self.attTableArray[i].name}</span>
						<input type="text" class="form-control" value="${self.attTableArray[i].name}" title="${self.attTableArray[i].name}" disabled>
					</td>
					<td class="text-truncate p-1">
						<span class="d-none">${self.attTableArray[i].question}</span>
						<input type="text" class="form-control" value="${self.attTableArray[i].question}" title="${self.attTableArray[i].question}" disabled>
					</td>
					${bodyValues}
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

		let tableValTables = $('#tableValTables').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			autoWidth: false,
			ordering: false,
			aaSorting: [],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC402,
				className: 'd-none',
				title: pf.const.language.RSC402,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Exportar tabla
		$('#valuesExport').off().on('click', function() {
			$('#valTable .buttons-excel').trigger('click');
		});

		self.tableValEvents();
	},

	tableValEvents() {
		let self = this;

		// Input Valor
		$('.valValueInput').off().on('blur', function() {
			let index = $(this).attr('id').replace('valValueInput_', '');
			let value = $(this).val();

			if(value === '') {
				value = 0;
				$(this).val(0);
			}

			self.segTableArray[index].value = value;
		});
	},

	checkSegmentation(run) {
		let self = this;

		checkControl = true;
		self.editSegmentation = {
			descripcion: '',
			sid: '',
			attributos: [],
			segmentos: []
		};

		// Nombre / Descripción
		let name = $('#name').val().trim();
		if(name === '') {
			$('#name').addClass('is-invalid');
			$('[for="name"]').addClass('is-invalid');
			checkControl = false;
		} else {
			$('#name').removeClass('is-invalid');
			$('[for="name"]').removeClass('is-invalid');
			self.editSegmentation.descripcion = name;
		}

		// País
		if(self.country === '') {
			$('#segmentCountry').addClass('is-invalid');
			$('#segmentCountry-group').addClass('group-invalid');
			$('[for="segmentCountry"]').addClass('is-invalid');
			checkControl = false;
		} else {
			$('#segmentCountry').removeClass('is-invalid');
			$('#segmentCountry-group').removeClass('group-invalid');
			$('[for="segmentCountry"]').removeClass('is-invalid');
		}

		// Identificador de encuesta
		let sid = $('#surveyProfiling').val();
		if(sid === '') {
			$('#surveyProfiling').addClass('is-invalid');
			$('#surveyProfiling-group').addClass('group-invalid');
			$('[for="surveyProfiling"]').addClass('is-invalid');
			checkControl = false;
		} else {
			$('#surveyProfiling').removeClass('is-invalid');
			$('#surveyProfiling-group').removeClass('group-invalid');
			$('[for="surveyProfiling"]').removeClass('is-invalid');
			self.editSegmentation.sid = sid;
		}

		// Atributos
		let attSize = self.attTableArray.length;
		for(let i = 0; i < attSize; i++) {
			if(self.attTableArray[i].name === '' && self.attTableArray[i].columnName === '' && self.attTableArray[i].code === '') {
				continue;
			} else if(self.attTableArray[i].name === '' || self.attTableArray[i].columnName === '' || self.attTableArray[i].code === '') {
				if(self.attTableArray[i].name === '') {
					$('#valueAttrNameInput' + i).addClass('is-invalid');
					checkControl = false;
				} else {
					$('#valueAttrNameInput' + i).removeClass('is-invalid');
				}
				if(self.attTableArray[i].columnName === '') {
					$('#question_' + i).addClass('is-invalid');
					checkControl = false;
				} else {
					$('#question_' + i).removeClass('is-invalid');
				}

				// ["name#columnName#question#code#answer","name#columnName#question#code#answer"]
				let attrString = self.attTableArray[i].name + '#' + self.attTableArray[i].columnName + '#' + self.attTableArray[i].question + '#' + self.attTableArray[i].code + '#' + self.attTableArray[i].answer;
				self.editSegmentation.attributos.push(attrString);
			} else {
				// ["name#columnName#question#code#answer","name#columnName#question#code#answer"]
				let attrString = self.attTableArray[i].name + '#' + self.attTableArray[i].columnName + '#' + self.attTableArray[i].question + '#' + self.attTableArray[i].code + '#' + self.attTableArray[i].answer;
				self.editSegmentation.attributos.push(attrString);
			}
		}

		if(self.editSegmentation.attributos.length === 0) {
			$('#valueAttrNameInput0').addClass('is-invalid');
			$('#question_0').addClass('is-invalid');
			$('#option_0').addClass('is-invalid');
			checkControl = false;
		}

		// Segmentos
		let segSize = self.segTableArray.length;
		for(let i = 0; i < segSize; i++) {
			if(self.segTableArray[i].name === '') {
				continue;
			} else {
				// ["name#value#attributoDesc","name#value#attributoDesc"]
				let segString = self.segTableArray[i].name + '#' + self.segTableArray[i].value + '#' + self.segTableArray[i].attributoDesc;
				self.editSegmentation.segmentos.push(segString);
			}
		}

		if(self.editSegmentation.segmentos.length === 0) {
			$('#valueSegNameInput0').addClass('is-invalid');
			$('[for="valueSegNameInput0"]').addClass('is-invalid');
			checkControl = false;
		} else {
			$('#valueSegNameInput0').removeClass('is-invalid');
			$('[for="valueSegNameInput0"]').removeClass('is-invalid');
		}

		if(checkControl) {
			let content = '';
			if(run) {
				content = pf.const.language.RSC1768;
			} else {
				content = pf.const.language.RSC1794;
			}

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

			let alertTitle = pf.const.language.RSC1741;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, content, objInfo, function() {
				self.updateSegmentacion(run);
			}, function() {});
		} else {
			let alertTitle = pf.const.language.RSC1741;
			let alertText = pf.const.language.RSC101;
			pf.utils.showInfoDialog(alertTitle, alertText);
		}
	},

	updateSegmentacion(run) {
		let self = this;

		let parameters = {
			idSegmentacion: self.segmentationID,
			Descripcion: self.editSegmentation.descripcion,
			country: self.country,
			sid: self.editSegmentation.sid,
			attributos: JSON.stringify(self.editSegmentation.attributos),
			segmentos: JSON.stringify(self.editSegmentation.segmentos)
		};
		ajaxComunCallWithCallback('updateSegmentacion', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(run) {
					$('#segResult').show();
				}

				self.executeSegmentation(run);
			}
		});
	},

	executeSegmentation(run) {
		let self = this;

		let parameters = {
			idSegmentacion: self.segmentationID,
			sid: self.editSegmentation.sid
		};
		ajaxComunCallWithCallback('executeSegmentation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.segmentationResult = ajaxReturn.result;

				if(run) {
					self.tableSegResult();

					// Direccionamiento a la tabla
					$('.app-content').animate({scrollTop: $('#segResult').offset().top}, 1000);
				} else {
					let alertTitle = pf.const.language.RSC1741;
					let alertText = pf.const.language.RSC106;
					let alertBtn = pf.const.language.RSC132;
					pf.utils.showInfoDialog(alertTitle, alertText, alertBtn, function() {
						window.location.href = '#!editsegmentations';
					});
				}
			}
		});
	},

	tableSegResult() {
		let self = this;

		let excelTitle = pf.const.language.RSC1769;

		let table = `
			<table id="tableSegResultTables" class="table table-hover tRegs">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
						<th scope="col" title="${pf.const.language.RSC397}">${pf.const.language.RSC397}</th>
					</tr>
				</thead>

				<thead class="filterstableSegResult">
					<tr>
						<td>email</td>
						<td>resultado</td>
					</tr>
				</thead>

				<tbody>
		`;

		let size = self.segmentationResult.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr data-id="${i}">
					<td class="text-truncate" title="${self.segmentationResult[i].email}">${self.segmentationResult[i].email}</td>
					<td class="text-truncate" title="${self.segmentationResult[i].result}">${self.segmentationResult[i].result}</td>
				</tr>
			`;
		}

		table += `
				</tbody>
			</table>
		`;

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

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

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

		let tableSegResultTables = $('#tableSegResultTables').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: excelTitle,
				className: 'd-none',
				title: excelTitle,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}]
		});

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

		// Apply the search
		applyTheSearch(tableSegResultTables, 'filterstableSegResult');

		$('.dataTables_filter').css('float', 'none');
		$('#registers_wrapper button').removeClass('dt-button');

		// Exportar tabla
		$('#exportSegResult').off().on('click', function() {
			$('#segResultTable .buttons-excel').trigger('click');
		});
	}
};