let MisionesTypeNewController = {
	user: null,
	language: '',
	data: '',
	dataFlag: false,
	survey: {},
	passiveTracking: {},
	loaders: {},

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = '';
		self.dataFlag = false;
		self.survey = {
			objetive: '',
			description: ''
		};
		self.passiveTracking= {
			objective: '',
			description: ''
		};
		self.market = false;
		self.loaders = {
			getAllObjetivosMision: false,
			getSystemConfig: false
		};
	},

	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('.', '_');

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

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

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

		addLoader();
		self.getSystemConfig();
		self.getAllObjetivosMision(true);

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

		// Collapse
		addEventArrowTableHeader();

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

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

		let arrObj = ['RSC326'];
		pf.rsc.translateByTagHTMLFormat('id', arrObj);

		let arrObj2 = ['RSC347'];
		pf.rsc.addPlaceholder(arrObj2, '*');
	},

	getAllObjetivosMision(init) {
		let self = this;

		ajaxComunCallWithCallback('getAllObjetivosMision', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				self.data = ajaxReturn.result;

				if(!init) {
					self.renderObjetives();
				} else {
					let size = self.data.length;
					for(let i = 0; i < size; i++) {
						if(self.data[i].survey == 1) {
							self.survey.objetive = self.data[i].objetivo;
							self.survey.description = pf.const.language['RSC' + self.data[i].descripcion];
						} else if(self.data[i].objetivo == 'PassiveTracking') {
							self.passiveTracking.objetive = self.data[i].objetivo;
							self.passiveTracking.description = pf.const.language['RSC' + self.data[i].descripcion];
						}
					}
				}

				// Control de spinner
				self.loaders.getAllObjetivosMision = true;
				spinnerControl(self.loaders);
			}
		}, false);
	},

	renderObjetives() {
		let self = this;

		let table = `
			<thead>
				<tr>
					<th scope="col">${pf.const.language.RSC340}</th>
					<th scope="col">${pf.const.language.RSC178}</th>
					<th scope="col">${pf.const.language.RSC972}</th>
				</tr>
			</thead>

			<thead class="filters">
				<tr>
					<td>objetive</td>
					<td>description</td>
					<td>order</td>
				</tr>
			</thead>

			<tbody>
		`;

		let videocallChecked = $('#videocall').prop('checked');
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			// Control para que solo aparezcan las videocalls como objetivo en misiones del Tipo Videocall
			if(videocallChecked == true && (self.data[i].objetivo != 'VideoCallUnitaria' && self.data[i].objetivo != 'VideoCallGrupal')) {
				continue;
			}
			if(self.data[i].survey == 0) {
				table += `
					<tr id="${self.data[i].objetivo}" class="c-pointer">
						<td>${self.data[i].objetivo}</td>
						<td class="desc">${pf.const.language['RSC' + self.data[i].descripcion]}</td>
						<td class="text-center">${self.data[i].order}</td>
					</tr>
				`;
			}
		}

		table += `
			</tbody>
		`;

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

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

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

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

		let ObjetiveTable = null;

		ObjetiveTable = $('#table').DataTable({
			language: self.language,
			scrollY: 300,
			scroller: false,
			paging: true,
			pageLength: 25,
			autoWidth: false,
			aaSorting: [],
			bDestroy: true
		});

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

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

		$('#table').bind('order', function(e) {
			ObjetiveTable
				.column(2)
				.search(1)
				.draw();
			$('input', $('.filters td')[2]).blur().focus();
		});

		$('#table').bind('noOrder', function(e) {
			ObjetiveTable
				.column(2)
				.search(0)
				.draw();
			$('input', $('.filters td')[2]).blur().focus();
		});

		if(self.order) {
			$('#table').trigger('order');
		} else {
			$('#table').trigger('noOrder');
		}

		$('#table tbody').off().on('click', 'tr', function() {
			let objetive = $(this).prop('id');
			let description = $(this).find('.desc').text();

			$('#table tbody tr').css('outline-width', 'initial');
			$('#table tbody tr').css('outline-style', 'none');
			$('#table tbody tr').css('outline-color', '#000');
			$('#table 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');
			$('#close').trigger('click');

			$('#resultTable').html('');
			self.renderObjetive(objetive, description);
		});
		self.adjustTable();
	},

	renderObjetive(objetive, description) {
		let self = this;

		let table = `
			<table id="registers" class="table table-hover">
				<thead>
					<tr>
						<th scope="col" title="${pf.const.language.RSC340}">${pf.const.language.RSC340}</th>
						<th scope="col" title="${pf.const.language.RSC178}">${pf.const.language.RSC178}</th>
					</tr>
				</thead>

				<tbody>
					<tr>
						<td id="objetive" class="text-truncate" title="${objetive}">${objetive}</td>
						<td class="text-truncate" title="${description}">${description}</td>
					</tr>
				</tbody>
			</table>
		`;

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			paging: false,
			filter: false,
			autoWidth: false,
		});

		// Ocultar botones de tabla
		hideTableButtons('registers');
	},

	adjustTable() {
		setTimeout(function() {
			$($.fn.dataTable.tables(true)).DataTable().columns.adjust();
		}, 200);
	},

	applyEvents() {
		let self = this;

		// Volver a Lista de tipo de misión
		$('#back').on('click', function() {
			window.location.href = '#!misiones_type';
		});

		// Crear nuevo tipo de misión
		$('#save').on('click', function() {
			self.createTypeMission();
		});

		// Objetivos
		$('#searchObjetives').off().on('click', function() {
			self.getAllObjetivosMision(false);
		});
		$('#objetiveTable').on('show.bs.modal', function(e) {
			setTimeout(function() {
				self.adjustTable();
			}, 200);
		});

		stcmbackend.misionesType.sharedEvents(self);
	},

	createTypeMission() {
		let idmisionValidator = true;
		let descripcionValidator = true;
		let objetiveValidator = true;

		let idmision = $('#missionName').val().trim();
		// Validación idmision
		if(idmision === '') {
			$('#missionName').addClass('is-invalid');
			$('[for="missionName"]').addClass('is-invalid');
			idmisionValidator = false;
		} else {
			$('#missionName').removeClass('is-invalid');
			$('[for="missionName"]').removeClass('is-invalid');
			idmisionValidator = true;
		}
		let isPassiveTracking = ($('#passive').prop('checked') ? '1': '0');
		let order = ($('#order').prop('checked') ? '1' : '0');
		let survey = ($('#survey').prop('checked') ? '1' : '0');
		let validation = 0;
		let isVideocall = ($('#videocall').prop('checked') ? '1' : '0');
		let isAuditoria = ($('#audit').prop('checked') ? '1' : '0');

		let descripcion = $('#missionDesc').val().trim();
		// Validación descripcion
		if(descripcion === '') {
			$('#missionDesc').addClass('is-invalid');
			$('[for="missionDesc"]').addClass('is-invalid');
			descripcionValidator = false;
		} else {
			$('#missionDesc').removeClass('is-invalid');
			$('[for="missionDesc"]').removeClass('is-invalid');
			descripcionValidator = true;
		}

		// Validación objetivo
		let objetive = $('#objetive').text();
		if(objetive === '') {
			$('#objetives').addClass('is-invalid');
			$('#objetives-group').addClass('group-invalid');
			$('[for="objetives"]').addClass('is-invalid');
			objetiveValidator = false;
		} else {
			$('#objetives').removeClass('is-invalid');
			$('#objetives-group').removeClass('group-invalid');
			$('[for="objetives"]').removeClass('is-invalid');
			objetiveValidator = true;
		}

		if(!idmisionValidator || !descripcionValidator || !objetiveValidator) {
			pf.utils.alerts.showCompleteAllFields();
			return false;
		}

		let parameters = {
			tipomision: idmision,
			descripcion: descripcion,
			survey: survey,
			needValidation: validation,
			objetivo: objetive,
			order: order,
			todo: 'new',
			isPassiveTracking: isPassiveTracking,
			isVideocall: isVideocall,
			isAuditoria: isAuditoria
		};
		ajaxComunCallWithCallback('setTipoMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC338;
				let successContent = pf.const.language.RSC361;
				pf.utils.showInfoDialog(successTitle, successContent);
				window.location.href = '#!misiones_type';
			}
		});
	},

	getSystemConfig() {
		let self = this;

		ajaxComunCallWithCallback('getSystemConfig', {}, function(ajaxReturn) {
			if(ajaxReturn) {
				let market = ajaxReturn.result.filter(obj => {
					return obj.name === 'market'
				});

				if(market[0] != undefined) {
					self.market = market[0].enabled;
				}

				if(self.market == 1) {
					$('#orderContainer').removeClass('d-none');
				}

				// Control de spinner
				self.loaders.getSystemConfig = true;
				spinnerControl(self.loaders);
			}
		}, false);
	}
};