myio-js-library 0.1.140 → 0.1.141

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -17972,13 +17972,13 @@ ${rangeText}`;
17972
17972
  function initializeModal() {
17973
17973
  if (data) {
17974
17974
  modalState.goalsData = data;
17975
- renderModal();
17975
+ renderModal3();
17976
17976
  } else {
17977
- renderModal();
17977
+ renderModal3();
17978
17978
  loadGoalsData();
17979
17979
  }
17980
17980
  }
17981
- function renderModal() {
17981
+ function renderModal3() {
17982
17982
  const existing = document.getElementById("myio-goals-panel-modal");
17983
17983
  if (existing) {
17984
17984
  existing.remove();
@@ -19367,7 +19367,1728 @@ ${rangeText}`;
19367
19367
  }
19368
19368
  }
19369
19369
 
19370
+ // src/components/temperature/utils.ts
19371
+ var DAY_PERIODS = [
19372
+ { id: "madrugada", label: "Madrugada (00h-06h)", startHour: 0, endHour: 6 },
19373
+ { id: "manha", label: "Manh\xE3 (06h-12h)", startHour: 6, endHour: 12 },
19374
+ { id: "tarde", label: "Tarde (12h-18h)", startHour: 12, endHour: 18 },
19375
+ { id: "noite", label: "Noite (18h-24h)", startHour: 18, endHour: 24 }
19376
+ ];
19377
+ var DEFAULT_CLAMP_RANGE = { min: 15, max: 40 };
19378
+ function getTodaySoFar() {
19379
+ const now = /* @__PURE__ */ new Date();
19380
+ const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0, 0);
19381
+ return {
19382
+ startTs: startOfDay.getTime(),
19383
+ endTs: now.getTime()
19384
+ };
19385
+ }
19386
+ var CHART_COLORS = [
19387
+ "#1976d2",
19388
+ // Blue
19389
+ "#FF6B6B",
19390
+ // Red
19391
+ "#4CAF50",
19392
+ // Green
19393
+ "#FF9800",
19394
+ // Orange
19395
+ "#9C27B0",
19396
+ // Purple
19397
+ "#00BCD4",
19398
+ // Cyan
19399
+ "#E91E63",
19400
+ // Pink
19401
+ "#795548"
19402
+ // Brown
19403
+ ];
19404
+ async function fetchTemperatureData(token, deviceId, startTs, endTs) {
19405
+ const url = `/api/plugins/telemetry/DEVICE/${deviceId}/values/timeseries?keys=temperature&startTs=${encodeURIComponent(startTs)}&endTs=${encodeURIComponent(endTs)}&limit=50000&agg=NONE`;
19406
+ const response = await fetch(url, {
19407
+ headers: {
19408
+ "X-Authorization": `Bearer ${token}`,
19409
+ "Content-Type": "application/json"
19410
+ }
19411
+ });
19412
+ if (!response.ok) {
19413
+ throw new Error(`Failed to fetch temperature data: ${response.status}`);
19414
+ }
19415
+ const data = await response.json();
19416
+ return data?.temperature || [];
19417
+ }
19418
+ function clampTemperature(value, range = DEFAULT_CLAMP_RANGE) {
19419
+ const num = Number(value || 0);
19420
+ if (num < range.min) return range.min;
19421
+ if (num > range.max) return range.max;
19422
+ return num;
19423
+ }
19424
+ function calculateStats(data, clampRange = DEFAULT_CLAMP_RANGE) {
19425
+ if (data.length === 0) {
19426
+ return { avg: 0, min: 0, max: 0, count: 0 };
19427
+ }
19428
+ const values = data.map((item) => clampTemperature(item.value, clampRange));
19429
+ const sum = values.reduce((acc, v) => acc + v, 0);
19430
+ return {
19431
+ avg: sum / values.length,
19432
+ min: Math.min(...values),
19433
+ max: Math.max(...values),
19434
+ count: values.length
19435
+ };
19436
+ }
19437
+ function interpolateTemperature(data, options) {
19438
+ const { intervalMinutes, startTs, endTs, clampRange = DEFAULT_CLAMP_RANGE } = options;
19439
+ const intervalMs = intervalMinutes * 60 * 1e3;
19440
+ if (data.length === 0) {
19441
+ return [];
19442
+ }
19443
+ const sortedData = [...data].sort((a, b) => a.ts - b.ts);
19444
+ const result = [];
19445
+ let lastKnownValue = clampTemperature(sortedData[0].value, clampRange);
19446
+ let dataIndex = 0;
19447
+ for (let ts = startTs; ts <= endTs; ts += intervalMs) {
19448
+ while (dataIndex < sortedData.length - 1 && sortedData[dataIndex + 1].ts <= ts) {
19449
+ dataIndex++;
19450
+ }
19451
+ const currentData = sortedData[dataIndex];
19452
+ if (currentData && Math.abs(currentData.ts - ts) < intervalMs) {
19453
+ lastKnownValue = clampTemperature(currentData.value, clampRange);
19454
+ }
19455
+ result.push({
19456
+ ts,
19457
+ value: lastKnownValue
19458
+ });
19459
+ }
19460
+ return result;
19461
+ }
19462
+ function aggregateByDay(data, clampRange = DEFAULT_CLAMP_RANGE) {
19463
+ if (data.length === 0) {
19464
+ return [];
19465
+ }
19466
+ const dayMap = /* @__PURE__ */ new Map();
19467
+ data.forEach((item) => {
19468
+ const date = new Date(item.ts);
19469
+ const dateKey = date.toISOString().split("T")[0];
19470
+ if (!dayMap.has(dateKey)) {
19471
+ dayMap.set(dateKey, []);
19472
+ }
19473
+ dayMap.get(dateKey).push(item);
19474
+ });
19475
+ const result = [];
19476
+ dayMap.forEach((dayData, dateKey) => {
19477
+ const values = dayData.map((item) => clampTemperature(item.value, clampRange));
19478
+ const sum = values.reduce((acc, v) => acc + v, 0);
19479
+ result.push({
19480
+ date: dateKey,
19481
+ dateTs: new Date(dateKey).getTime(),
19482
+ avg: sum / values.length,
19483
+ min: Math.min(...values),
19484
+ max: Math.max(...values),
19485
+ count: values.length
19486
+ });
19487
+ });
19488
+ return result.sort((a, b) => a.dateTs - b.dateTs);
19489
+ }
19490
+ function filterByDayPeriods(data, selectedPeriods) {
19491
+ if (selectedPeriods.length === 0 || selectedPeriods.length === DAY_PERIODS.length) {
19492
+ return data;
19493
+ }
19494
+ return data.filter((item) => {
19495
+ const date = new Date(item.ts);
19496
+ const hour = date.getHours();
19497
+ return selectedPeriods.some((periodId) => {
19498
+ const period = DAY_PERIODS.find((p) => p.id === periodId);
19499
+ if (!period) return false;
19500
+ return hour >= period.startHour && hour < period.endHour;
19501
+ });
19502
+ });
19503
+ }
19504
+ function getSelectedPeriodsLabel(selectedPeriods) {
19505
+ if (selectedPeriods.length === 0 || selectedPeriods.length === DAY_PERIODS.length) {
19506
+ return "Todos os per\xEDodos";
19507
+ }
19508
+ if (selectedPeriods.length === 1) {
19509
+ const period = DAY_PERIODS.find((p) => p.id === selectedPeriods[0]);
19510
+ return period?.label || "";
19511
+ }
19512
+ return `${selectedPeriods.length} per\xEDodos selecionados`;
19513
+ }
19514
+ function formatTemperature(value, decimals = 1) {
19515
+ return `${value.toFixed(decimals)}\xB0C`;
19516
+ }
19517
+ function exportTemperatureCSV(data, deviceLabel, stats, startDate, endDate) {
19518
+ if (data.length === 0) {
19519
+ console.warn("No data to export");
19520
+ return;
19521
+ }
19522
+ const BOM = "\uFEFF";
19523
+ let csvContent = BOM;
19524
+ csvContent += `Relat\xF3rio de Temperatura - ${deviceLabel}
19525
+ `;
19526
+ csvContent += `Per\xEDodo: ${startDate} at\xE9 ${endDate}
19527
+ `;
19528
+ csvContent += `M\xE9dia: ${formatTemperature(stats.avg)}
19529
+ `;
19530
+ csvContent += `M\xEDnima: ${formatTemperature(stats.min)}
19531
+ `;
19532
+ csvContent += `M\xE1xima: ${formatTemperature(stats.max)}
19533
+ `;
19534
+ csvContent += `Total de leituras: ${stats.count}
19535
+ `;
19536
+ csvContent += "\n";
19537
+ csvContent += "Data/Hora,Temperatura (\xB0C)\n";
19538
+ data.forEach((item) => {
19539
+ const date = new Date(item.ts).toLocaleString("pt-BR");
19540
+ const temp = Number(item.value).toFixed(2);
19541
+ csvContent += `"${date}",${temp}
19542
+ `;
19543
+ });
19544
+ const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
19545
+ const url = URL.createObjectURL(blob);
19546
+ const link = document.createElement("a");
19547
+ link.href = url;
19548
+ link.download = `temperatura_${deviceLabel.replace(/\s+/g, "_")}_${startDate}_${endDate}.csv`;
19549
+ document.body.appendChild(link);
19550
+ link.click();
19551
+ document.body.removeChild(link);
19552
+ URL.revokeObjectURL(url);
19553
+ }
19554
+ var DARK_THEME = {
19555
+ background: "rgba(0, 0, 0, 0.85)",
19556
+ surface: "#1a1f28",
19557
+ text: "#ffffff",
19558
+ textMuted: "rgba(255, 255, 255, 0.7)",
19559
+ border: "rgba(255, 255, 255, 0.1)",
19560
+ primary: "#1976d2",
19561
+ success: "#4CAF50",
19562
+ warning: "#FF9800",
19563
+ danger: "#f44336",
19564
+ chartLine: "#1976d2",
19565
+ chartGrid: "rgba(255, 255, 255, 0.1)"
19566
+ };
19567
+ var LIGHT_THEME = {
19568
+ background: "rgba(0, 0, 0, 0.6)",
19569
+ surface: "#ffffff",
19570
+ text: "#333333",
19571
+ textMuted: "#666666",
19572
+ border: "#e0e0e0",
19573
+ primary: "#1976d2",
19574
+ success: "#4CAF50",
19575
+ warning: "#FF9800",
19576
+ danger: "#f44336",
19577
+ chartLine: "#1976d2",
19578
+ chartGrid: "#e0e0e0"
19579
+ };
19580
+ function getThemeColors(theme) {
19581
+ return theme === "dark" ? DARK_THEME : LIGHT_THEME;
19582
+ }
19583
+
19584
+ // src/components/temperature/TemperatureModal.ts
19585
+ async function openTemperatureModal(params) {
19586
+ const modalId = `myio-temp-modal-${Date.now()}`;
19587
+ const defaultDateRange = getTodaySoFar();
19588
+ const startTs = params.startDate ? new Date(params.startDate).getTime() : defaultDateRange.startTs;
19589
+ const endTs = params.endDate ? new Date(params.endDate).getTime() : defaultDateRange.endTs;
19590
+ const state = {
19591
+ token: params.token,
19592
+ deviceId: params.deviceId,
19593
+ label: params.label || "Sensor de Temperatura",
19594
+ currentTemperature: params.currentTemperature ?? null,
19595
+ temperatureMin: params.temperatureMin ?? null,
19596
+ temperatureMax: params.temperatureMax ?? null,
19597
+ temperatureStatus: params.temperatureStatus ?? null,
19598
+ startTs,
19599
+ endTs,
19600
+ granularity: params.granularity || "hour",
19601
+ theme: params.theme || "light",
19602
+ clampRange: params.clampRange || DEFAULT_CLAMP_RANGE,
19603
+ locale: params.locale || "pt-BR",
19604
+ data: [],
19605
+ stats: { avg: 0, min: 0, max: 0, count: 0 },
19606
+ isLoading: true,
19607
+ dateRangePicker: null,
19608
+ selectedPeriods: ["madrugada", "manha", "tarde", "noite"]
19609
+ // All periods selected by default
19610
+ };
19611
+ const savedGranularity = localStorage.getItem("myio-temp-modal-granularity");
19612
+ const savedTheme = localStorage.getItem("myio-temp-modal-theme");
19613
+ if (savedGranularity) state.granularity = savedGranularity;
19614
+ if (savedTheme) state.theme = savedTheme;
19615
+ const modalContainer = document.createElement("div");
19616
+ modalContainer.id = modalId;
19617
+ document.body.appendChild(modalContainer);
19618
+ renderModal(modalContainer, state, modalId);
19619
+ try {
19620
+ state.data = await fetchTemperatureData(state.token, state.deviceId, state.startTs, state.endTs);
19621
+ state.stats = calculateStats(state.data, state.clampRange);
19622
+ state.isLoading = false;
19623
+ renderModal(modalContainer, state, modalId);
19624
+ drawChart(modalId, state);
19625
+ } catch (error) {
19626
+ console.error("[TemperatureModal] Error fetching data:", error);
19627
+ state.isLoading = false;
19628
+ renderModal(modalContainer, state, modalId, error);
19629
+ }
19630
+ await setupEventListeners(modalContainer, state, modalId, params.onClose);
19631
+ return {
19632
+ destroy: () => {
19633
+ modalContainer.remove();
19634
+ params.onClose?.();
19635
+ },
19636
+ updateData: async (startDate, endDate, granularity) => {
19637
+ state.startTs = new Date(startDate).getTime();
19638
+ state.endTs = new Date(endDate).getTime();
19639
+ if (granularity) state.granularity = granularity;
19640
+ state.isLoading = true;
19641
+ renderModal(modalContainer, state, modalId);
19642
+ try {
19643
+ state.data = await fetchTemperatureData(state.token, state.deviceId, state.startTs, state.endTs);
19644
+ state.stats = calculateStats(state.data, state.clampRange);
19645
+ state.isLoading = false;
19646
+ renderModal(modalContainer, state, modalId);
19647
+ drawChart(modalId, state);
19648
+ } catch (error) {
19649
+ console.error("[TemperatureModal] Error updating data:", error);
19650
+ state.isLoading = false;
19651
+ renderModal(modalContainer, state, modalId, error);
19652
+ }
19653
+ }
19654
+ };
19655
+ }
19656
+ function renderModal(container, state, modalId, error) {
19657
+ const colors = getThemeColors(state.theme);
19658
+ const startDateStr = new Date(state.startTs).toLocaleDateString(state.locale);
19659
+ const endDateStr = new Date(state.endTs).toLocaleDateString(state.locale);
19660
+ const statusText = state.temperatureStatus === "ok" ? "Dentro da faixa" : state.temperatureStatus === "above" ? "Acima do limite" : state.temperatureStatus === "below" ? "Abaixo do limite" : "N/A";
19661
+ const statusColor = state.temperatureStatus === "ok" ? colors.success : state.temperatureStatus === "above" ? colors.danger : state.temperatureStatus === "below" ? colors.primary : colors.textMuted;
19662
+ const rangeText = state.temperatureMin !== null && state.temperatureMax !== null ? `${state.temperatureMin}\xB0C - ${state.temperatureMax}\xB0C` : "N\xE3o definida";
19663
+ new Date(state.startTs).toISOString().slice(0, 16);
19664
+ new Date(state.endTs).toISOString().slice(0, 16);
19665
+ const isMaximized = container.__isMaximized || false;
19666
+ const contentMaxWidth = isMaximized ? "100%" : "900px";
19667
+ const contentMaxHeight = isMaximized ? "100vh" : "95vh";
19668
+ const contentBorderRadius = isMaximized ? "0" : "10px";
19669
+ container.innerHTML = `
19670
+ <div class="myio-temp-modal-overlay" style="
19671
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
19672
+ background: rgba(0, 0, 0, 0.5); z-index: 9998;
19673
+ display: flex; justify-content: center; align-items: center;
19674
+ backdrop-filter: blur(2px);
19675
+ ">
19676
+ <div class="myio-temp-modal-content" style="
19677
+ background: ${colors.surface}; border-radius: ${contentBorderRadius};
19678
+ max-width: ${contentMaxWidth}; width: ${isMaximized ? "100%" : "95%"};
19679
+ max-height: ${contentMaxHeight}; height: ${isMaximized ? "100%" : "auto"};
19680
+ overflow: hidden; display: flex; flex-direction: column;
19681
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
19682
+ font-family: 'Roboto', Arial, sans-serif;
19683
+ ">
19684
+ <!-- Header - MyIO Premium Style -->
19685
+ <div style="
19686
+ padding: 4px 8px; display: flex; align-items: center; justify-content: space-between;
19687
+ background: #3e1a7d; color: white; border-radius: ${isMaximized ? "0" : "10px 10px 0 0"};
19688
+ min-height: 20px;
19689
+ ">
19690
+ <h2 style="margin: 6px; font-size: 18px; font-weight: 600; color: white; line-height: 2;">
19691
+ \u{1F321}\uFE0F ${state.label} - Hist\xF3rico de Temperatura
19692
+ </h2>
19693
+ <div style="display: flex; gap: 4px; align-items: center;">
19694
+ <!-- Theme Toggle -->
19695
+ <button id="${modalId}-theme-toggle" title="Alternar tema" style="
19696
+ background: none; border: none; font-size: 16px; cursor: pointer;
19697
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
19698
+ transition: background-color 0.2s;
19699
+ ">${state.theme === "dark" ? "\u2600\uFE0F" : "\u{1F319}"}</button>
19700
+ <!-- Maximize Button -->
19701
+ <button id="${modalId}-maximize" title="${isMaximized ? "Restaurar" : "Maximizar"}" style="
19702
+ background: none; border: none; font-size: 16px; cursor: pointer;
19703
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
19704
+ transition: background-color 0.2s;
19705
+ ">${isMaximized ? "\u{1F5D7}" : "\u{1F5D6}"}</button>
19706
+ <!-- Close Button -->
19707
+ <button id="${modalId}-close" title="Fechar" style="
19708
+ background: none; border: none; font-size: 20px; cursor: pointer;
19709
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
19710
+ transition: background-color 0.2s;
19711
+ ">\xD7</button>
19712
+ </div>
19713
+ </div>
19714
+
19715
+ <!-- Body -->
19716
+ <div style="flex: 1; overflow-y: auto; padding: 16px;">
19717
+
19718
+ <!-- Controls Row -->
19719
+ <div style="
19720
+ display: flex; gap: 16px; flex-wrap: wrap; align-items: flex-end;
19721
+ margin-bottom: 16px; padding: 16px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#f7f7f7"};
19722
+ border-radius: 6px; border: 1px solid ${colors.border};
19723
+ ">
19724
+ <!-- Granularity Select -->
19725
+ <div>
19726
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
19727
+ Granularidade
19728
+ </label>
19729
+ <select id="${modalId}-granularity" style="
19730
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
19731
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
19732
+ cursor: pointer; min-width: 130px;
19733
+ ">
19734
+ <option value="hour" ${state.granularity === "hour" ? "selected" : ""}>Hora (30 min)</option>
19735
+ <option value="day" ${state.granularity === "day" ? "selected" : ""}>Dia (m\xE9dia)</option>
19736
+ </select>
19737
+ </div>
19738
+ <!-- Day Period Filter (Multiselect) -->
19739
+ <div style="position: relative;">
19740
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
19741
+ Per\xEDodos do Dia
19742
+ </label>
19743
+ <button id="${modalId}-period-btn" type="button" style="
19744
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
19745
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
19746
+ cursor: pointer; min-width: 180px; text-align: left;
19747
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
19748
+ ">
19749
+ <span>${getSelectedPeriodsLabel(state.selectedPeriods)}</span>
19750
+ <span style="font-size: 10px;">\u25BC</span>
19751
+ </button>
19752
+ <div id="${modalId}-period-dropdown" style="
19753
+ display: none; position: absolute; top: 100%; left: 0; z-index: 1000;
19754
+ background: ${colors.surface}; border: 1px solid ${colors.border};
19755
+ border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);
19756
+ min-width: 200px; margin-top: 4px; padding: 8px 0;
19757
+ ">
19758
+ ${DAY_PERIODS.map((period) => `
19759
+ <label style="
19760
+ display: flex; align-items: center; gap: 8px; padding: 8px 12px;
19761
+ cursor: pointer; font-size: 13px; color: ${colors.text};
19762
+ " onmouseover="this.style.background='${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"}'"
19763
+ onmouseout="this.style.background='transparent'">
19764
+ <input type="checkbox"
19765
+ name="${modalId}-period"
19766
+ value="${period.id}"
19767
+ ${state.selectedPeriods.includes(period.id) ? "checked" : ""}
19768
+ style="width: 16px; height: 16px; cursor: pointer; accent-color: #3e1a7d;">
19769
+ ${period.label}
19770
+ </label>
19771
+ `).join("")}
19772
+ <div style="border-top: 1px solid ${colors.border}; margin-top: 8px; padding-top: 8px;">
19773
+ <button id="${modalId}-period-select-all" type="button" style="
19774
+ width: calc(100% - 16px); margin: 0 8px 4px; padding: 6px;
19775
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"};
19776
+ border: none; border-radius: 4px; cursor: pointer;
19777
+ font-size: 12px; color: ${colors.text};
19778
+ ">Selecionar Todos</button>
19779
+ <button id="${modalId}-period-clear" type="button" style="
19780
+ width: calc(100% - 16px); margin: 0 8px; padding: 6px;
19781
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"};
19782
+ border: none; border-radius: 4px; cursor: pointer;
19783
+ font-size: 12px; color: ${colors.text};
19784
+ ">Limpar Sele\xE7\xE3o</button>
19785
+ </div>
19786
+ </div>
19787
+ </div>
19788
+ <!-- Date Range Picker -->
19789
+ <div style="flex: 1; min-width: 220px;">
19790
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
19791
+ Per\xEDodo
19792
+ </label>
19793
+ <input type="text" id="${modalId}-date-range" readonly placeholder="Selecione o per\xEDodo..." style="
19794
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
19795
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
19796
+ width: 100%; cursor: pointer; box-sizing: border-box;
19797
+ "/>
19798
+ </div>
19799
+ <!-- Query Button -->
19800
+ <button id="${modalId}-query" style="
19801
+ background: #3e1a7d; color: white; border: none;
19802
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
19803
+ font-size: 14px; font-weight: 500; height: 38px;
19804
+ display: flex; align-items: center; gap: 8px;
19805
+ font-family: 'Roboto', Arial, sans-serif;
19806
+ " ${state.isLoading ? "disabled" : ""}>
19807
+ ${state.isLoading ? '<span style="animation: spin 1s linear infinite; display: inline-block;">\u21BB</span> Carregando...' : "Carregar"}
19808
+ </button>
19809
+ </div>
19810
+
19811
+ <!-- Stats Cards -->
19812
+ <div style="
19813
+ display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
19814
+ gap: 12px; margin-bottom: 16px;
19815
+ ">
19816
+ <!-- Current Temperature -->
19817
+ <div style="
19818
+ padding: 16px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#fafafa"};
19819
+ border-radius: 12px; border: 1px solid ${colors.border};
19820
+ ">
19821
+ <span style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500;">Temperatura Atual</span>
19822
+ <div style="font-weight: 700; font-size: 24px; color: ${statusColor}; margin-top: 4px;">
19823
+ ${state.currentTemperature !== null ? formatTemperature(state.currentTemperature) : "N/A"}
19824
+ </div>
19825
+ <div style="font-size: 11px; color: ${statusColor}; margin-top: 2px;">${statusText}</div>
19826
+ </div>
19827
+ <!-- Average -->
19828
+ <div style="
19829
+ padding: 16px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#fafafa"};
19830
+ border-radius: 12px; border: 1px solid ${colors.border};
19831
+ ">
19832
+ <span style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500;">M\xE9dia do Per\xEDodo</span>
19833
+ <div id="${modalId}-avg" style="font-weight: 600; font-size: 20px; color: ${colors.text}; margin-top: 4px;">
19834
+ ${state.stats.count > 0 ? formatTemperature(state.stats.avg) : "N/A"}
19835
+ </div>
19836
+ <div style="font-size: 11px; color: ${colors.textMuted}; margin-top: 2px;">${startDateStr} - ${endDateStr}</div>
19837
+ </div>
19838
+ <!-- Min/Max -->
19839
+ <div style="
19840
+ padding: 16px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#fafafa"};
19841
+ border-radius: 12px; border: 1px solid ${colors.border};
19842
+ ">
19843
+ <span style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500;">Min / Max</span>
19844
+ <div id="${modalId}-minmax" style="font-weight: 600; font-size: 20px; color: ${colors.text}; margin-top: 4px;">
19845
+ ${state.stats.count > 0 ? `${formatTemperature(state.stats.min)} / ${formatTemperature(state.stats.max)}` : "N/A"}
19846
+ </div>
19847
+ <div style="font-size: 11px; color: ${colors.textMuted}; margin-top: 2px;">${state.stats.count} leituras</div>
19848
+ </div>
19849
+ <!-- Ideal Range -->
19850
+ <div style="
19851
+ padding: 16px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#fafafa"};
19852
+ border-radius: 12px; border: 1px solid ${colors.border};
19853
+ ">
19854
+ <span style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500;">Faixa Ideal</span>
19855
+ <div style="font-weight: 600; font-size: 20px; color: ${colors.success}; margin-top: 4px;">
19856
+ ${rangeText}
19857
+ </div>
19858
+ </div>
19859
+ </div>
19860
+
19861
+ <!-- Chart Container -->
19862
+ <div style="margin-bottom: 20px;">
19863
+ <h3 style="margin: 0 0 12px 0; font-size: 14px; color: ${colors.textMuted}; font-weight: 500;">
19864
+ Hist\xF3rico de Temperatura
19865
+ </h3>
19866
+ <div id="${modalId}-chart" style="
19867
+ height: 320px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.03)" : "#fafafa"};
19868
+ border-radius: 12px; display: flex; justify-content: center; align-items: center;
19869
+ border: 1px solid ${colors.border}; position: relative;
19870
+ ">
19871
+ ${state.isLoading ? `<div style="text-align: center; color: ${colors.textMuted};">
19872
+ <div style="animation: spin 1s linear infinite; font-size: 32px; margin-bottom: 8px;">\u21BB</div>
19873
+ <div>Carregando dados...</div>
19874
+ </div>` : error ? `<div style="text-align: center; color: ${colors.danger};">
19875
+ <div style="font-size: 32px; margin-bottom: 8px;">\u26A0\uFE0F</div>
19876
+ <div>Erro ao carregar dados</div>
19877
+ <div style="font-size: 12px; margin-top: 4px;">${error.message}</div>
19878
+ </div>` : state.data.length === 0 ? `<div style="text-align: center; color: ${colors.textMuted};">
19879
+ <div style="font-size: 32px; margin-bottom: 8px;">\u{1F4ED}</div>
19880
+ <div>Sem dados para o per\xEDodo selecionado</div>
19881
+ </div>` : `<canvas id="${modalId}-canvas" style="width: 100%; height: 100%;"></canvas>`}
19882
+ </div>
19883
+ </div>
19884
+
19885
+ <!-- Actions -->
19886
+ <div style="display: flex; justify-content: flex-end; gap: 12px;">
19887
+ <button id="${modalId}-export" style="
19888
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f7f7f7"};
19889
+ color: ${colors.text}; border: 1px solid ${colors.border};
19890
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
19891
+ font-size: 14px; display: flex; align-items: center; gap: 8px;
19892
+ font-family: 'Roboto', Arial, sans-serif;
19893
+ " ${state.data.length === 0 ? "disabled" : ""}>
19894
+ \u{1F4E5} Exportar CSV
19895
+ </button>
19896
+ <button id="${modalId}-close-btn" style="
19897
+ background: #3e1a7d; color: white; border: none;
19898
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
19899
+ font-size: 14px; font-weight: 500;
19900
+ font-family: 'Roboto', Arial, sans-serif;
19901
+ ">
19902
+ Fechar
19903
+ </button>
19904
+ </div>
19905
+ </div><!-- End Body -->
19906
+ </div>
19907
+ </div>
19908
+ <style>
19909
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
19910
+ #${modalId} select:focus, #${modalId} input:focus {
19911
+ outline: 2px solid #3e1a7d;
19912
+ outline-offset: 2px;
19913
+ }
19914
+ #${modalId} button:hover:not(:disabled) {
19915
+ opacity: 0.9;
19916
+ }
19917
+ #${modalId} button:disabled {
19918
+ opacity: 0.5;
19919
+ cursor: not-allowed;
19920
+ }
19921
+ #${modalId} .myio-temp-modal-content > div:first-child button:hover {
19922
+ background: rgba(255, 255, 255, 0.1) !important;
19923
+ color: white !important;
19924
+ }
19925
+ </style>
19926
+ `;
19927
+ }
19928
+ function drawChart(modalId, state) {
19929
+ const chartContainer = document.getElementById(`${modalId}-chart`);
19930
+ const canvas = document.getElementById(`${modalId}-canvas`);
19931
+ if (!chartContainer || !canvas || state.data.length === 0) return;
19932
+ const ctx = canvas.getContext("2d");
19933
+ if (!ctx) return;
19934
+ const colors = getThemeColors(state.theme);
19935
+ const filteredData = filterByDayPeriods(state.data, state.selectedPeriods);
19936
+ if (filteredData.length === 0) {
19937
+ canvas.width = chartContainer.clientWidth;
19938
+ canvas.height = chartContainer.clientHeight;
19939
+ ctx.fillStyle = colors.textMuted;
19940
+ ctx.font = "14px Roboto, Arial, sans-serif";
19941
+ ctx.textAlign = "center";
19942
+ ctx.fillText("Nenhum dado para os per\xEDodos selecionados", canvas.width / 2, canvas.height / 2);
19943
+ return;
19944
+ }
19945
+ let chartData;
19946
+ if (state.granularity === "hour") {
19947
+ const interpolated = interpolateTemperature(filteredData, {
19948
+ intervalMinutes: 30,
19949
+ startTs: state.startTs,
19950
+ endTs: state.endTs,
19951
+ clampRange: state.clampRange
19952
+ });
19953
+ const filteredInterpolated = filterByDayPeriods(interpolated, state.selectedPeriods);
19954
+ chartData = filteredInterpolated.map((item) => ({
19955
+ x: item.ts,
19956
+ y: Number(item.value),
19957
+ screenX: 0,
19958
+ screenY: 0
19959
+ }));
19960
+ } else {
19961
+ const daily = aggregateByDay(filteredData, state.clampRange);
19962
+ chartData = daily.map((item) => ({
19963
+ x: item.dateTs,
19964
+ y: item.avg,
19965
+ screenX: 0,
19966
+ screenY: 0,
19967
+ label: item.date
19968
+ }));
19969
+ }
19970
+ if (chartData.length === 0) return;
19971
+ const width = chartContainer.clientWidth - 2;
19972
+ const height = 320;
19973
+ canvas.width = width;
19974
+ canvas.height = height;
19975
+ const paddingLeft = 60;
19976
+ const paddingRight = 20;
19977
+ const paddingTop = 20;
19978
+ const paddingBottom = 55;
19979
+ const isPeriodsFiltered = state.selectedPeriods.length < 4 && state.selectedPeriods.length > 0;
19980
+ const values = chartData.map((d) => d.y);
19981
+ const minY = Math.min(...values) - 1;
19982
+ const maxY = Math.max(...values) + 1;
19983
+ const chartWidth = width - paddingLeft - paddingRight;
19984
+ const chartHeight = height - paddingTop - paddingBottom;
19985
+ const scaleY = chartHeight / (maxY - minY || 1);
19986
+ if (isPeriodsFiltered) {
19987
+ const pointSpacing = chartWidth / Math.max(1, chartData.length - 1);
19988
+ chartData.forEach((point, index) => {
19989
+ point.screenX = paddingLeft + index * pointSpacing;
19990
+ point.screenY = height - paddingBottom - (point.y - minY) * scaleY;
19991
+ });
19992
+ } else {
19993
+ const minX = chartData[0].x;
19994
+ const maxX = chartData[chartData.length - 1].x;
19995
+ const timeRange = maxX - minX || 1;
19996
+ const scaleX = chartWidth / timeRange;
19997
+ chartData.forEach((point) => {
19998
+ point.screenX = paddingLeft + (point.x - minX) * scaleX;
19999
+ point.screenY = height - paddingBottom - (point.y - minY) * scaleY;
20000
+ });
20001
+ }
20002
+ ctx.clearRect(0, 0, width, height);
20003
+ ctx.strokeStyle = colors.chartGrid;
20004
+ ctx.lineWidth = 1;
20005
+ for (let i = 0; i <= 4; i++) {
20006
+ const y = paddingTop + chartHeight * i / 4;
20007
+ ctx.beginPath();
20008
+ ctx.moveTo(paddingLeft, y);
20009
+ ctx.lineTo(width - paddingRight, y);
20010
+ ctx.stroke();
20011
+ }
20012
+ if (state.temperatureMin !== null && state.temperatureMax !== null) {
20013
+ const rangeMinY = height - paddingBottom - (state.temperatureMin - minY) * scaleY;
20014
+ const rangeMaxY = height - paddingBottom - (state.temperatureMax - minY) * scaleY;
20015
+ ctx.fillStyle = "rgba(76, 175, 80, 0.1)";
20016
+ ctx.fillRect(paddingLeft, rangeMaxY, chartWidth, rangeMinY - rangeMaxY);
20017
+ ctx.strokeStyle = colors.success;
20018
+ ctx.setLineDash([5, 5]);
20019
+ ctx.beginPath();
20020
+ ctx.moveTo(paddingLeft, rangeMinY);
20021
+ ctx.lineTo(width - paddingRight, rangeMinY);
20022
+ ctx.moveTo(paddingLeft, rangeMaxY);
20023
+ ctx.lineTo(width - paddingRight, rangeMaxY);
20024
+ ctx.stroke();
20025
+ ctx.setLineDash([]);
20026
+ }
20027
+ ctx.strokeStyle = colors.chartLine;
20028
+ ctx.lineWidth = 2;
20029
+ ctx.beginPath();
20030
+ chartData.forEach((point, i) => {
20031
+ if (i === 0) ctx.moveTo(point.screenX, point.screenY);
20032
+ else ctx.lineTo(point.screenX, point.screenY);
20033
+ });
20034
+ ctx.stroke();
20035
+ ctx.fillStyle = colors.chartLine;
20036
+ chartData.forEach((point) => {
20037
+ ctx.beginPath();
20038
+ ctx.arc(point.screenX, point.screenY, 4, 0, Math.PI * 2);
20039
+ ctx.fill();
20040
+ });
20041
+ ctx.fillStyle = colors.textMuted;
20042
+ ctx.font = "11px system-ui, sans-serif";
20043
+ ctx.textAlign = "right";
20044
+ for (let i = 0; i <= 4; i++) {
20045
+ const val = minY + (maxY - minY) * (4 - i) / 4;
20046
+ const y = paddingTop + chartHeight * i / 4;
20047
+ ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 8, y + 4);
20048
+ }
20049
+ ctx.textAlign = "center";
20050
+ const numLabels = Math.min(8, chartData.length);
20051
+ const labelInterval = Math.max(1, Math.floor(chartData.length / numLabels));
20052
+ for (let i = 0; i < chartData.length; i += labelInterval) {
20053
+ const point = chartData[i];
20054
+ const date = new Date(point.x);
20055
+ let label;
20056
+ if (state.granularity === "hour") {
20057
+ label = date.toLocaleTimeString(state.locale, { hour: "2-digit", minute: "2-digit" });
20058
+ } else {
20059
+ label = date.toLocaleDateString(state.locale, { day: "2-digit", month: "2-digit" });
20060
+ }
20061
+ ctx.strokeStyle = colors.chartGrid;
20062
+ ctx.lineWidth = 1;
20063
+ ctx.beginPath();
20064
+ ctx.moveTo(point.screenX, paddingTop);
20065
+ ctx.lineTo(point.screenX, height - paddingBottom);
20066
+ ctx.stroke();
20067
+ ctx.fillStyle = colors.textMuted;
20068
+ ctx.fillText(label, point.screenX, height - paddingBottom + 18);
20069
+ }
20070
+ ctx.strokeStyle = colors.border;
20071
+ ctx.lineWidth = 1;
20072
+ ctx.beginPath();
20073
+ ctx.moveTo(paddingLeft, paddingTop);
20074
+ ctx.lineTo(paddingLeft, height - paddingBottom);
20075
+ ctx.lineTo(width - paddingRight, height - paddingBottom);
20076
+ ctx.stroke();
20077
+ setupChartTooltip(canvas, chartContainer, chartData, state, colors);
20078
+ }
20079
+ function setupChartTooltip(canvas, container, chartData, state, colors) {
20080
+ const existingTooltip = container.querySelector(".myio-chart-tooltip");
20081
+ if (existingTooltip) existingTooltip.remove();
20082
+ const tooltip = document.createElement("div");
20083
+ tooltip.className = "myio-chart-tooltip";
20084
+ tooltip.style.cssText = `
20085
+ position: absolute;
20086
+ background: ${state.theme === "dark" ? "rgba(30, 30, 40, 0.95)" : "rgba(255, 255, 255, 0.98)"};
20087
+ border: 1px solid ${colors.border};
20088
+ border-radius: 8px;
20089
+ padding: 10px 14px;
20090
+ font-size: 13px;
20091
+ color: ${colors.text};
20092
+ pointer-events: none;
20093
+ opacity: 0;
20094
+ transition: opacity 0.15s;
20095
+ z-index: 1000;
20096
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20097
+ min-width: 140px;
20098
+ `;
20099
+ container.appendChild(tooltip);
20100
+ const findNearestPoint = (mouseX, mouseY) => {
20101
+ const threshold = 20;
20102
+ let nearest = null;
20103
+ let minDist = Infinity;
20104
+ for (const point of chartData) {
20105
+ const dist = Math.sqrt(
20106
+ Math.pow(mouseX - point.screenX, 2) + Math.pow(mouseY - point.screenY, 2)
20107
+ );
20108
+ if (dist < minDist && dist < threshold) {
20109
+ minDist = dist;
20110
+ nearest = point;
20111
+ }
20112
+ }
20113
+ return nearest;
20114
+ };
20115
+ canvas.addEventListener("mousemove", (e) => {
20116
+ const rect = canvas.getBoundingClientRect();
20117
+ const mouseX = e.clientX - rect.left;
20118
+ const mouseY = e.clientY - rect.top;
20119
+ const point = findNearestPoint(mouseX, mouseY);
20120
+ if (point) {
20121
+ const date = new Date(point.x);
20122
+ let dateStr;
20123
+ if (state.granularity === "hour") {
20124
+ dateStr = date.toLocaleDateString(state.locale, {
20125
+ day: "2-digit",
20126
+ month: "2-digit",
20127
+ year: "numeric"
20128
+ }) + " " + date.toLocaleTimeString(state.locale, {
20129
+ hour: "2-digit",
20130
+ minute: "2-digit"
20131
+ });
20132
+ } else {
20133
+ dateStr = date.toLocaleDateString(state.locale, {
20134
+ day: "2-digit",
20135
+ month: "2-digit",
20136
+ year: "numeric"
20137
+ });
20138
+ }
20139
+ tooltip.innerHTML = `
20140
+ <div style="font-weight: 600; margin-bottom: 6px; color: ${colors.primary};">
20141
+ ${formatTemperature(point.y)}
20142
+ </div>
20143
+ <div style="font-size: 11px; color: ${colors.textMuted};">
20144
+ \u{1F4C5} ${dateStr}
20145
+ </div>
20146
+ `;
20147
+ let tooltipX = point.screenX + 15;
20148
+ let tooltipY = point.screenY - 15;
20149
+ const tooltipRect = tooltip.getBoundingClientRect();
20150
+ const containerRect = container.getBoundingClientRect();
20151
+ if (tooltipX + tooltipRect.width > containerRect.width - 10) {
20152
+ tooltipX = point.screenX - tooltipRect.width - 15;
20153
+ }
20154
+ if (tooltipY < 10) {
20155
+ tooltipY = point.screenY + 15;
20156
+ }
20157
+ tooltip.style.left = `${tooltipX}px`;
20158
+ tooltip.style.top = `${tooltipY}px`;
20159
+ tooltip.style.opacity = "1";
20160
+ canvas.style.cursor = "pointer";
20161
+ } else {
20162
+ tooltip.style.opacity = "0";
20163
+ canvas.style.cursor = "default";
20164
+ }
20165
+ });
20166
+ canvas.addEventListener("mouseleave", () => {
20167
+ tooltip.style.opacity = "0";
20168
+ canvas.style.cursor = "default";
20169
+ });
20170
+ }
20171
+ async function setupEventListeners(container, state, modalId, onClose) {
20172
+ const closeModal = () => {
20173
+ container.remove();
20174
+ onClose?.();
20175
+ };
20176
+ container.querySelector(".myio-temp-modal-overlay")?.addEventListener("click", (e) => {
20177
+ if (e.target === e.currentTarget) closeModal();
20178
+ });
20179
+ document.getElementById(`${modalId}-close`)?.addEventListener("click", closeModal);
20180
+ document.getElementById(`${modalId}-close-btn`)?.addEventListener("click", closeModal);
20181
+ const dateRangeInput = document.getElementById(`${modalId}-date-range`);
20182
+ if (dateRangeInput && !state.dateRangePicker) {
20183
+ try {
20184
+ state.dateRangePicker = await createDateRangePicker2(dateRangeInput, {
20185
+ presetStart: new Date(state.startTs).toISOString(),
20186
+ presetEnd: new Date(state.endTs).toISOString(),
20187
+ includeTime: true,
20188
+ timePrecision: "minute",
20189
+ maxRangeDays: 90,
20190
+ locale: state.locale,
20191
+ parentEl: container.querySelector(".myio-temp-modal-content"),
20192
+ onApply: (result) => {
20193
+ state.startTs = new Date(result.startISO).getTime();
20194
+ state.endTs = new Date(result.endISO).getTime();
20195
+ console.log("[TemperatureModal] Date range applied:", result);
20196
+ }
20197
+ });
20198
+ } catch (error) {
20199
+ console.warn("[TemperatureModal] DateRangePicker initialization failed:", error);
20200
+ }
20201
+ }
20202
+ document.getElementById(`${modalId}-theme-toggle`)?.addEventListener("click", async () => {
20203
+ state.theme = state.theme === "dark" ? "light" : "dark";
20204
+ localStorage.setItem("myio-temp-modal-theme", state.theme);
20205
+ state.dateRangePicker = null;
20206
+ renderModal(container, state, modalId);
20207
+ if (state.data.length > 0) drawChart(modalId, state);
20208
+ await setupEventListeners(container, state, modalId, onClose);
20209
+ });
20210
+ document.getElementById(`${modalId}-maximize`)?.addEventListener("click", async () => {
20211
+ container.__isMaximized = !container.__isMaximized;
20212
+ state.dateRangePicker = null;
20213
+ renderModal(container, state, modalId);
20214
+ if (state.data.length > 0) drawChart(modalId, state);
20215
+ await setupEventListeners(container, state, modalId, onClose);
20216
+ });
20217
+ const periodBtn = document.getElementById(`${modalId}-period-btn`);
20218
+ const periodDropdown = document.getElementById(`${modalId}-period-dropdown`);
20219
+ periodBtn?.addEventListener("click", (e) => {
20220
+ e.stopPropagation();
20221
+ if (periodDropdown) {
20222
+ periodDropdown.style.display = periodDropdown.style.display === "none" ? "block" : "none";
20223
+ }
20224
+ });
20225
+ document.addEventListener("click", (e) => {
20226
+ if (periodDropdown && !periodDropdown.contains(e.target) && e.target !== periodBtn) {
20227
+ periodDropdown.style.display = "none";
20228
+ }
20229
+ });
20230
+ const periodCheckboxes = document.querySelectorAll(`input[name="${modalId}-period"]`);
20231
+ periodCheckboxes.forEach((checkbox) => {
20232
+ checkbox.addEventListener("change", () => {
20233
+ const checked = Array.from(periodCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
20234
+ state.selectedPeriods = checked;
20235
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20236
+ if (btnLabel) {
20237
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20238
+ }
20239
+ if (state.data.length > 0) drawChart(modalId, state);
20240
+ });
20241
+ });
20242
+ document.getElementById(`${modalId}-period-select-all`)?.addEventListener("click", () => {
20243
+ periodCheckboxes.forEach((cb) => {
20244
+ cb.checked = true;
20245
+ });
20246
+ state.selectedPeriods = ["madrugada", "manha", "tarde", "noite"];
20247
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20248
+ if (btnLabel) {
20249
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20250
+ }
20251
+ if (state.data.length > 0) drawChart(modalId, state);
20252
+ });
20253
+ document.getElementById(`${modalId}-period-clear`)?.addEventListener("click", () => {
20254
+ periodCheckboxes.forEach((cb) => {
20255
+ cb.checked = false;
20256
+ });
20257
+ state.selectedPeriods = [];
20258
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20259
+ if (btnLabel) {
20260
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20261
+ }
20262
+ if (state.data.length > 0) drawChart(modalId, state);
20263
+ });
20264
+ document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
20265
+ state.granularity = e.target.value;
20266
+ localStorage.setItem("myio-temp-modal-granularity", state.granularity);
20267
+ if (state.data.length > 0) drawChart(modalId, state);
20268
+ });
20269
+ document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
20270
+ if (state.startTs >= state.endTs) {
20271
+ alert("Por favor, selecione um per\xEDodo v\xE1lido");
20272
+ return;
20273
+ }
20274
+ state.isLoading = true;
20275
+ state.dateRangePicker = null;
20276
+ renderModal(container, state, modalId);
20277
+ try {
20278
+ state.data = await fetchTemperatureData(state.token, state.deviceId, state.startTs, state.endTs);
20279
+ state.stats = calculateStats(state.data, state.clampRange);
20280
+ state.isLoading = false;
20281
+ renderModal(container, state, modalId);
20282
+ drawChart(modalId, state);
20283
+ await setupEventListeners(container, state, modalId, onClose);
20284
+ } catch (error) {
20285
+ console.error("[TemperatureModal] Error fetching data:", error);
20286
+ state.isLoading = false;
20287
+ renderModal(container, state, modalId, error);
20288
+ await setupEventListeners(container, state, modalId, onClose);
20289
+ }
20290
+ });
20291
+ document.getElementById(`${modalId}-export`)?.addEventListener("click", () => {
20292
+ if (state.data.length === 0) return;
20293
+ const startDateStr = new Date(state.startTs).toLocaleDateString(state.locale).replace(/\//g, "-");
20294
+ const endDateStr = new Date(state.endTs).toLocaleDateString(state.locale).replace(/\//g, "-");
20295
+ exportTemperatureCSV(
20296
+ state.data,
20297
+ state.label,
20298
+ state.stats,
20299
+ startDateStr,
20300
+ endDateStr
20301
+ );
20302
+ });
20303
+ }
20304
+
20305
+ // src/components/temperature/TemperatureComparisonModal.ts
20306
+ async function openTemperatureComparisonModal(params) {
20307
+ const modalId = `myio-temp-comparison-modal-${Date.now()}`;
20308
+ const defaultDateRange = getTodaySoFar();
20309
+ const startTs = params.startDate ? new Date(params.startDate).getTime() : defaultDateRange.startTs;
20310
+ const endTs = params.endDate ? new Date(params.endDate).getTime() : defaultDateRange.endTs;
20311
+ const state = {
20312
+ token: params.token,
20313
+ devices: params.devices,
20314
+ startTs,
20315
+ endTs,
20316
+ granularity: params.granularity || "hour",
20317
+ theme: params.theme || "dark",
20318
+ clampRange: params.clampRange || DEFAULT_CLAMP_RANGE,
20319
+ locale: params.locale || "pt-BR",
20320
+ deviceData: [],
20321
+ isLoading: true,
20322
+ dateRangePicker: null,
20323
+ selectedPeriods: ["madrugada", "manha", "tarde", "noite"]
20324
+ // All periods selected by default
20325
+ };
20326
+ const savedGranularity = localStorage.getItem("myio-temp-comparison-granularity");
20327
+ const savedTheme = localStorage.getItem("myio-temp-comparison-theme");
20328
+ if (savedGranularity) state.granularity = savedGranularity;
20329
+ if (savedTheme) state.theme = savedTheme;
20330
+ const modalContainer = document.createElement("div");
20331
+ modalContainer.id = modalId;
20332
+ document.body.appendChild(modalContainer);
20333
+ renderModal2(modalContainer, state, modalId);
20334
+ await fetchAllDevicesData(state);
20335
+ renderModal2(modalContainer, state, modalId);
20336
+ drawComparisonChart(modalId, state);
20337
+ await setupEventListeners2(modalContainer, state, modalId, params.onClose);
20338
+ return {
20339
+ destroy: () => {
20340
+ modalContainer.remove();
20341
+ params.onClose?.();
20342
+ },
20343
+ updateData: async (startDate, endDate, granularity) => {
20344
+ state.startTs = new Date(startDate).getTime();
20345
+ state.endTs = new Date(endDate).getTime();
20346
+ if (granularity) state.granularity = granularity;
20347
+ state.isLoading = true;
20348
+ renderModal2(modalContainer, state, modalId);
20349
+ await fetchAllDevicesData(state);
20350
+ renderModal2(modalContainer, state, modalId);
20351
+ drawComparisonChart(modalId, state);
20352
+ setupEventListeners2(modalContainer, state, modalId, params.onClose);
20353
+ }
20354
+ };
20355
+ }
20356
+ async function fetchAllDevicesData(state) {
20357
+ state.isLoading = true;
20358
+ state.deviceData = [];
20359
+ try {
20360
+ const results = await Promise.all(
20361
+ state.devices.map(async (device, index) => {
20362
+ const deviceId = device.tbId || device.id;
20363
+ try {
20364
+ const data = await fetchTemperatureData(state.token, deviceId, state.startTs, state.endTs);
20365
+ const stats = calculateStats(data, state.clampRange);
20366
+ return {
20367
+ device,
20368
+ data,
20369
+ stats,
20370
+ color: CHART_COLORS[index % CHART_COLORS.length]
20371
+ };
20372
+ } catch (error) {
20373
+ console.error(`[TemperatureComparisonModal] Error fetching data for ${device.label}:`, error);
20374
+ return {
20375
+ device,
20376
+ data: [],
20377
+ stats: { avg: 0, min: 0, max: 0, count: 0 },
20378
+ color: CHART_COLORS[index % CHART_COLORS.length]
20379
+ };
20380
+ }
20381
+ })
20382
+ );
20383
+ state.deviceData = results;
20384
+ } catch (error) {
20385
+ console.error("[TemperatureComparisonModal] Error fetching data:", error);
20386
+ }
20387
+ state.isLoading = false;
20388
+ }
20389
+ function renderModal2(container, state, modalId) {
20390
+ const colors = getThemeColors(state.theme);
20391
+ new Date(state.startTs).toLocaleDateString(state.locale);
20392
+ new Date(state.endTs).toLocaleDateString(state.locale);
20393
+ new Date(state.startTs).toISOString().slice(0, 16);
20394
+ new Date(state.endTs).toISOString().slice(0, 16);
20395
+ const legendHTML = state.deviceData.map((dd) => `
20396
+ <div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px;
20397
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.03)"};
20398
+ border-radius: 8px;">
20399
+ <span style="width: 12px; height: 12px; border-radius: 50%; background: ${dd.color};"></span>
20400
+ <span style="color: ${colors.text}; font-size: 13px;">${dd.device.label}</span>
20401
+ <span style="color: ${colors.textMuted}; font-size: 11px; margin-left: auto;">
20402
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.avg) : "N/A"}
20403
+ </span>
20404
+ </div>
20405
+ `).join("");
20406
+ const statsHTML = state.deviceData.map((dd) => `
20407
+ <div style="
20408
+ padding: 12px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#fafafa"};
20409
+ border-radius: 10px; border-left: 4px solid ${dd.color};
20410
+ min-width: 150px;
20411
+ ">
20412
+ <div style="font-weight: 600; color: ${colors.text}; font-size: 13px; margin-bottom: 8px;">
20413
+ ${dd.device.label}
20414
+ </div>
20415
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 4px; font-size: 11px;">
20416
+ <span style="color: ${colors.textMuted};">M\xE9dia:</span>
20417
+ <span style="color: ${colors.text}; font-weight: 500;">
20418
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.avg) : "N/A"}
20419
+ </span>
20420
+ <span style="color: ${colors.textMuted};">Min:</span>
20421
+ <span style="color: ${colors.text};">
20422
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.min) : "N/A"}
20423
+ </span>
20424
+ <span style="color: ${colors.textMuted};">Max:</span>
20425
+ <span style="color: ${colors.text};">
20426
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.max) : "N/A"}
20427
+ </span>
20428
+ <span style="color: ${colors.textMuted};">Leituras:</span>
20429
+ <span style="color: ${colors.text};">${dd.stats.count}</span>
20430
+ </div>
20431
+ </div>
20432
+ `).join("");
20433
+ const isMaximized = container.__isMaximized || false;
20434
+ const contentMaxWidth = isMaximized ? "100%" : "1100px";
20435
+ const contentMaxHeight = isMaximized ? "100vh" : "95vh";
20436
+ const contentBorderRadius = isMaximized ? "0" : "10px";
20437
+ container.innerHTML = `
20438
+ <div class="myio-temp-comparison-overlay" style="
20439
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
20440
+ background: rgba(0, 0, 0, 0.5); z-index: 9998;
20441
+ display: flex; justify-content: center; align-items: center;
20442
+ backdrop-filter: blur(2px);
20443
+ ">
20444
+ <div class="myio-temp-comparison-content" style="
20445
+ background: ${colors.surface}; border-radius: ${contentBorderRadius};
20446
+ max-width: ${contentMaxWidth}; width: ${isMaximized ? "100%" : "95%"};
20447
+ max-height: ${contentMaxHeight}; height: ${isMaximized ? "100%" : "auto"};
20448
+ overflow: hidden; display: flex; flex-direction: column;
20449
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20450
+ font-family: 'Roboto', Arial, sans-serif;
20451
+ ">
20452
+ <!-- Header - MyIO Premium Style -->
20453
+ <div style="
20454
+ padding: 4px 8px; display: flex; align-items: center; justify-content: space-between;
20455
+ background: #3e1a7d; color: white; border-radius: ${isMaximized ? "0" : "10px 10px 0 0"};
20456
+ min-height: 20px;
20457
+ ">
20458
+ <h2 style="margin: 6px; font-size: 18px; font-weight: 600; color: white; line-height: 2;">
20459
+ \u{1F321}\uFE0F Compara\xE7\xE3o de Temperatura - ${state.devices.length} sensores
20460
+ </h2>
20461
+ <div style="display: flex; gap: 4px; align-items: center;">
20462
+ <!-- Theme Toggle -->
20463
+ <button id="${modalId}-theme-toggle" title="Alternar tema" style="
20464
+ background: none; border: none; font-size: 16px; cursor: pointer;
20465
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
20466
+ transition: background-color 0.2s;
20467
+ ">${state.theme === "dark" ? "\u2600\uFE0F" : "\u{1F319}"}</button>
20468
+ <!-- Maximize Button -->
20469
+ <button id="${modalId}-maximize" title="${isMaximized ? "Restaurar" : "Maximizar"}" style="
20470
+ background: none; border: none; font-size: 16px; cursor: pointer;
20471
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
20472
+ transition: background-color 0.2s;
20473
+ ">${isMaximized ? "\u{1F5D7}" : "\u{1F5D6}"}</button>
20474
+ <!-- Close Button -->
20475
+ <button id="${modalId}-close" title="Fechar" style="
20476
+ background: none; border: none; font-size: 20px; cursor: pointer;
20477
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
20478
+ transition: background-color 0.2s;
20479
+ ">\xD7</button>
20480
+ </div>
20481
+ </div>
20482
+
20483
+ <!-- Body -->
20484
+ <div style="flex: 1; overflow-y: auto; padding: 16px;">
20485
+
20486
+ <!-- Controls Row -->
20487
+ <div style="
20488
+ display: flex; gap: 16px; flex-wrap: wrap; align-items: flex-end;
20489
+ margin-bottom: 16px; padding: 16px;
20490
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#f7f7f7"};
20491
+ border-radius: 6px; border: 1px solid ${colors.border};
20492
+ ">
20493
+ <!-- Granularity Select -->
20494
+ <div>
20495
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
20496
+ Granularidade
20497
+ </label>
20498
+ <select id="${modalId}-granularity" style="
20499
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
20500
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
20501
+ cursor: pointer; min-width: 130px;
20502
+ ">
20503
+ <option value="hour" ${state.granularity === "hour" ? "selected" : ""}>Hora (30 min)</option>
20504
+ <option value="day" ${state.granularity === "day" ? "selected" : ""}>Dia (m\xE9dia)</option>
20505
+ </select>
20506
+ </div>
20507
+ <!-- Day Period Filter (Multiselect) -->
20508
+ <div style="position: relative;">
20509
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
20510
+ Per\xEDodos do Dia
20511
+ </label>
20512
+ <button id="${modalId}-period-btn" type="button" style="
20513
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
20514
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
20515
+ cursor: pointer; min-width: 180px; text-align: left;
20516
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
20517
+ ">
20518
+ <span>${getSelectedPeriodsLabel(state.selectedPeriods)}</span>
20519
+ <span style="font-size: 10px;">\u25BC</span>
20520
+ </button>
20521
+ <div id="${modalId}-period-dropdown" style="
20522
+ display: none; position: absolute; top: 100%; left: 0; z-index: 1000;
20523
+ background: ${colors.surface}; border: 1px solid ${colors.border};
20524
+ border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20525
+ min-width: 200px; margin-top: 4px; padding: 8px 0;
20526
+ ">
20527
+ ${DAY_PERIODS.map((period) => `
20528
+ <label style="
20529
+ display: flex; align-items: center; gap: 8px; padding: 8px 12px;
20530
+ cursor: pointer; font-size: 13px; color: ${colors.text};
20531
+ " onmouseover="this.style.background='${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"}'"
20532
+ onmouseout="this.style.background='transparent'">
20533
+ <input type="checkbox"
20534
+ name="${modalId}-period"
20535
+ value="${period.id}"
20536
+ ${state.selectedPeriods.includes(period.id) ? "checked" : ""}
20537
+ style="width: 16px; height: 16px; cursor: pointer; accent-color: #3e1a7d;">
20538
+ ${period.label}
20539
+ </label>
20540
+ `).join("")}
20541
+ <div style="border-top: 1px solid ${colors.border}; margin-top: 8px; padding-top: 8px;">
20542
+ <button id="${modalId}-period-select-all" type="button" style="
20543
+ width: calc(100% - 16px); margin: 0 8px 4px; padding: 6px;
20544
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"};
20545
+ border: none; border-radius: 4px; cursor: pointer;
20546
+ font-size: 12px; color: ${colors.text};
20547
+ ">Selecionar Todos</button>
20548
+ <button id="${modalId}-period-clear" type="button" style="
20549
+ width: calc(100% - 16px); margin: 0 8px; padding: 6px;
20550
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"};
20551
+ border: none; border-radius: 4px; cursor: pointer;
20552
+ font-size: 12px; color: ${colors.text};
20553
+ ">Limpar Sele\xE7\xE3o</button>
20554
+ </div>
20555
+ </div>
20556
+ </div>
20557
+ <!-- Date Range Picker -->
20558
+ <div style="flex: 1; min-width: 220px;">
20559
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
20560
+ Per\xEDodo
20561
+ </label>
20562
+ <input type="text" id="${modalId}-date-range" readonly placeholder="Selecione o per\xEDodo..." style="
20563
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
20564
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
20565
+ width: 100%; cursor: pointer; box-sizing: border-box;
20566
+ "/>
20567
+ </div>
20568
+ <!-- Query Button -->
20569
+ <button id="${modalId}-query" style="
20570
+ background: #3e1a7d; color: white; border: none;
20571
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
20572
+ font-size: 14px; font-weight: 500; height: 38px;
20573
+ display: flex; align-items: center; gap: 8px;
20574
+ font-family: 'Roboto', Arial, sans-serif;
20575
+ " ${state.isLoading ? "disabled" : ""}>
20576
+ ${state.isLoading ? '<span style="animation: spin 1s linear infinite; display: inline-block;">\u21BB</span> Carregando...' : "Carregar"}
20577
+ </button>
20578
+ </div>
20579
+
20580
+ <!-- Legend -->
20581
+ <div style="
20582
+ display: flex; flex-wrap: wrap; gap: 10px;
20583
+ margin-bottom: 20px;
20584
+ ">
20585
+ ${legendHTML}
20586
+ </div>
20587
+
20588
+ <!-- Chart Container -->
20589
+ <div style="margin-bottom: 24px;">
20590
+ <div id="${modalId}-chart" style="
20591
+ height: 380px;
20592
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.03)" : "#fafafa"};
20593
+ border-radius: 14px; display: flex; justify-content: center; align-items: center;
20594
+ border: 1px solid ${colors.border}; position: relative;
20595
+ ">
20596
+ ${state.isLoading ? `<div style="text-align: center; color: ${colors.textMuted};">
20597
+ <div style="animation: spin 1s linear infinite; font-size: 36px; margin-bottom: 12px;">\u21BB</div>
20598
+ <div style="font-size: 15px;">Carregando dados de ${state.devices.length} sensores...</div>
20599
+ </div>` : state.deviceData.every((dd) => dd.data.length === 0) ? `<div style="text-align: center; color: ${colors.textMuted};">
20600
+ <div style="font-size: 48px; margin-bottom: 12px;">\u{1F4ED}</div>
20601
+ <div style="font-size: 16px;">Sem dados para o per\xEDodo selecionado</div>
20602
+ </div>` : `<canvas id="${modalId}-canvas" style="width: 100%; height: 100%;"></canvas>`}
20603
+ </div>
20604
+ </div>
20605
+
20606
+ <!-- Stats Cards -->
20607
+ <div style="
20608
+ display: flex; flex-wrap: wrap; gap: 12px;
20609
+ margin-bottom: 24px;
20610
+ ">
20611
+ ${statsHTML}
20612
+ </div>
20613
+
20614
+ <!-- Actions -->
20615
+ <div style="display: flex; justify-content: flex-end; gap: 12px;">
20616
+ <button id="${modalId}-export" style="
20617
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f7f7f7"};
20618
+ color: ${colors.text}; border: 1px solid ${colors.border};
20619
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
20620
+ font-size: 14px; display: flex; align-items: center; gap: 8px;
20621
+ font-family: 'Roboto', Arial, sans-serif;
20622
+ " ${state.deviceData.every((dd) => dd.data.length === 0) ? "disabled" : ""}>
20623
+ \u{1F4E5} Exportar CSV
20624
+ </button>
20625
+ <button id="${modalId}-close-btn" style="
20626
+ background: #3e1a7d; color: white; border: none;
20627
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
20628
+ font-size: 14px; font-weight: 500;
20629
+ font-family: 'Roboto', Arial, sans-serif;
20630
+ ">
20631
+ Fechar
20632
+ </button>
20633
+ </div>
20634
+ </div><!-- End Body -->
20635
+ </div>
20636
+ </div>
20637
+ <style>
20638
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
20639
+ #${modalId} select:focus, #${modalId} input:focus {
20640
+ outline: 2px solid #3e1a7d;
20641
+ outline-offset: 2px;
20642
+ }
20643
+ #${modalId} button:hover:not(:disabled) {
20644
+ opacity: 0.9;
20645
+ }
20646
+ #${modalId} button:disabled {
20647
+ opacity: 0.5;
20648
+ cursor: not-allowed;
20649
+ }
20650
+ #${modalId} .myio-temp-comparison-content > div:first-child button:hover {
20651
+ background: rgba(255, 255, 255, 0.1) !important;
20652
+ color: white !important;
20653
+ }
20654
+ </style>
20655
+ `;
20656
+ }
20657
+ function drawComparisonChart(modalId, state) {
20658
+ const chartContainer = document.getElementById(`${modalId}-chart`);
20659
+ const canvas = document.getElementById(`${modalId}-canvas`);
20660
+ if (!chartContainer || !canvas) return;
20661
+ const hasData = state.deviceData.some((dd) => dd.data.length > 0);
20662
+ if (!hasData) return;
20663
+ const ctx = canvas.getContext("2d");
20664
+ if (!ctx) return;
20665
+ const colors = getThemeColors(state.theme);
20666
+ const width = chartContainer.clientWidth - 2;
20667
+ const height = 380;
20668
+ canvas.width = width;
20669
+ canvas.height = height;
20670
+ const paddingLeft = 65;
20671
+ const paddingRight = 25;
20672
+ const paddingTop = 25;
20673
+ const paddingBottom = 55;
20674
+ ctx.clearRect(0, 0, width, height);
20675
+ const processedData = [];
20676
+ state.deviceData.forEach((dd) => {
20677
+ if (dd.data.length === 0) return;
20678
+ const filteredData = filterByDayPeriods(dd.data, state.selectedPeriods);
20679
+ if (filteredData.length === 0) return;
20680
+ let points;
20681
+ if (state.granularity === "hour") {
20682
+ const interpolated = interpolateTemperature(filteredData, {
20683
+ intervalMinutes: 30,
20684
+ startTs: state.startTs,
20685
+ endTs: state.endTs,
20686
+ clampRange: state.clampRange
20687
+ });
20688
+ const filteredInterpolated = filterByDayPeriods(interpolated, state.selectedPeriods);
20689
+ points = filteredInterpolated.map((item) => ({
20690
+ x: item.ts,
20691
+ y: Number(item.value),
20692
+ screenX: 0,
20693
+ screenY: 0,
20694
+ deviceLabel: dd.device.label,
20695
+ deviceColor: dd.color
20696
+ }));
20697
+ } else {
20698
+ const daily = aggregateByDay(filteredData, state.clampRange);
20699
+ points = daily.map((item) => ({
20700
+ x: item.dateTs,
20701
+ y: item.avg,
20702
+ screenX: 0,
20703
+ screenY: 0,
20704
+ deviceLabel: dd.device.label,
20705
+ deviceColor: dd.color
20706
+ }));
20707
+ }
20708
+ if (points.length > 0) {
20709
+ processedData.push({ device: dd, points });
20710
+ }
20711
+ });
20712
+ if (processedData.length === 0) {
20713
+ ctx.fillStyle = colors.textMuted;
20714
+ ctx.font = "14px Roboto, Arial, sans-serif";
20715
+ ctx.textAlign = "center";
20716
+ ctx.fillText("Nenhum dado para os per\xEDodos selecionados", width / 2, height / 2);
20717
+ return;
20718
+ }
20719
+ const isPeriodsFiltered = state.selectedPeriods.length < 4 && state.selectedPeriods.length > 0;
20720
+ let globalMinY = Infinity;
20721
+ let globalMaxY = -Infinity;
20722
+ processedData.forEach(({ points }) => {
20723
+ points.forEach((point) => {
20724
+ if (point.y < globalMinY) globalMinY = point.y;
20725
+ if (point.y > globalMaxY) globalMaxY = point.y;
20726
+ });
20727
+ });
20728
+ globalMinY = Math.floor(globalMinY) - 1;
20729
+ globalMaxY = Math.ceil(globalMaxY) + 1;
20730
+ const chartWidth = width - paddingLeft - paddingRight;
20731
+ const chartHeight = height - paddingTop - paddingBottom;
20732
+ const scaleY = chartHeight / (globalMaxY - globalMinY || 1);
20733
+ if (isPeriodsFiltered) {
20734
+ const maxPoints = Math.max(...processedData.map(({ points }) => points.length));
20735
+ const pointSpacing = chartWidth / Math.max(1, maxPoints - 1);
20736
+ processedData.forEach(({ points }) => {
20737
+ points.forEach((point, index) => {
20738
+ point.screenX = paddingLeft + index * pointSpacing;
20739
+ point.screenY = height - paddingBottom - (point.y - globalMinY) * scaleY;
20740
+ });
20741
+ });
20742
+ } else {
20743
+ let globalMinX = Infinity;
20744
+ let globalMaxX = -Infinity;
20745
+ processedData.forEach(({ points }) => {
20746
+ points.forEach((point) => {
20747
+ if (point.x < globalMinX) globalMinX = point.x;
20748
+ if (point.x > globalMaxX) globalMaxX = point.x;
20749
+ });
20750
+ });
20751
+ const timeRange = globalMaxX - globalMinX || 1;
20752
+ const scaleX = chartWidth / timeRange;
20753
+ processedData.forEach(({ points }) => {
20754
+ points.forEach((point) => {
20755
+ point.screenX = paddingLeft + (point.x - globalMinX) * scaleX;
20756
+ point.screenY = height - paddingBottom - (point.y - globalMinY) * scaleY;
20757
+ });
20758
+ });
20759
+ }
20760
+ ctx.strokeStyle = colors.chartGrid;
20761
+ ctx.lineWidth = 1;
20762
+ for (let i = 0; i <= 5; i++) {
20763
+ const y = paddingTop + chartHeight * i / 5;
20764
+ ctx.beginPath();
20765
+ ctx.moveTo(paddingLeft, y);
20766
+ ctx.lineTo(width - paddingRight, y);
20767
+ ctx.stroke();
20768
+ }
20769
+ processedData.forEach(({ device, points }) => {
20770
+ ctx.strokeStyle = device.color;
20771
+ ctx.lineWidth = 2.5;
20772
+ ctx.beginPath();
20773
+ points.forEach((point, i) => {
20774
+ if (i === 0) ctx.moveTo(point.screenX, point.screenY);
20775
+ else ctx.lineTo(point.screenX, point.screenY);
20776
+ });
20777
+ ctx.stroke();
20778
+ ctx.fillStyle = device.color;
20779
+ points.forEach((point) => {
20780
+ ctx.beginPath();
20781
+ ctx.arc(point.screenX, point.screenY, 4, 0, Math.PI * 2);
20782
+ ctx.fill();
20783
+ });
20784
+ });
20785
+ ctx.fillStyle = colors.textMuted;
20786
+ ctx.font = "12px system-ui, sans-serif";
20787
+ ctx.textAlign = "right";
20788
+ for (let i = 0; i <= 5; i++) {
20789
+ const val = globalMinY + (globalMaxY - globalMinY) * (5 - i) / 5;
20790
+ const y = paddingTop + chartHeight * i / 5;
20791
+ ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 10, y + 4);
20792
+ }
20793
+ ctx.textAlign = "center";
20794
+ const xAxisPoints = processedData[0]?.points || [];
20795
+ const numLabels = Math.min(8, xAxisPoints.length);
20796
+ const labelInterval = Math.max(1, Math.floor(xAxisPoints.length / numLabels));
20797
+ for (let i = 0; i < xAxisPoints.length; i += labelInterval) {
20798
+ const point = xAxisPoints[i];
20799
+ const date = new Date(point.x);
20800
+ let label;
20801
+ if (state.granularity === "hour") {
20802
+ label = date.toLocaleTimeString(state.locale, { hour: "2-digit", minute: "2-digit" });
20803
+ } else {
20804
+ label = date.toLocaleDateString(state.locale, { day: "2-digit", month: "2-digit" });
20805
+ }
20806
+ ctx.strokeStyle = colors.chartGrid;
20807
+ ctx.lineWidth = 1;
20808
+ ctx.beginPath();
20809
+ ctx.moveTo(point.screenX, paddingTop);
20810
+ ctx.lineTo(point.screenX, height - paddingBottom);
20811
+ ctx.stroke();
20812
+ ctx.fillStyle = colors.textMuted;
20813
+ ctx.fillText(label, point.screenX, height - paddingBottom + 18);
20814
+ }
20815
+ ctx.strokeStyle = colors.border;
20816
+ ctx.lineWidth = 1;
20817
+ ctx.beginPath();
20818
+ ctx.moveTo(paddingLeft, paddingTop);
20819
+ ctx.lineTo(paddingLeft, height - paddingBottom);
20820
+ ctx.lineTo(width - paddingRight, height - paddingBottom);
20821
+ ctx.stroke();
20822
+ const allChartPoints = processedData.flatMap((pd) => pd.points);
20823
+ setupComparisonChartTooltip(canvas, chartContainer, allChartPoints, state, colors);
20824
+ }
20825
+ function setupComparisonChartTooltip(canvas, container, chartData, state, colors) {
20826
+ const existingTooltip = container.querySelector(".myio-chart-tooltip");
20827
+ if (existingTooltip) existingTooltip.remove();
20828
+ const tooltip = document.createElement("div");
20829
+ tooltip.className = "myio-chart-tooltip";
20830
+ tooltip.style.cssText = `
20831
+ position: absolute;
20832
+ background: ${state.theme === "dark" ? "rgba(30, 30, 40, 0.95)" : "rgba(255, 255, 255, 0.98)"};
20833
+ border: 1px solid ${colors.border};
20834
+ border-radius: 8px;
20835
+ padding: 10px 14px;
20836
+ font-size: 13px;
20837
+ color: ${colors.text};
20838
+ pointer-events: none;
20839
+ opacity: 0;
20840
+ transition: opacity 0.15s;
20841
+ z-index: 1000;
20842
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20843
+ min-width: 160px;
20844
+ `;
20845
+ container.appendChild(tooltip);
20846
+ const findNearestPoint = (mouseX, mouseY) => {
20847
+ const threshold = 20;
20848
+ let nearest = null;
20849
+ let minDist = Infinity;
20850
+ for (const point of chartData) {
20851
+ const dist = Math.sqrt(
20852
+ Math.pow(mouseX - point.screenX, 2) + Math.pow(mouseY - point.screenY, 2)
20853
+ );
20854
+ if (dist < minDist && dist < threshold) {
20855
+ minDist = dist;
20856
+ nearest = point;
20857
+ }
20858
+ }
20859
+ return nearest;
20860
+ };
20861
+ canvas.addEventListener("mousemove", (e) => {
20862
+ const rect = canvas.getBoundingClientRect();
20863
+ const mouseX = e.clientX - rect.left;
20864
+ const mouseY = e.clientY - rect.top;
20865
+ const point = findNearestPoint(mouseX, mouseY);
20866
+ if (point) {
20867
+ const date = new Date(point.x);
20868
+ let dateStr;
20869
+ if (state.granularity === "hour") {
20870
+ dateStr = date.toLocaleDateString(state.locale, {
20871
+ day: "2-digit",
20872
+ month: "2-digit",
20873
+ year: "numeric"
20874
+ }) + " " + date.toLocaleTimeString(state.locale, {
20875
+ hour: "2-digit",
20876
+ minute: "2-digit"
20877
+ });
20878
+ } else {
20879
+ dateStr = date.toLocaleDateString(state.locale, {
20880
+ day: "2-digit",
20881
+ month: "2-digit",
20882
+ year: "numeric"
20883
+ });
20884
+ }
20885
+ tooltip.innerHTML = `
20886
+ <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
20887
+ <span style="width: 10px; height: 10px; border-radius: 50%; background: ${point.deviceColor};"></span>
20888
+ <span style="font-weight: 600;">${point.deviceLabel}</span>
20889
+ </div>
20890
+ <div style="font-weight: 600; font-size: 16px; color: ${point.deviceColor}; margin-bottom: 4px;">
20891
+ ${formatTemperature(point.y)}
20892
+ </div>
20893
+ <div style="font-size: 11px; color: ${colors.textMuted};">
20894
+ \u{1F4C5} ${dateStr}
20895
+ </div>
20896
+ `;
20897
+ let tooltipX = point.screenX + 15;
20898
+ let tooltipY = point.screenY - 15;
20899
+ const tooltipRect = tooltip.getBoundingClientRect();
20900
+ const containerRect = container.getBoundingClientRect();
20901
+ if (tooltipX + tooltipRect.width > containerRect.width - 10) {
20902
+ tooltipX = point.screenX - tooltipRect.width - 15;
20903
+ }
20904
+ if (tooltipY < 10) {
20905
+ tooltipY = point.screenY + 15;
20906
+ }
20907
+ tooltip.style.left = `${tooltipX}px`;
20908
+ tooltip.style.top = `${tooltipY}px`;
20909
+ tooltip.style.opacity = "1";
20910
+ canvas.style.cursor = "pointer";
20911
+ } else {
20912
+ tooltip.style.opacity = "0";
20913
+ canvas.style.cursor = "default";
20914
+ }
20915
+ });
20916
+ canvas.addEventListener("mouseleave", () => {
20917
+ tooltip.style.opacity = "0";
20918
+ canvas.style.cursor = "default";
20919
+ });
20920
+ }
20921
+ async function setupEventListeners2(container, state, modalId, onClose) {
20922
+ const closeModal = () => {
20923
+ container.remove();
20924
+ onClose?.();
20925
+ };
20926
+ container.querySelector(".myio-temp-comparison-overlay")?.addEventListener("click", (e) => {
20927
+ if (e.target === e.currentTarget) closeModal();
20928
+ });
20929
+ document.getElementById(`${modalId}-close`)?.addEventListener("click", closeModal);
20930
+ document.getElementById(`${modalId}-close-btn`)?.addEventListener("click", closeModal);
20931
+ const dateRangeInput = document.getElementById(`${modalId}-date-range`);
20932
+ if (dateRangeInput && !state.dateRangePicker) {
20933
+ try {
20934
+ state.dateRangePicker = await createDateRangePicker2(dateRangeInput, {
20935
+ presetStart: new Date(state.startTs).toISOString(),
20936
+ presetEnd: new Date(state.endTs).toISOString(),
20937
+ includeTime: true,
20938
+ timePrecision: "minute",
20939
+ maxRangeDays: 90,
20940
+ locale: state.locale,
20941
+ parentEl: container.querySelector(".myio-temp-comparison-content"),
20942
+ onApply: (result) => {
20943
+ state.startTs = new Date(result.startISO).getTime();
20944
+ state.endTs = new Date(result.endISO).getTime();
20945
+ console.log("[TemperatureComparisonModal] Date range applied:", result);
20946
+ }
20947
+ });
20948
+ } catch (error) {
20949
+ console.warn("[TemperatureComparisonModal] DateRangePicker initialization failed:", error);
20950
+ }
20951
+ }
20952
+ document.getElementById(`${modalId}-theme-toggle`)?.addEventListener("click", async () => {
20953
+ state.theme = state.theme === "dark" ? "light" : "dark";
20954
+ localStorage.setItem("myio-temp-comparison-theme", state.theme);
20955
+ state.dateRangePicker = null;
20956
+ renderModal2(container, state, modalId);
20957
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
20958
+ drawComparisonChart(modalId, state);
20959
+ }
20960
+ await setupEventListeners2(container, state, modalId, onClose);
20961
+ });
20962
+ document.getElementById(`${modalId}-maximize`)?.addEventListener("click", async () => {
20963
+ container.__isMaximized = !container.__isMaximized;
20964
+ state.dateRangePicker = null;
20965
+ renderModal2(container, state, modalId);
20966
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
20967
+ drawComparisonChart(modalId, state);
20968
+ }
20969
+ await setupEventListeners2(container, state, modalId, onClose);
20970
+ });
20971
+ const periodBtn = document.getElementById(`${modalId}-period-btn`);
20972
+ const periodDropdown = document.getElementById(`${modalId}-period-dropdown`);
20973
+ periodBtn?.addEventListener("click", (e) => {
20974
+ e.stopPropagation();
20975
+ if (periodDropdown) {
20976
+ periodDropdown.style.display = periodDropdown.style.display === "none" ? "block" : "none";
20977
+ }
20978
+ });
20979
+ document.addEventListener("click", (e) => {
20980
+ if (periodDropdown && !periodDropdown.contains(e.target) && e.target !== periodBtn) {
20981
+ periodDropdown.style.display = "none";
20982
+ }
20983
+ });
20984
+ const periodCheckboxes = document.querySelectorAll(`input[name="${modalId}-period"]`);
20985
+ periodCheckboxes.forEach((checkbox) => {
20986
+ checkbox.addEventListener("change", () => {
20987
+ const checked = Array.from(periodCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
20988
+ state.selectedPeriods = checked;
20989
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20990
+ if (btnLabel) {
20991
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20992
+ }
20993
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
20994
+ drawComparisonChart(modalId, state);
20995
+ }
20996
+ });
20997
+ });
20998
+ document.getElementById(`${modalId}-period-select-all`)?.addEventListener("click", () => {
20999
+ periodCheckboxes.forEach((cb) => {
21000
+ cb.checked = true;
21001
+ });
21002
+ state.selectedPeriods = ["madrugada", "manha", "tarde", "noite"];
21003
+ const btnLabel = periodBtn?.querySelector("span:first-child");
21004
+ if (btnLabel) {
21005
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
21006
+ }
21007
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21008
+ drawComparisonChart(modalId, state);
21009
+ }
21010
+ });
21011
+ document.getElementById(`${modalId}-period-clear`)?.addEventListener("click", () => {
21012
+ periodCheckboxes.forEach((cb) => {
21013
+ cb.checked = false;
21014
+ });
21015
+ state.selectedPeriods = [];
21016
+ const btnLabel = periodBtn?.querySelector("span:first-child");
21017
+ if (btnLabel) {
21018
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
21019
+ }
21020
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21021
+ drawComparisonChart(modalId, state);
21022
+ }
21023
+ });
21024
+ document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
21025
+ state.granularity = e.target.value;
21026
+ localStorage.setItem("myio-temp-comparison-granularity", state.granularity);
21027
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21028
+ drawComparisonChart(modalId, state);
21029
+ }
21030
+ });
21031
+ document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
21032
+ if (state.startTs >= state.endTs) {
21033
+ alert("Por favor, selecione um per\xEDodo v\xE1lido");
21034
+ return;
21035
+ }
21036
+ state.isLoading = true;
21037
+ state.dateRangePicker = null;
21038
+ renderModal2(container, state, modalId);
21039
+ await fetchAllDevicesData(state);
21040
+ renderModal2(container, state, modalId);
21041
+ drawComparisonChart(modalId, state);
21042
+ await setupEventListeners2(container, state, modalId, onClose);
21043
+ });
21044
+ document.getElementById(`${modalId}-export`)?.addEventListener("click", () => {
21045
+ if (state.deviceData.every((dd) => dd.data.length === 0)) return;
21046
+ exportComparisonCSV(state);
21047
+ });
21048
+ }
21049
+ function exportComparisonCSV(state) {
21050
+ const startDateStr = new Date(state.startTs).toLocaleDateString(state.locale).replace(/\//g, "-");
21051
+ const endDateStr = new Date(state.endTs).toLocaleDateString(state.locale).replace(/\//g, "-");
21052
+ const BOM = "\uFEFF";
21053
+ let csvContent = BOM;
21054
+ csvContent += `Compara\xE7\xE3o de Temperatura
21055
+ `;
21056
+ csvContent += `Per\xEDodo: ${startDateStr} at\xE9 ${endDateStr}
21057
+ `;
21058
+ csvContent += `Sensores: ${state.devices.map((d) => d.label).join(", ")}
21059
+ `;
21060
+ csvContent += "\n";
21061
+ csvContent += "Estat\xEDsticas por Sensor:\n";
21062
+ csvContent += "Sensor,M\xE9dia (\xB0C),Min (\xB0C),Max (\xB0C),Leituras\n";
21063
+ state.deviceData.forEach((dd) => {
21064
+ csvContent += `"${dd.device.label}",${dd.stats.avg.toFixed(2)},${dd.stats.min.toFixed(2)},${dd.stats.max.toFixed(2)},${dd.stats.count}
21065
+ `;
21066
+ });
21067
+ csvContent += "\n";
21068
+ csvContent += "Dados Detalhados:\n";
21069
+ csvContent += "Data/Hora,Sensor,Temperatura (\xB0C)\n";
21070
+ state.deviceData.forEach((dd) => {
21071
+ dd.data.forEach((item) => {
21072
+ const date = new Date(item.ts).toLocaleString(state.locale);
21073
+ const temp = Number(item.value).toFixed(2);
21074
+ csvContent += `"${date}","${dd.device.label}",${temp}
21075
+ `;
21076
+ });
21077
+ });
21078
+ const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
21079
+ const url = URL.createObjectURL(blob);
21080
+ const link = document.createElement("a");
21081
+ link.href = url;
21082
+ link.download = `comparacao_temperatura_${startDateStr}_${endDateStr}.csv`;
21083
+ document.body.appendChild(link);
21084
+ link.click();
21085
+ document.body.removeChild(link);
21086
+ URL.revokeObjectURL(url);
21087
+ }
21088
+
21089
+ exports.CHART_COLORS = CHART_COLORS;
19370
21090
  exports.ConnectionStatusType = ConnectionStatusType;
21091
+ exports.DEFAULT_CLAMP_RANGE = DEFAULT_CLAMP_RANGE;
19371
21092
  exports.DeviceStatusType = DeviceStatusType;
19372
21093
  exports.MyIOChartModal = MyIOChartModal;
19373
21094
  exports.MyIODraggableCard = MyIODraggableCard;
@@ -19375,6 +21096,7 @@ ${rangeText}`;
19375
21096
  exports.MyIOToast = MyIOToast;
19376
21097
  exports.addDetectionContext = addDetectionContext;
19377
21098
  exports.addNamespace = addNamespace;
21099
+ exports.aggregateByDay = aggregateByDay;
19378
21100
  exports.averageByDay = averageByDay;
19379
21101
  exports.buildListItemsThingsboardByUniqueDatasource = buildListItemsThingsboardByUniqueDatasource;
19380
21102
  exports.buildMyioIngestionAuth = buildMyioIngestionAuth;
@@ -19383,6 +21105,8 @@ ${rangeText}`;
19383
21105
  exports.calcDeltaPercent = calcDeltaPercent;
19384
21106
  exports.calculateDeviceStatus = calculateDeviceStatus;
19385
21107
  exports.calculateDeviceStatusWithRanges = calculateDeviceStatusWithRanges;
21108
+ exports.calculateStats = calculateStats;
21109
+ exports.clampTemperature = clampTemperature;
19386
21110
  exports.classify = classify;
19387
21111
  exports.classifyWaterLabel = classifyWaterLabel;
19388
21112
  exports.classifyWaterLabels = classifyWaterLabels;
@@ -19395,9 +21119,11 @@ ${rangeText}`;
19395
21119
  exports.detectDeviceType = detectDeviceType;
19396
21120
  exports.determineInterval = determineInterval;
19397
21121
  exports.deviceStatusIcons = deviceStatusIcons;
21122
+ exports.exportTemperatureCSV = exportTemperatureCSV;
19398
21123
  exports.exportToCSV = exportToCSV;
19399
21124
  exports.exportToCSVAll = exportToCSVAll;
19400
21125
  exports.extractMyIOCredentials = extractMyIOCredentials;
21126
+ exports.fetchTemperatureData = fetchTemperatureData;
19401
21127
  exports.fetchThingsboardCustomerAttrsFromStorage = fetchThingsboardCustomerAttrsFromStorage;
19402
21128
  exports.fetchThingsboardCustomerServerScopeAttrs = fetchThingsboardCustomerServerScopeAttrs;
19403
21129
  exports.findValue = findValue;
@@ -19411,6 +21137,7 @@ ${rangeText}`;
19411
21137
  exports.formatEnergy = formatEnergy;
19412
21138
  exports.formatNumberReadable = formatNumberReadable;
19413
21139
  exports.formatTankHeadFromCm = formatTankHeadFromCm;
21140
+ exports.formatTemperature = formatTemperature;
19414
21141
  exports.formatWaterByGroup = formatWaterByGroup;
19415
21142
  exports.formatWaterVolumeM3 = formatWaterVolumeM3;
19416
21143
  exports.getAuthCacheStats = getAuthCacheStats;
@@ -19425,6 +21152,7 @@ ${rangeText}`;
19425
21152
  exports.getValueByDatakeyLegacy = getValueByDatakeyLegacy;
19426
21153
  exports.getWaterCategories = getWaterCategories;
19427
21154
  exports.groupByDay = groupByDay;
21155
+ exports.interpolateTemperature = interpolateTemperature;
19428
21156
  exports.isDeviceOffline = isDeviceOffline;
19429
21157
  exports.isValidConnectionStatus = isValidConnectionStatus;
19430
21158
  exports.isValidDeviceStatus = isValidDeviceStatus;
@@ -19442,6 +21170,8 @@ ${rangeText}`;
19442
21170
  exports.openDemandModal = openDemandModal;
19443
21171
  exports.openGoalsPanel = openGoalsPanel;
19444
21172
  exports.openRealTimeTelemetryModal = openRealTimeTelemetryModal;
21173
+ exports.openTemperatureComparisonModal = openTemperatureComparisonModal;
21174
+ exports.openTemperatureModal = openTemperatureModal;
19445
21175
  exports.parseInputDateToDate = parseInputDateToDate;
19446
21176
  exports.renderCardComponent = renderCardComponent;
19447
21177
  exports.renderCardComponentEnhanced = renderCardComponent2;