let ConversacionesController = {
	today: '',
	typeColors: null,
	fontSize: null,
	fontName: null,
	colorsRGB: [],
	colorsHex: [],
	users: '',
	idIssuingUser: '',
	idReceivingUser: '',
	group: '',
	idGroup: '',
	startDate: '',
	startTime: '00:00',
	endDate: '',
	endTime: '23:59',
	data: [],
	dataFlag: false,
	difusion: null,
	idDifusion: '',
	dateFormat: '',

	reset() {
		let self = this;

		self.today = '';
		self.typeColors = null;
		self.fontSize = null;
		self.fontName = null;
		self.colorsRGB = [];
		self.colorsHex = [];
		self.users = '';
		self.idIssuingUser = '';
		self.idReceivingUser = '';
		self.group = '';
		self.idGroup = '';
		self.startDate = '';
		self.startTime = '00:00';
		self.endDate = '';
		self.endTime = '23:59';
		self.data = [];
		self.dataFlag = false;
		self.difusion = null;
		self.idDifusion = '';
		self.dateFormat = '';
	},

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

		// Información de administrador
		let JSONuser = sessionStorage['STCMBackEnd:user'];
		let user = JSON.parse(JSONuser);
		self.dateFormat = user.formatoFecha;

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

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

		// Opciones de header
		let jsonsubopt = {
			groups: 'groups',
			distributionlistSelector: 'difusion',
			userSender: 'issuingUser',
			userReceiver: 'receivingUser',
			refresh: {
				id: 'loadConversation',
				disabled: true
			},
			downloadMultimedia: 'downloadAllAttachment',
			startEndDate: {
				class: 'ma-le-5',
				style: 'line-height: initial;'
			},
			startEndTime: {
				class: 'ma-le-5',
				style: 'line-height: initial;'
			}
		};

		let nav = `
			<div class="d-flex">
				${createSubOptionStartEndDateTime(jsonsubopt.startEndDate.class, jsonsubopt.startEndTime.class, jsonsubopt.startEndDate.style, jsonsubopt.startEndTime.style)}

				<div class="d-flex pa-to-28">
					${createSubOptionRefresh(jsonsubopt.refresh.id, jsonsubopt.refresh.disabled)}
					${createSubOptionDownloadMultimedia(jsonsubopt.downloadMultimedia)}
				</div>
			</div>
		`;

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

		let modalActions = `
			${createSubOptionGroups(jsonsubopt.groups)}
			${createSubOptionDistributionListSelector(jsonsubopt.distributionlistSelector)}
			${createSubOptionUserSender(jsonsubopt.userSender)}
			${createSubOptionUserReceiver(jsonsubopt.userReceiver)}
		`;

		$('#page-modal-actions').html(modalActions);
		$('#groups').parent().parent().addClass('pl-0');
		$('#receivingUser').parent().parent().addClass('pr-0');

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

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

		// Añadir textos
		$('.RSC-saveAttachment').append(pf.const.language.RSC78);

		self.loadLang();

		$('#resultTableC').hide();
		$('#attachmentViewer').hide();

		let now = new Date();
		let nYear = now.getFullYear();
		let nMonth = now.getMonth() + 1;
		if(nMonth < 10) {
			nMonth = '0' + nMonth;
		}
		let nDay = now.getDate();
		if(nDay < 10) {
			nDay = '0' + nDay;
		}
		self.today = nYear + '-' + nMonth + '-' + nDay;
		self.startDate = self.today;
		self.endDate = self.today;

		$('#startDate').val(self.startDate);
		$('#startTime').val(self.startTime);
		$('#endDate').val(self.endDate);
		$('#endTime').val(self.endTime);

		// Valores de configuración
		let config = JSON.parse(atob(sessionStorage.getItem('STCMBackEnd:config')));
		self.typeColors = config.UsarColorDegradado;
		self.fontSize = config.SizeFontAnalytics;
		self.fontName = config.FontAnalytics;

		if(!config.RGBFin || config.RGBFin === '') {
			self.colorsRGB[0] = '000,000,255';
			self.colorsHex[0] = rgb2hex('rgb(000,000,255)');
		} else {
			if(self.typeColors == 1) {
				self.colorsRGB[0] = config.RGBFin;
				self.colorsHex[0] = rgb2hex('rgb(' + config.RGBFin + ')');
			} else {
				self.colorsRGB = [];
				for(let i = 0; i < config.colores.length; i++) {
					self.colorsRGB.push(config.colores[i].color);
				}
			}
		}

		if(!config.RGBInicio || config.RGBInicio === '') {
			self.colorsRGB[1] = '255,000,000';
			self.colorsHex[1] = rgb2hex('rgb(255,000,000)');
		} else {
			if(self.typeColors == 1) {
				self.colorsRGB[1] = config.RGBInicio;
				self.colorsHex[1] = rgb2hex('rgb(' + config.RGBInicio + ')');
			} else {
				self.colorsHex = [];
				for(let i = 0; i < config.colores.length; i++) {
					self.colorsHex.push(rgb2hex('rgb(' + config.colores[i].color + ')'));
				}
			}
		}

		self.applyEvents();

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

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

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

	applyEvents() {
		let self = this;

		// Usuario Emisor
		$('#searchIssuingUser').on('click', function() {
			if(self.users === '') {
				let parameters = {
					country: '',
					consejero: '1',
					enabled: '1',
					staff: '1',
					admin: '1'
				};
				ajaxComunCallWithCallback('getAllUsers', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						self.users = ajaxReturn.result;

						self.renderUsers();
					}
				});
			} else {
				self.idIssuingUser = '';
			}
		});

		// Usuario Receptor
		$('#searchReceivingUser').on('click', function() {
			self.idReceivingUser = '';
		});

		// Grupos
		$('#searchGroups').on('click', function() {
			if(self.group === '') {
				ajaxComunCallWithCallback('getAllGroups', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.group = ajaxReturn.result;

						self.renderGroups();
					}
				});
			}
		});

		// Listas de Difusion
		$('#searchDifusion').on('click', function() {
			if(!self.difusion) {
				ajaxComunCallWithCallback('getAllDistributionList', {}, function(ajaxReturn) {
					if(ajaxReturn) {
						self.difusion = ajaxReturn.result;

						self.renderDifusion();
					}
				});
			}
		});

		// Fecha de inicio
		$('#startDate').on('change', function() {
			self.startDate = $('#startDate').val();
			if(self.startDate > self.endDate) {
				$('#startDate').val(self.endDate);
				self.startDate = $('#startDate').val();
			}
		});

		// Hora de inicio
		$('#startTime').on('change', function() {
			self.startTime = $('#startTime').val();
		});

		// Fecha de fin
		$('#endDate').on('change', function() {
			self.endDate = $('#endDate').val();
			if(self.endDate < self.startDate) {
				$('#endDate').val(self.startDate);
				self.endDate = $('#endDate').val();
			}
		});

		// Hora de fin
		$('#endTime').on('change', function() {
			self.endTime = $('#endTime').val();
		});

		// Conversaciones
		$('#loadConversation').on('click', function() {
			self.getAnalyticsConversacion('read');
		});

		// Collapse
		addEventArrowTableHeader();
	},

	renderUsers() {
		let self = this;

		let gdpr = sessionStorage['STCMBackEnd:GDPR'];

		let nameSurnameHead = `<th scope="col" title="${pf.const.language.RSC123}">${pf.const.language.RSC123}</th>`;
		let nameSurnameFilter = `<td>Nombre</td>`;

		// Control GDPR
		if(gdpr == '1') {
			nameSurnameHead = '';
			nameSurnameFilter = '';
		}

		let table = `
			<thead>
				<tr>
					${nameSurnameHead}
					<th scope="col" title="${pf.const.language.RSC136}">${pf.const.language.RSC136}</th>
					<th scope="col" title="${pf.const.language.RSC126}">${pf.const.language.RSC126}</th>
					<th scope="col" title="${pf.const.language.RSC277}">${pf.const.language.RSC277}</th>
				</tr>
			</thead>

			<thead class="filtersUser">
				<tr>
					${nameSurnameFilter}
					<td>E-mail</td>
					<td>Enabled</td>
					<td>Role</td>
				</tr>
			</thead>

			<tbody>
		`;

		// Obtener países permitidos
		let allowedCountries = JSON.parse(atob(sessionStorage['STCMBackEnd:userCountries']));
		let size = self.users.length;
		for(let i = 0; i < size; i++) {
			// Control de países permitidos
			if(allowedCountries.indexOf(self.users[i].country) == -1) {
				continue;
			}

			let surname1 = self.users[i].userApellidos ? ' ' + self.users[i].userApellidos : '';
			let surname2 = self.users[i].userApellidos2 ? ' ' + self.users[i].userApellidos2 : '';
			let completname = self.users[i].nameUser + surname1 + surname2;

			let nameSurnameBody = `<td class="nameUser" title="${completname}">${completname}</td>`;

			// Control GDPR
			if(gdpr == '1') {
				nameSurnameBody = '';
			}

			table += `
				<tr id="${self.users[i].id}">
					${nameSurnameBody}
					<td class="emailUser" title="${self.users[i].email}">${self.users[i].email}</td>
					<td class="text-center">
						<span class="d-none">${(self.users[i].enabled == '1' ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						<input type="checkbox" disabled ${(self.users[i].enabled == '1' ? 'checked' : '')}>
					</td>
					<td title="${self.users[i].role}">${(self.users[i].role == null ? '' : self.users[i].role)}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

			if(title == 'Enabled') {
				value = optionsSelectAllYesNo();
			}

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

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

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

		// Apply the search
		applyTheSearch(tableUsers, 'filtersUser');

		$('#tableUser tbody').off().on('click', 'tr', function() {
			$('#searchGroups').prop('disabled', true);
			$('#searchDifusion').prop('disabled', true);
			$('.filtersUser td input').val('');
			$('.filtersUser td input').trigger('change');

			if(self.idIssuingUser === '') {
				self.idIssuingUser = $(this).prop('id');
				let nameIssuingUser = $(this).find('.nameUser').text();
				if(nameIssuingUser == '') {
					nameIssuingUser = $(this).find('.emailUser').text();
				}
				$('#issuingUser').val(nameIssuingUser);
				$('#searchReceivingUser').prop('disabled', false);
			} else {
				self.idReceivingUser = $(this).prop('id');
				let nameReceivingUser = $(this).find('.nameUser').text();
				if(nameReceivingUser == '') {
					nameReceivingUser = $(this).find('.emailUser').text();
				}
				$('#receivingUser').val(nameReceivingUser);
				$('#loadConversation').prop('disabled', false);
			}

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

	renderGroups() {
		let self = this;

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

			<thead class="filtersGroup">
				<tr>
					<td>Nombre</td>
					<td>Administrador</td>
				</tr>
			</thead>

			<tbody>
		`;

		let size = self.group.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="${self.group[i].groupName}">
					<td class="nameGroup" title="${self.group[i].name}">${self.group[i].name}</td>
					<td title="${self.group[i].userNombre} ${self.group[i].userApellidos} ${self.group[i].userApellidos2}">${self.group[i].userNombre} ${self.group[i].userApellidos} ${self.group[i].userApellidos2}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableGroup, 'filtersGroup');

		$('#tableGroup tbody').off().on('click', 'tr', function() {
			$('#searchIssuingUser').prop('disabled', true);
			$('#searchDifusion').prop('disabled', true);
			$('.filtersGroup td input').val('');
			$('.filtersGroup td input').trigger('change');

			self.idGroup = $(this).prop('id');
			let nameGroup = $(this).find('.nameGroup').text();
			$('#groups').val(nameGroup);
			$('#loadConversation').prop('disabled', false);

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

	renderDifusion() {
		let self = this;

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

			<thead class="filtersDifusion">
				<tr>
					<td>Descripcion</td>
					<td>Administrador</td>
				</tr>
			</thead>
			
			<tbody>
		`;

		let size = self.difusion.length;
		for(let i = 0; i < size; i++) {
			table += `
				<tr id="${self.difusion[i].id}">
					<td class="nameDifusion" title="${self.difusion[i].Descripcion}">${self.difusion[i].Descripcion}</td>
					<td title="${self.difusion[i].AdminName}">${self.difusion[i].AdminName}</td>
				</tr>
			`;
		}

		table += `
			</tbody>
		`;

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

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

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

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

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

		// Apply the search
		applyTheSearch(tableGroup, 'filtersDifusion');

		$('#tableDifusion tbody').off().on('click', 'tr', function() {
			$('#searchIssuingUser').prop('disabled', true);
			$('#searchGroups').prop('disabled', true);
			$('.filtersDifusion td input').val('');
			$('.filtersDifusion td input').trigger('change');

			self.idDifusion = $(this).attr('id');

			let nameDifusion = $(this).find('.nameDifusion').text();
			$('#difusion').val(nameDifusion);
			$('#loadConversation').prop('disabled', false);

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

	getAnalyticsConversacion(type) {
		let self = this;

		let client = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let mail = client.email.split('@');
		let user = mail[0].replace('.', '_');
		let idLista = '';

		if(self.idDifusion) {
			idLista = self.idDifusion;
		}

		let parameters = {
			jid: self.idIssuingUser,
			bid: self.idReceivingUser,
			idgroup: self.idGroup,
			fechaInicio: self.startDate + ' ' + self.startTime,
			fechaFin: self.endDate + ' ' + self.endTime,
			type: type,
			user: user,
			idlista: idLista
		};
		ajaxComunCallWithCallback('getAnalyticsConversacion', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				if(type === 'read') {
					self.data = ajaxReturn.result;
					self.renderConversation();
				} else {
					let link = document.createElement('a');
					link.href = stcm.const.downloads + ajaxReturn.result;
					link.download = 'attachment.zip';
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
					// Carpeta para vaciar
					let folderFile = ajaxReturn.result.split('/');

					let parameters = {
						folder: folderFile[0]
					};
					ajaxComunCallWithCallback('deleteFolder', parameters, function(ajaxReturn) {
						if(ajaxReturn) {
							//
						}
					});
				}
			}
		});
	},

	renderConversation() {
		let self = this;

		if(self.dataFlag) {
			$('#registers').dataTable().fnDestroy();
		} else {
			self.dataFlag = true;
		}

		$('#resultTableC').show();

		let table = `
			<thead>
				<tr>
					<th scope="col" title="${pf.const.language.RSC161}">${pf.const.language.RSC161}</th>
					<th scope="col" title="${pf.const.language.RSC162}">${pf.const.language.RSC162}</th>
					<th scope="col" title="${pf.const.language.RSC164}">${pf.const.language.RSC164}</th>
					<th scope="col" title="${pf.const.language.RSC165}">${pf.const.language.RSC165}</th>
					<th scope="col" title="${pf.const.language.RSC166}">${pf.const.language.RSC166}</th>
					<th scope="col" title="${pf.const.language.RSC167}">${pf.const.language.RSC167}</th>
					<th scope="col" title="${pf.const.language.RSC168}">${pf.const.language.RSC168}</th>
					<th scope="col" title="${pf.const.language.RSC169}">${pf.const.language.RSC169}</th>
				</tr>
			</thead>

			<thead class="filtersResult">
				<tr>
					<td>issuingUser</td>
					<td>receivingUser</td>
					<td>message</td>
					<td>date</td>
					<td>time</td>
					<td>attachmentName</td>
					<td>attachmentType</td>
					<td>visualizar</td>
				</tr>
			</thead>

			<tbody>
		`;

		let eye = `
			<button type="button" class="btn btn-eye loadFile">
				${stcmbackend.svg.bigEyeWithoutColor}
			</button>
		`;

		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			let nameA = '';
			let nameB = '';
			if($('#groups').val() == '' && $('#difusion').val() == '') {
				// Emisor
				if(self.data[i].jid == self.idIssuingUser) {
					nameA = $('#issuingUser').val();
				} else {
					nameA = $('#receivingUser').val();
				}
				// Receptor
				if(self.data[i].bid == self.idReceivingUser) {
					nameB = $('#receivingUser').val();
				} else {
					nameB = $('#issuingUser').val();
				}
			} else if($('#difusion').val() == '') {
				nameA = self.data[i].nameUser + ' ' + self.data[i].userApellidos + ' ' + self.data[i].userApellidos2;
				nameB = $('#groups').val();
			} else {
				nameA = self.data[i].nameUser + ' ' + self.data[i].userApellidos + ' ' + self.data[i].userApellidos2;
				nameB = $('#difusion').val();
			}

			// Formato de fecha, el servicio devuelve AAAA-MM-DD HH:MM:SS
			let dateTime = '';
			let time = '';
			let dateTimeArray = self.data[i].stampServer.split(' ');
			// Para ordenación en columna
			let dateOrder = dateTimeArray[0];
			let date = dateTimeArray[0].replace(/-/g, '/');
			if(self.dateFormat === 'DDMMAAAA') {
				dateTime = modifyDateFormat(date);
				time = dateTimeArray[1];
			} else {
				dateTime = date;
				time = dateTimeArray[1];
			}

			let attachment = false;
			if(self.data[i].attachmentName != '' && self.data[i].attachmentName.indexOf('.') != -1) {
				attachment = true;
			}

			table += `
				<tr id="s-${self.data[i].stamp}">
					<td class="text-truncate" title="${nameA}">
						${nameA}
					</td>
					<td class="text-truncate" title="${nameB}">
						${nameB}
					</td>
					<td class="text-truncate" title="${(self.data[i].msg != null ? self.data[i].msg : '')}">${(self.data[i].msg != null ? self.data[i].msg : '')}</td>
					<td class="text-truncate" title="${dateTime}">
						<span class="d-none">${dateOrder}</span>
						${dateTime}
					</td>
					<td class="text-truncate" title="${time}">${time}</td>
					<td class="text-truncate file" title="${(attachment ? self.data[i].attachmentName : '')}">${(attachment ? self.data[i].attachmentName : '')}</td>
					<td class="text-truncate type" title="${self.data[i].attachmentType}">${self.data[i].attachmentType}</td>
					<td class="text-center">
						<span class="d-none">${(attachment ? pf.const.language.RSC120 : pf.const.language.RSC121)}</span>
						${(attachment ? eye : '')}
					</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 == 'visualizar') {
				value = optionsSelectAllYesNo();
			}

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

		let dataTable = $('#registers').DataTable({
			retrieve: true,
			language: pf.const.language_table,
			pageLength: 25,
			autoWidth: false,
			columnDefs: [
				{width: '60px', targets: 7}
			],
			dom: 'Bfrtip',
			buttons: [{
				extend: 'excelHtml5',
				text: pf.const.language.RSC129,
				className: 'd-none',
				title: pf.const.language.RSC36,
				exportOptions: {
					format: {
						body(data, row, column, node) {
							let dev = '';
							if(column === 3) {
								dev = data.replace(/<span class="d-none">[A-Za-z0-9-.:]*<\/span>/g, '');
							} else {
								dev = data.replace(/<\/?[^>]+(>|$)/g, '');
							}
							return dev;
						}
					}
				},
				customize(xlsx) {
					dataTablesExcelCustomize(xlsx);
				}
			}],
			rowGroup: {
				endRender(rows, group) {
					return group + ': ' + pf.const.language.RSC146 + ' (' + rows.count() + ')';
				},
				dataSrc: 0
			},
			order: [[3, 'asc'], [4, 'asc']]
		});

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

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

		dataTable.rowGroup().disable().draw();
		$('#nestBy').hide();

		// Creación de select principal de agrupamiento
		// Arrays de datos
		let name = [];

		$.each($('#registers thead th'), function() {
			name.push($(this).text());
		});

		let options1 = `<option value="-1">${pf.const.language.RSC130}</option>`;
		for(let i = 0; i < name.length; i++) {
			options1 += `<option value="${i}">${name[i]}</option>`;
		}
		$('#groupBy').html(options1);

		// Función de agrupamiento anidado
		function nestBy() {
			$('#nestBy').html('');
			let options2 = `<option value="-1">${pf.const.language.RSC131}</option>`;
			for(let i = 0; i < name.length; i++) {
				if(i == $('#groupBy').val()) {
					continue;
				} else {
					options2 += `<option value="${i}">${name[i]}</option>`;
				}
			}
			$('#nestBy').html(options2);

			// Evento de anidado
			$('#nestBy').off().on('change', function() {
				let valueGroup = $('#groupBy').val();

				if($('#nestBy').val() === '-1') {
					dataTable.rowGroup().dataSrc(valueGroup);
					dataTable.order([[valueGroup, 'asc']]).draw();
				} else {
					let valueNest = $('#nestBy').val();
					dataTable.rowGroup().dataSrc([valueGroup, valueNest]);
					dataTable.order([[valueGroup, 'asc'], [valueNest, 'asc']]).draw();
				}
			});
		}

		// Evento de agrupamiento
		$('#groupBy').on('change', function() {
			if($('#groupBy').val() === '-1') {
				dataTable.rowGroup().disable().draw();
				$('#nestBy').hide();
			} else {
				let value = $('#groupBy').val();

				dataTable.rowGroup().enable().draw();
				$('#nestBy').show();

				dataTable.rowGroup().dataSrc(value);
				dataTable.order([[value, 'asc']]).draw();

				// Recreación de agrupamiento secundario
				nestBy();
			}
		});

		// Exportar tabla
		$('#exportConversation').prop('disabled', false);
		$('#exportConversation').off().on('click', function() {
			$('#resultTableC .buttons-excel').trigger('click');
		});

		// Activación de botón de descarga de todos los documentos adjuntos
		$('#downloadAllAttachment').prop('disabled', false);
		$('#downloadAllAttachment').off().on('click', function() {
			self.getAnalyticsConversacion('load');
		});

		// Carga de archivos
		self.fileLoad();

		// Carga de archivos con cambio de página
		$('#resultTableC').on('draw.dt', function() {
			self.fileLoad();
		});
	},

	// Carga de archivos
	fileLoad() {
		let self = this;

		$('.loadFile').off().on('click', function() {
			let file = $(this).parent().parent().find('.file').text();
			let type = $(this).parent().parent().find('.type').text();
			let stamp = $(this).parent().parent().attr('id').replace('s-', '');
			self.fileShow(file, type, stamp);
		});
	},

	fileShow(file, type, stamp) {
		let self = this;

		$('#attachmentViewer').show();
		$('.attachmentContainer').html('');

		file = file.replace(/\"/g, '');

		let row = '';
		let size = self.data.length;
		for(let i = 0; i < size; i++) {
			if(self.data[i].stamp === stamp) {
				row = self.data[i];
			}
		}
		let year = row.stampServer.substr(0, 4);
		let month = row.stampServer.substr(5, 2);
		let day = row.stampServer.substr(8, 2);
		let issuingUser = '';
		if(row.jid != '') {
			let issuing = row.jid.split('@');
			issuingUser = issuing[0];
		}
		let receivingUser = '';
		if(row.bid != '') {
			let receiving = row.bid.split('@');
			receivingUser = receiving[0];
		}

		// Caso de grupo
		if(self.idGroup !== '') {
			issuingUser = receivingUser;
		}

		let formatExt = type.split('/');
		let format = formatExt[0];

		let src = stcm.const.conversationFiles;

		let content = '';
		switch(format) {
			case 'image':
				src += 'imagenes/' + year + '/' + month + '/' + day + '/' + issuingUser + '/' + stamp + receivingUser + file;
				content = `<img src="${src}">`;
				break;
			case 'video':
				if(type === 'video/quicktime') {
					let fileLastDot = file.lastIndexOf('.');
					file = file.substr(0, fileLastDot);
					file += '.mp4';
					type = 'video/mp4';
				}
				src += 'video/' + year + '/' + month + '/' + day + '/' + issuingUser + '/' + stamp + receivingUser + file;
				content = `
					<video controls>
						<source src="${src}" type="${type}">
					</video>
				`;
				break;
			case 'audio':
				src += 'audio/' + year + '/' + month + '/' + day + '/' + issuingUser + '/' + stamp + receivingUser + file;
				content = `
					<audio controls>
						<source src="${src}" type="${type}">
					</audio>
				`;
				break;
			case 'application':
				src += 'docs/' + year + '/' + month + '/' + day + '/' + issuingUser + '/' + stamp + receivingUser + file;
				content = `
					<object data="${src}" type="${type}" width="100%" height="100%">
						<p>${pf.const.language.RSC173}</p>
						<p>${pf.const.language.RSC174}</p>
					</object>
				`;
				break;
			default:
				content = '';
		}

		$('.attachmentContainer').html(content);

		$('#downloadAttachment').off().on('click', function(e) {
			e.preventDefault();
			self.createFileServer(src, file);
		});

		$('#closeAttachment').off().on('click', function() {
			$('#attachmentViewer').hide();
		});
	},

	createFileServer(url, file) {
		let client = JSON.parse(sessionStorage['STCMBackEnd:user']);
		let mail = client.email.split('@');
		let user = mail[0].replace('.', '_');

		let parameters = {
			url: url,
			file: file,
			user: user
		};
		ajaxComunCallWithCallbackOne('getAttachedConversation', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				let resp = JSON.parse(ajaxReturn.resData.response);
				let src = stcm.const.downloads + resp.file;
				let link = document.createElement('a');
				link.href = src;
				link.download = file;
				document.body.appendChild(link);
				link.click();
				document.body.removeChild(link);

				let parameters = {
					filename: resp.file
				};
				ajaxComunCallWithCallback('deleteFile', parameters, function(ajaxReturn) {
					if(ajaxReturn) {
						//
					}
				});
			}
		});
	}
};