import { ChangeDetectorRef, Component, inject, Input, OnChanges, OnDestroy, output, signal, SimpleChanges } from '@angular/core'; import { HttpErrorResponse } from '@angular/common/http'; import { combineLatest, Subscription, timeout, TimeoutError } from 'rxjs'; import { MatButtonModule } from '@angular/material/button'; import { MatProgressBarModule } from '@angular/material/progress-bar'; import { PlotlyChart } from '../../shared/plotly/plotly-chart'; import { Dominio, Indicador, IndicadorMetadatos, PlotlyFigure, Tema } from './indicadores.models'; import { describePeriods, filterCompatibility, GlobalApplied } from './indicadores-memory'; import { IndicadoresSnapshots, snapshotKey } from './indicadores-snapshots'; import { httpMessage } from './indicadores-http'; import { percentText } from './indicadores-format'; import { declaraEstrato, stratifiedCapabilities } from './indicadores-stratified'; import { barras, Celda, clic, dona, ESTRATO, Escenario, Eu7Incompatible, Modelo, modelo, porcentaje, periodosCompatibles, Seleccion, seleccionEtiqueta } from './indicadores-eu7-escenario'; const EU7_FIGURES = [['fig_c2_donas', 'Dona de dos anillos'], ['fig_c2_barras', 'Barras por escenario clínico']] as const; @Component({ selector: 'app-indicador-eu7-escenario', imports: [MatButtonModule, MatProgressBarModule, PlotlyChart], templateUrl: './indicador-eu7-escenario.html', styleUrl: './indicador-eu7-escenario.scss', }) export class IndicadorEu7Escenario implements OnChanges, OnDestroy { @Input({ required: true }) dominio!: Dominio; @Input({ required: true }) indicador!: Indicador; @Input({ required: true }) tema!: Tema; @Input({ required: true }) applied!: GlobalApplied; @Input() visible = true; @Input() metadata?: IndicadorMetadatos; readonly metadataRequested = output(); readonly status = signal<'deferred' | 'loading' | 'ready' | 'empty' | 'error' | 'incompatible'>('deferred'); message = ''; selection: Seleccion = {}; periods: string[] = []; periodIndex = 0; model?: Modelo; donutFigure?: PlotlyFigure; barsFigure?: PlotlyFigure; helpOpen = false; private readonly snapshots = inject(IndicadoresSnapshots); private readonly changeDetector = inject(ChangeDetectorRef); private subscription?: Subscription; private key = ''; private loaded = false; private pages: Modelo[] = []; get appliedSummary() { return describePeriods(this.applied.tipo, this.applied.selection); } get selectionLabel() { return this.model ? seleccionEtiqueta(this.model, this.selection) : 'TOTAL'; } get sinDatoNote() { const m = this.model; if (!m) return ''; if (m.vacio) return 'No hay registros publicados en este periodo.'; const n = m.sinDato.n; return n === null ? `${m.sinDatoEtiqueta}: ${m.sinDato.estado}. Fuera de la dona.` : m.total === null ? `Fuera de la dona: ${n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte. Total de la dona no disponible.` : `Fuera de la dona: ${n} de ${m.total + n} pacientes con resultado no disponible o de calidad de espécimen insatisfactoria a la fecha de corte.`; } get generalCells() { const m = this.model; return !m || m.vacio ? [] : [...m.categorias.map(c => ({ etiqueta: c.etiqueta, celda: m.celdas[c.id] })), { etiqueta: m.sinDatoEtiqueta, celda: m.sinDato }]; } get scenarioCells() { const m = this.model; return !m ? [] : m.escenarios.flatMap(s => [...m.categorias.map(c => ({ escenario: s.etiqueta, categoria: c.etiqueta, celda: s.celdas[c.id], den: s.den, pct: porcentaje(s, c.id) })), { escenario: s.etiqueta, categoria: m.sinDatoEtiqueta, celda: s.celdas['SIN_DATO'], den: null, pct: null }]); } // "Cómo leer" shows only what the kit publishes for the two figures of this view. get readingGuide() { const details = this.metadata?.figuras_detalle ?? []; return EU7_FIGURES.flatMap(([figura, nombre]) => { const detail = details.find(item => item.figura === figura); const descripcion = detail?.descripcion?.trim() ?? ''; const como_leer = (detail?.como_leer ?? []).filter(line => line.trim().length > 0); return descripcion || como_leer.length ? [{ figura, nombre, descripcion, como_leer }] : []; }); } cellText(cell: Celda) { return cell.n === null ? cell.estado : cell.n.toLocaleString('es-MX'); } percentText(value: number | null) { return percentText(value); } toggleHelp() { this.helpOpen = !this.helpOpen; if (this.helpOpen) this.metadataRequested.emit(); } ngOnChanges(changes: SimpleChanges) { const key = snapshotKey(this.dominio, this.indicador, this.applied) + JSON.stringify([ this.indicador.contrato, this.indicador.tipos_periodo, this.indicador.figuras, this.indicador.filtros]); if (key !== this.key) { this.subscription?.unsubscribe(); this.key = key; this.loaded = false; this.pages = []; this.periods = []; this.model = undefined; this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; if (!this.visible) { this.status.set('deferred'); return; } this.load(); } else if (this.visible && !this.loaded) this.load(); else if (this.model && changes['tema']) this.draw(); // Visibility and metadata changes must not restart Plotly rendering. } retry() { if (this.visible) this.load(); } private load() { this.subscription?.unsubscribe(); this.loaded = true; this.model = undefined; this.pages = []; this.periods = []; this.selection = {}; this.donutFigure = undefined; this.barsFigure = undefined; const compatibility = filterCompatibility(this.applied, this.indicador.tipos_periodo); if (this.dominio !== 'cacu' || this.indicador.id !== 'cacu_eu7' || this.indicador.contrato !== 'C2' || !this.indicador.figuras.includes('fig_c2_donas') || !this.indicador.figuras.includes('fig_c2_barras') || !(stratifiedCapabilities(this.indicador).includes(ESTRATO) || declaraEstrato(this.indicador, ESTRATO)) || !compatibility.compatible) { this.message = !compatibility.compatible ? compatibility.reason : 'El catálogo no publica las capacidades necesarias para esta vista EU7.'; this.status.set('incompatible'); return; } const key = this.key; const periods = this.applied.selection.mode === 'explicit' ? [...this.applied.selection.periodos] : undefined; this.status.set('loading'); this.subscription = combineLatest([ this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version), this.snapshots.datos(this.dominio, this.indicador.id, this.applied.tipo, periods, this.indicador.version, { estrato: ESTRATO }), ]).pipe(timeout({ first: 40000 })).subscribe({ next: ([general, escenarios]) => { if (key !== this.key) return; try { this.periods = periodosCompatibles(general, escenarios, this.applied.tipo, periods); this.pages = this.periods.map(p => modelo(general, escenarios, p)); this.periodIndex = 0; this.activatePeriod(); } catch (error) { this.failure(error); } }, error: error => { if (key === this.key) this.failure(error); }, }); } private failure(error: unknown) { this.model = undefined; this.donutFigure = undefined; this.barsFigure = undefined; this.message = error instanceof TimeoutError ? 'El servicio tardó demasiado. Vuelve a intentar.' : error instanceof Eu7Incompatible ? error.message : httpMessage(error) + (error instanceof HttpErrorResponse && error.status === 404 && this.applied.selection.mode === 'explicit' && this.applied.selection.periodos.length > 1 ? ' La respuesta corresponde al conjunto de periodos solicitado.' : ''); this.status.set(error instanceof Eu7Incompatible || error instanceof Error && !(error instanceof HttpErrorResponse) && !(error instanceof TimeoutError) ? 'incompatible' : 'error'); } private activatePeriod() { this.model = this.pages[this.periodIndex]; this.selection = {}; this.draw(); this.status.set(this.model ? this.model.vacio ? 'empty' : 'ready' : 'empty'); } changePeriod(step: number) { if (![1, -1].includes(step) || !this.pages[this.periodIndex + step]) return; this.periodIndex += step; this.activatePeriod(); } select(trace: string, index = 0) { if (!this.model || this.status() !== 'ready') return; this.selection = clic(this.model, this.selection, trace, index); this.draw(); } plotClicked(event: unknown) { const point = (event as { points?: { data?: { name?: string }; pointNumber?: number }[] } | null)?.points?.[0]; if (point?.data && typeof point.data.name === 'string' && Number.isInteger(point.pointNumber)) this.select(point.data.name, point.pointNumber); } private draw() { if (!this.model) return; this.donutFigure = dona(this.model, this.selection, this.tema); this.barsFigure = barras(this.model, this.selection, this.tema); this.changeDetector.markForCheck(); } ngOnDestroy() { this.subscription?.unsubscribe(); } }