let RotationController = {
	survey: null,
	surveys: '',
	questions: [],
	id: '',
	urlImages: '',

	reset() {
		let self = this;

		self.survey = null;
		self.surveys = '';
		self.questions = [];
		self.id = '';
		self.urlImages = '';
	},

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

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

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

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

		let nav = `
			${createSubOptionSave(jsonsubopt.save)}
			${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');

		self.loadLang();

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));

		self.urlImages = config.URLEncuestas;
		//Comprobar si estamos o no editando
		let location = window.location.toString().replace('#!', '/');
		let queryString = new URL(location).search;
		let urlParams = new URLSearchParams(queryString);
		if(urlParams.has('id') && urlParams.has('description') && urlParams.has('survey')) {
			self.setEditAttributes(urlParams);
		} else if(window.location.href.indexOf('editar') > -1) {
			let errorTitle = (pf.const.language.RSC61);
			let errorContent = (pf.const.language.RSC1440);
			pf.utils.showInfoDialog(errorTitle, errorContent);
		}

		$('#sortableQuestions').sortable();
		self.applyEvents();

		// Collapse
		addEventArrowTableHeader();

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

	setEditAttributes(urlParams) {
		let self = this;

		let id = urlParams.get('id');
		let survey = urlParams.get('survey');
		let descripcion = urlParams.get('description');

		self.id = id;
		self.survey = survey;
		$('#surveyInput').val(survey);
		$('#descripcion').val(descripcion);

		let parameters = {
			survey: self.survey,
			idrotation: self.id
		};
		ajaxComunCallWithCallback('getRotacionSurveyQuestions', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.questions = [];
					let size = ajaxReturn.result.length;
					for(let i = 0; i < size; i++) {
						if(self.questions[parseInt(ajaxReturn.result[i].section_order)] == undefined) {
							self.questions[parseInt(ajaxReturn.result[i].section_order)] = {};
							self.questions[parseInt(ajaxReturn.result[i].section_order)]['questions'] = [ajaxReturn.result[i]];
							self.questions[parseInt(ajaxReturn.result[i].section_order)]['name'] = ajaxReturn.result[i].group_name;
							self.questions[parseInt(ajaxReturn.result[i].section_order)]['gid'] = ajaxReturn.result[i].title_section;
						} else {
							self.questions[parseInt(ajaxReturn.result[i].section_order)].questions.push(ajaxReturn.result[i]);
						}
					}

				self.renderQuestionList();
			}
		});
	},

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

	applyEvents() {
		let self = this;

		// Volver a RSC
		$('#back').on('click', function() {
			window.location.href = '#!rotaciones';
		});

		// Encuestas
		$('#searchSurvey').on('click', function() {
			if(self.surveys === '') {
				ajaxComunCallWithCallback('getAllSurveys', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.surveys = ajaxReturn.result;
						self.renderSurveys();
					}
				});
			} else {
				$('#surveyTable').modal('show', true);
			}
		});

		// Restricciones de carácteres por tecla
		$('.ovSpecChars').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
		$('.ovSpecChars').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);
		});

		$('#save').on('click', function() {
			let objInfo = {
				accept: {
					text: pf.const.language.RSC78
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC78;
			let alertText = pf.const.language.RSC105;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.setRotation();
			}, function() {});
		});
	},

	renderSurveys() {
		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.RSC112}">${pf.const.language.RSC112}</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.RSC115}">${pf.const.language.RSC115}</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>
				</tr>
			</thead>

			<thead class="filtersPoll">
				<tr>
					<td>sid</td>
					<td>surveyls_title</td>
					<td>datecreated</td>
					<td>active</td>
					<td>perfilacion</td>
					<td>startdate</td>
					<td>expires</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.surveys.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="sid${self.surveys[i].sid}" class="c-pointer">
					<td class="text-truncate" title="${self.surveys[i].sid}">${self.surveys[i].sid}</td>
					<td class="text-truncate pollName" title="${self.surveys[i].surveyls_title}">${self.surveys[i].surveyls_title}</td>
					<td class="text-truncate" title="${self.surveys[i].datecreated}">${self.surveys[i].datecreated}</td>
					<td class="text-center">
						<span class="d-none">${(self.surveys[i].active == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveys[i].active == '1' ? 'checked' : '')}>
					</td>
					<td class="text-center">
						<span class="d-none">${(self.surveys[i].perfilacion == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.surveys[i].perfilacion == '1' ? 'checked' : '')}>
					</td>
					<td class="text-truncate start-date" title="${self.surveys[i].startdate}">${self.surveys[i].startdate}</td>
					<td class="text-truncate end-date" title="${self.surveys[i].expires}">${self.surveys[i].expires}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'active' || title == 'perfilacion') {
				value = optionsSelectAllYesNo();
			}

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

		let tablePoll = $('#tablePoll').DataTable({
			language: pf.const.language_table,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: []
		});

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

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

		// Apply the search
		applyTheSearch(tablePoll, 'filtersPoll');

		$('#tablePoll tbody').off().on('click', 'tr', function() {
			let idSurvey = $(this).prop('id').replace('sid', '');

			if(idSurvey == undefined || idSurvey == '') {
				return false;
			}

			self.survey = idSurvey;
			let name = $(this).find('.pollName').text();
			$('#surveyInput').val(name);
			$('#tablePoll tbody tr').css('outline-width', 'initial');
			$('#tablePoll tbody tr').css('outline-style', 'none');
			$('#tablePoll tbody tr').css('outline-color', '#000');
			$('#tablePoll tbody tr').css('font-weight', 'normal');
			$(this).css('outline-width', 'thin');
			$(this).css('outline-style', 'solid');
			$(this).css('outline-color', '#f00');
			$(this).css('font-weight', 'bold');
			$('#closePool').trigger('click');

			let parameters = {
				survey: self.survey,
				filter: '1'
			};
			ajaxComunCallWithCallback('getQuestionsSurvey', parameters, function(ajaxReturn) {
				if(ajaxReturn) {
					self.questions = [];
					let size = ajaxReturn.result.length;
					for(let i = 0; i < size; i++) {
						if(self.questions[parseInt(ajaxReturn.result[i].group_order)] == undefined) {
							self.questions[parseInt(ajaxReturn.result[i].group_order)] = {};
							self.questions[parseInt(ajaxReturn.result[i].group_order)]['questions'] = [ajaxReturn.result[i]];
							self.questions[parseInt(ajaxReturn.result[i].group_order)]['name'] = ajaxReturn.result[i].group_name;
							self.questions[parseInt(ajaxReturn.result[i].group_order)]['gid'] = ajaxReturn.result[i].gid;
						} else {
							self.questions[parseInt(ajaxReturn.result[i].group_order)].questions.push(ajaxReturn.result[i]);
						}
					}

					self.renderQuestionList();
				}
			});
		});
	},

	renderQuestionList() {
		let self = this;

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

		let size = self.questions.length;
		for(let i = 0; i < size; i++) {
			if(self.questions[i] == undefined) {
				continue;
			}

			let section = `
				<li class="list-group-item c-drag" role="button" data-section="1" data-id="${self.questions[i].gid}">
					<div class="d-flex flex-row justify-content-between mb-2">
						<div class="w-100 d-inline-block">
							${stcmbackend.svg.arrowDownUpWithoutColor}
							${self.questions[i].name}
						</div>
					</div>

					<div>
						<ul id="sortableQuestions${i}" class="list-group">

						</ul>
					</div>
				</li>
			`;

			$('#sortableQuestions').append(section);
			$('#sortableQuestions' + i).sortable();

			let orderedQuestions = self.questions[i].questions.sort((a, b) => parseFloat(a.question_order) - parseFloat(b.question_order));

			orderedQuestions.forEach(question => {
				let label = question.question.replace(`src="`, `src="${self.urlImages}`);
				$('#sortableQuestions' + i).append(
					`<li class="ui-state-default list-group-item c-drag" role="button" idQuestion="${question.title}" data-section="0">
						<div class="d-flex flex-row justify-content-between">
							<div class="w-100 d-inline-block">
								${stcmbackend.svg.arrowDownUpWithoutColor}
								${label}
							</div>
						</div>
					</li>`
				);
				$(`li[idQuestion='${question.title}']`).find('p').each((i, p)=>{
					$(p).css('display', 'inline');
					$(p).find('img').removeAttr('style').css({'max-height': '200px', 'margin-right': '20px', 'margin-left': '20px'});
				})
			});
		}
	},

	generateQuestionArray() {
		let lisQuestions = $('#sortableQuestions li');
		let result = [];
		let idSection = '';
		let orderSection = 0;
		let orderQuestion = 0;
		lisQuestions.each(function(idx, li) {
			if($(li).data('section') == '1') {
				idSection = $(li).data('id');
				orderSection++;
			} else {
				orderQuestion++;
				let menu = $(li);
				let roleString = `${idSection}#${orderSection}#${menu.attr('idQuestion')}#${orderQuestion}`;
				result.push(roleString);
			}
		});
		return result;
	},

	addZero(v) {
		return (v < 10 ? v = '0' + v : v);
	},

	generateID() {
		let dt = new Date();
		let self = this;
		let Y = dt.getFullYear().toString();
		let n = (dt.getMonth() +1).toString();
		let j = dt.getDate().toString();
		let h = self.addZero(dt.getHours()).toString();
		let m = self.addZero(dt.getMinutes()).toString();
		let s = self.addZero(dt.getSeconds()).toString();
		let z = dt.getMilliseconds().toString();

		if(z < 10) {
			z = '00' + z;
		} else if(z < 100) {
			z = '0' + z;
		}

		let fulldate = Y + n + j + h + m + s;
		return fulldate;
	},

	setRotation() {
		let self = this;

		let survey = self.survey;
		let descripcion = $('#descripcion').val().trim();

		let descripcionValidator = true;
		let surveyValidator = true;
		if(descripcion == '') {
			descripcionValidator = false;
			$('#descripcion').addClass('is-invalid');
			$('[for="descripcion"]').addClass('is-invalid');
		} else {
			descripcionValidator = true;
			$('#descripcion').removeClass('is-invalid');
			$('[for="descripcion"]').removeClass('is-invalid');
		}
		if(!survey) {
			surveyValidator = false;
			$('#surveyInput').addClass('is-invalid');
			$('#surveyInput-group').addClass('group-invalid');
			$('[for="surveyInput"]').addClass('is-invalid');
		} else {
			surveyValidator = true;
			$('#surveyInput').removeClass('is-invalid');
			$('#surveyInput-group').removeClass('group-invalid');
			$('[for="surveyInput"]').removeClass('is-invalid');
		}
		if(!surveyValidator || !descripcionValidator) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let idRotation = self.id;
		if(!self.id) {
			idRotation = self.generateID();
		}

		let values= self.generateQuestionArray();
		let valuesJSON = JSON.stringify(values);

		let parameters = {
			survey: survey,
			idrotation: idRotation,
			values: valuesJSON,
			description: descripcion
		};
		ajaxComunCallWithCallback('setRotacionSurveyQuestions', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = (pf.const.language.RSC78);
				let successContent = (pf.const.language.RSC106);
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!rotaciones';
			}
		});
	}
};