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