let MisionesTypeController = {
	user: null,
	language: '',
	data: '',
	market: false,
	arrayDelMult: [],

	reset() {
		let self = this;

		self.user = null;
		self.language = pf.const.language_table;
		self.data = '';
		self.market = false;
		self.arrayDelMult = [];
	},

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

		// Opciones de header
		let jsonsubopt = {
			new: 'new'
		};

		let nav = `
			${createSubOptionNew(jsonsubopt.new)}
		`;

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

		$('#new svg').css({'width': '24px', 'height': '24px'});

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

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

		// Collapse
		addEventArrowTableHeader();
	},

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

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

	applyEvents() {
		let self = this;

		// Nuevo
		$('#new').on('click', function() {
			window.location.href = '#!misiones_type_new';
		});

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

				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;
						}

						// Tabla de resultados
						self.renderData();

						removeLoader()
					}
				}, false);
			}
		}, false);
	},

	renderData() {
		let self = this;

		let order_th = '';
		let order_td = '';
		if(self.market == 1) {
			//show pedido
			order_th = `<th scope="col" title="${pf.const.language.RSC972}">${pf.const.language.RSC972}</th>`;
			order_td = '<td>order</td>';
		}

		let table = `
			<thead>
				<tr>
					<th class="text-center" scope="col" title="">
						<div class="div-global-selection">
							<input type="checkbox" class="globalSelection">
						</div>
					</th>
					<th scope="col" title="${pf.const.language.RSC338}">${pf.const.language.RSC338}</th>
					<th scope="col" title="${pf.const.language.RSC329}">${pf.const.language.RSC329}</th>
					<th scope="col" title="${pf.const.language.RSC110}">${pf.const.language.RSC110}</th>
					<th scope="col" title="${pf.const.language.RSC1271}">${pf.const.language.RSC1271}</th>
					<th scope="col" title="${pf.const.language.RSC2018}">${pf.const.language.RSC2018}</th>
					${order_th}
					<th scope="col" title="${pf.const.language.RSC2516}">${pf.const.language.RSC2516}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>selector</td>
					<td>misionType</td>
					<td>description</td>
					<td>survey</td>
					<td>passivetracking</td>
					<td>videocall</td>
					${order_td}
					<td>acciones</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(self.data[i].isOrder == 0 || self.market == 1) {
				let orderRow_td = '';
				if(self.market == 1) {
					orderRow_td = `
						<td class="pl-2 c-pointer editRow">
							<span class="d-none">${(self.data[i].isOrder == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<div class="custom-control custom-switch">
								<input id="order${i}" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].isOrder == 1 ? 'checked' : '')} disabled>
								<label for="order${i}" class="custom-control-label c-pointer"></label>
							</div>
						</td>
					`;
				}

				table += `
					<tr data-id="${self.data[i].idTipoMision}">
						<td class="text-center">
							<div class="div-single-selection" data-id="${self.data[i].idTipoMision}">
								<input type="checkbox" class="deleteSelection">
							</div>
						</td>
						<td class="text-truncate c-pointer editRow" title="${self.data[i].idTipoMision}">${self.data[i].idTipoMision}</td>
						<td class="text-truncate c-pointer editRow" title="${self.data[i].Descripcion}">${self.data[i].Descripcion}</td>
						<td class="pl-2 c-pointer editRow">
							<span class="d-none">${(self.data[i].isSurvey == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<div class="custom-control custom-switch">
								<input id="survey${i}" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].isSurvey == 1 ? 'checked' : '')} disabled>
								<label for="survey${i}" class="custom-control-label c-pointer"></label>
							</div>
						</td>
						<td class="pl-2 c-pointer editRow">
							<span class="d-none">${(self.data[i].isPassiveTracking == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<div class="custom-control custom-switch">
								<input id="isPassiveTracking${i}" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].isPassiveTracking == 1 ? 'checked' : '')} disabled>
								<label for="isPassiveTracking${i}" class="custom-control-label c-pointer"></label>
							</div>
						</td>
						<td class="pl-2 c-pointer editRow">
							<span class="d-none">${(self.data[i].isVideocall == 1 ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
							<div class="custom-control custom-switch">
								<input id="isVideocall${i}" type="checkbox" class="custom-control-input uSwitch" ${(self.data[i].isVideocall == 1 ? 'checked' : '')} disabled>
								<label for="isVideocall${i}" class="custom-control-label c-pointer"></label>
							</div>
						</td>
						${orderRow_td}
						<td class="text-center">
							<div id="dropdownActions${i}" class="div-dd-actions c-pointer" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
								${stcmbackend.svg.threeDotsVertical18}
							</div>

							<div class="dropdown-menu dropdown-menu-right shadow menu-actions" aria-labelledby="dropdownActions${i}" data-id="${self.data[i].idTipoMision}">
								<p class="dropdown-item editRow">
									${stcmbackend.svg.pencilWithoutColor}
									<span>${pf.const.language.RSC225}</span>
								</p>
								<p class="dropdown-item deleteRow">
									${stcmbackend.svg.trashWithoutColor}
									<span>${pf.const.language.RSC95}</span>
								</p>
							</div>
						</td>
					</tr>
				`;
			}
		}

		table += `
			</tbody>
		`;

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

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

			if(title === 'selector' || title === 'acciones') {
				value = `<input type="text" class="form-control form-control-sm" disabled>`;
			} else if(title === 'survey' || title === 'passivetracking' || title === 'videocall' || title === 'order') {
				value = optionsSelectAllYesNo();
			}

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

		let columnDefs = [
			{width: '25px', orderable: false, targets: 0},
			{width: '55px', targets: 3},
			{width: '100px', targets: 4},
			{width: '60px', targets: 5},
			{width: '60px', orderable: false, targets: 6}
		];

		if(self.market == 1) {
			columnDefs = [
				{width: '25px', orderable: false, targets: 0},
				{width: '55px', targets: 3},
				{width: '100px', targets: 4},
				{width: '60px', targets: 5},
				{width: '55px', targets: 6},
				{width: '60px', orderable: false, targets: 7}
			];
		}

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: self.language,
			pageLength: 25,
			autoWidth: false,
			columnDefs: columnDefs,
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC351,
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			aaSorting: []
		});

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

		// Apply the search
		applyTheSearch(dataTable, 'filtersResult');

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

		self.tableEvents(dataTable);

		// Eventos con cambio de página de tabla
		$('#registers').on('draw.dt', function() {
			self.tableEvents(dataTable);
		});
	},

	tableEvents(dataTable) {
		let self = this;

		// Eventos del input global
		globalSelectionInputActions();

		// Editar tipo de misión
		$('.editRow').off().on('click', function() {
			let id = $(this).parent().data('id');

			sessionStorage.setItem('idTipoMision', btoa(id));
			window.location.href = '#!misiones_type_edit';
		});

		// Borrar tipo de mision
		$('.deleteRow').off().on('click', function() {
			let id = $(this).parent().data('id');

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

			let alertTitle = pf.const.language.RSC351;
			let alertText = pf.const.language.RSC352;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteMissionType(id);
			}, function() {});
		});

		// Array de eliminado múltiple
		$('.deleteSelection').off().on('change', function() {
			let value = $(this).prop('checked');
			let id = $(this).parent().data('id');

			if(value) {
				self.arrayDelMult.push(id);
			} else {
				let index = self.arrayDelMult.indexOf(id);
				self.arrayDelMult.splice(index, 1);
			}

			// Eventos de los inputs individuales
			deleteSelectionInputActions(self.arrayDelMult);
		});

		// Función de borrado múltiple
		$('#multSelecDelete').off().on('click', function() {
			// Aviso de borrado múltiple
			let objInfo = {
				accept: {
					text: pf.const.language.RSC95
				},
				cancel: {
					text: pf.const.language.RSC57
				}
			};

			let alertTitle = pf.const.language.RSC351;
			let alertText = pf.const.language.RSC1695;
			pf.utils.showInfoDialogAcceptCancel(alertTitle, alertText, objInfo, function() {
				self.deleteMissionType();
			}, function() {});
		});
	},

	deleteMissionType(id = false) {
		let self = this;

		let missionsType = [];
		if(id !== false) {
			let obj = {
				id: id
			}
			missionsType.push(obj);
		} else {
			let delSize = self.arrayDelMult.length;
			for(let i = 0; i < delSize; i++) {
				let obj = {
					id: self.arrayDelMult[i]
				}
				missionsType.push(obj);
			}
			self.arrayDelMult = [];
		}

		let parameters = {
			missionsType: JSON.stringify(missionsType)
		};
		ajaxComunCallWithCallback('deleteTipoMision', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let successTitle = pf.const.language.RSC338;
				let successContent = pf.const.language.RSC362;
				pf.utils.showInfoDialog(successTitle, successContent);
				loadHTML('inc/misiones/misiones_type.html', 'wrapper', MisionesTypeController);
			}
		});
	}
};