myio-js-library 0.1.140 → 0.1.142

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
+ renderModal4();
18152
18152
  } else {
18153
- renderModal();
18153
+ renderModal4();
18154
18154
  loadGoalsData();
18155
18155
  }
18156
18156
  }
18157
- function renderModal() {
18157
+ function renderModal4() {
18158
18158
  const existing = document.getElementById("myio-goals-panel-modal");
18159
18159
  if (existing) {
18160
18160
  existing.remove();
@@ -19542,8 +19542,2332 @@ 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 dataMin = Math.min(...values);
20158
+ const dataMax = Math.max(...values);
20159
+ const thresholdMin = state.temperatureMin !== null ? state.temperatureMin : dataMin;
20160
+ const thresholdMax = state.temperatureMax !== null ? state.temperatureMax : dataMax;
20161
+ const minY = Math.min(dataMin, thresholdMin) - 1;
20162
+ const maxY = Math.max(dataMax, thresholdMax) + 1;
20163
+ const chartWidth = width - paddingLeft - paddingRight;
20164
+ const chartHeight = height - paddingTop - paddingBottom;
20165
+ const scaleY = chartHeight / (maxY - minY || 1);
20166
+ if (isPeriodsFiltered) {
20167
+ const pointSpacing = chartWidth / Math.max(1, chartData.length - 1);
20168
+ chartData.forEach((point, index) => {
20169
+ point.screenX = paddingLeft + index * pointSpacing;
20170
+ point.screenY = height - paddingBottom - (point.y - minY) * scaleY;
20171
+ });
20172
+ } else {
20173
+ const minX = chartData[0].x;
20174
+ const maxX = chartData[chartData.length - 1].x;
20175
+ const timeRange = maxX - minX || 1;
20176
+ const scaleX = chartWidth / timeRange;
20177
+ chartData.forEach((point) => {
20178
+ point.screenX = paddingLeft + (point.x - minX) * scaleX;
20179
+ point.screenY = height - paddingBottom - (point.y - minY) * scaleY;
20180
+ });
20181
+ }
20182
+ ctx.clearRect(0, 0, width, height);
20183
+ ctx.strokeStyle = colors.chartGrid;
20184
+ ctx.lineWidth = 1;
20185
+ for (let i = 0; i <= 4; i++) {
20186
+ const y = paddingTop + chartHeight * i / 4;
20187
+ ctx.beginPath();
20188
+ ctx.moveTo(paddingLeft, y);
20189
+ ctx.lineTo(width - paddingRight, y);
20190
+ ctx.stroke();
20191
+ }
20192
+ if (state.temperatureMin !== null && state.temperatureMax !== null) {
20193
+ const rangeMinY = height - paddingBottom - (state.temperatureMin - minY) * scaleY;
20194
+ const rangeMaxY = height - paddingBottom - (state.temperatureMax - minY) * scaleY;
20195
+ ctx.fillStyle = "rgba(76, 175, 80, 0.1)";
20196
+ ctx.fillRect(paddingLeft, rangeMaxY, chartWidth, rangeMinY - rangeMaxY);
20197
+ ctx.strokeStyle = colors.success;
20198
+ ctx.setLineDash([5, 5]);
20199
+ ctx.beginPath();
20200
+ ctx.moveTo(paddingLeft, rangeMinY);
20201
+ ctx.lineTo(width - paddingRight, rangeMinY);
20202
+ ctx.moveTo(paddingLeft, rangeMaxY);
20203
+ ctx.lineTo(width - paddingRight, rangeMaxY);
20204
+ ctx.stroke();
20205
+ ctx.setLineDash([]);
20206
+ }
20207
+ ctx.strokeStyle = colors.chartLine;
20208
+ ctx.lineWidth = 2;
20209
+ ctx.beginPath();
20210
+ chartData.forEach((point, i) => {
20211
+ if (i === 0) ctx.moveTo(point.screenX, point.screenY);
20212
+ else ctx.lineTo(point.screenX, point.screenY);
20213
+ });
20214
+ ctx.stroke();
20215
+ ctx.fillStyle = colors.chartLine;
20216
+ chartData.forEach((point) => {
20217
+ ctx.beginPath();
20218
+ ctx.arc(point.screenX, point.screenY, 4, 0, Math.PI * 2);
20219
+ ctx.fill();
20220
+ });
20221
+ ctx.fillStyle = colors.textMuted;
20222
+ ctx.font = "11px system-ui, sans-serif";
20223
+ ctx.textAlign = "right";
20224
+ for (let i = 0; i <= 4; i++) {
20225
+ const val = minY + (maxY - minY) * (4 - i) / 4;
20226
+ const y = paddingTop + chartHeight * i / 4;
20227
+ ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 8, y + 4);
20228
+ }
20229
+ ctx.textAlign = "center";
20230
+ const numLabels = Math.min(8, chartData.length);
20231
+ const labelInterval = Math.max(1, Math.floor(chartData.length / numLabels));
20232
+ for (let i = 0; i < chartData.length; i += labelInterval) {
20233
+ const point = chartData[i];
20234
+ const date = new Date(point.x);
20235
+ let label;
20236
+ if (state.granularity === "hour") {
20237
+ label = date.toLocaleTimeString(state.locale, { hour: "2-digit", minute: "2-digit" });
20238
+ } else {
20239
+ label = date.toLocaleDateString(state.locale, { day: "2-digit", month: "2-digit" });
20240
+ }
20241
+ ctx.strokeStyle = colors.chartGrid;
20242
+ ctx.lineWidth = 1;
20243
+ ctx.beginPath();
20244
+ ctx.moveTo(point.screenX, paddingTop);
20245
+ ctx.lineTo(point.screenX, height - paddingBottom);
20246
+ ctx.stroke();
20247
+ ctx.fillStyle = colors.textMuted;
20248
+ ctx.fillText(label, point.screenX, height - paddingBottom + 18);
20249
+ }
20250
+ ctx.strokeStyle = colors.border;
20251
+ ctx.lineWidth = 1;
20252
+ ctx.beginPath();
20253
+ ctx.moveTo(paddingLeft, paddingTop);
20254
+ ctx.lineTo(paddingLeft, height - paddingBottom);
20255
+ ctx.lineTo(width - paddingRight, height - paddingBottom);
20256
+ ctx.stroke();
20257
+ setupChartTooltip(canvas, chartContainer, chartData, state, colors);
20258
+ }
20259
+ function setupChartTooltip(canvas, container, chartData, state, colors) {
20260
+ const existingTooltip = container.querySelector(".myio-chart-tooltip");
20261
+ if (existingTooltip) existingTooltip.remove();
20262
+ const tooltip = document.createElement("div");
20263
+ tooltip.className = "myio-chart-tooltip";
20264
+ tooltip.style.cssText = `
20265
+ position: absolute;
20266
+ background: ${state.theme === "dark" ? "rgba(30, 30, 40, 0.95)" : "rgba(255, 255, 255, 0.98)"};
20267
+ border: 1px solid ${colors.border};
20268
+ border-radius: 8px;
20269
+ padding: 10px 14px;
20270
+ font-size: 13px;
20271
+ color: ${colors.text};
20272
+ pointer-events: none;
20273
+ opacity: 0;
20274
+ transition: opacity 0.15s;
20275
+ z-index: 1000;
20276
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20277
+ min-width: 140px;
20278
+ `;
20279
+ container.appendChild(tooltip);
20280
+ const findNearestPoint = (mouseX, mouseY) => {
20281
+ const threshold = 20;
20282
+ let nearest = null;
20283
+ let minDist = Infinity;
20284
+ for (const point of chartData) {
20285
+ const dist = Math.sqrt(
20286
+ Math.pow(mouseX - point.screenX, 2) + Math.pow(mouseY - point.screenY, 2)
20287
+ );
20288
+ if (dist < minDist && dist < threshold) {
20289
+ minDist = dist;
20290
+ nearest = point;
20291
+ }
20292
+ }
20293
+ return nearest;
20294
+ };
20295
+ canvas.addEventListener("mousemove", (e) => {
20296
+ const rect = canvas.getBoundingClientRect();
20297
+ const mouseX = e.clientX - rect.left;
20298
+ const mouseY = e.clientY - rect.top;
20299
+ const point = findNearestPoint(mouseX, mouseY);
20300
+ if (point) {
20301
+ const date = new Date(point.x);
20302
+ let dateStr;
20303
+ if (state.granularity === "hour") {
20304
+ dateStr = date.toLocaleDateString(state.locale, {
20305
+ day: "2-digit",
20306
+ month: "2-digit",
20307
+ year: "numeric"
20308
+ }) + " " + date.toLocaleTimeString(state.locale, {
20309
+ hour: "2-digit",
20310
+ minute: "2-digit"
20311
+ });
20312
+ } else {
20313
+ dateStr = date.toLocaleDateString(state.locale, {
20314
+ day: "2-digit",
20315
+ month: "2-digit",
20316
+ year: "numeric"
20317
+ });
20318
+ }
20319
+ tooltip.innerHTML = `
20320
+ <div style="font-weight: 600; margin-bottom: 6px; color: ${colors.primary};">
20321
+ ${formatTemperature(point.y)}
20322
+ </div>
20323
+ <div style="font-size: 11px; color: ${colors.textMuted};">
20324
+ \u{1F4C5} ${dateStr}
20325
+ </div>
20326
+ `;
20327
+ let tooltipX = point.screenX + 15;
20328
+ let tooltipY = point.screenY - 15;
20329
+ const tooltipRect = tooltip.getBoundingClientRect();
20330
+ const containerRect = container.getBoundingClientRect();
20331
+ if (tooltipX + tooltipRect.width > containerRect.width - 10) {
20332
+ tooltipX = point.screenX - tooltipRect.width - 15;
20333
+ }
20334
+ if (tooltipY < 10) {
20335
+ tooltipY = point.screenY + 15;
20336
+ }
20337
+ tooltip.style.left = `${tooltipX}px`;
20338
+ tooltip.style.top = `${tooltipY}px`;
20339
+ tooltip.style.opacity = "1";
20340
+ canvas.style.cursor = "pointer";
20341
+ } else {
20342
+ tooltip.style.opacity = "0";
20343
+ canvas.style.cursor = "default";
20344
+ }
20345
+ });
20346
+ canvas.addEventListener("mouseleave", () => {
20347
+ tooltip.style.opacity = "0";
20348
+ canvas.style.cursor = "default";
20349
+ });
20350
+ }
20351
+ async function setupEventListeners(container, state, modalId, onClose) {
20352
+ const closeModal = () => {
20353
+ container.remove();
20354
+ onClose?.();
20355
+ };
20356
+ container.querySelector(".myio-temp-modal-overlay")?.addEventListener("click", (e) => {
20357
+ if (e.target === e.currentTarget) closeModal();
20358
+ });
20359
+ document.getElementById(`${modalId}-close`)?.addEventListener("click", closeModal);
20360
+ document.getElementById(`${modalId}-close-btn`)?.addEventListener("click", closeModal);
20361
+ const dateRangeInput = document.getElementById(`${modalId}-date-range`);
20362
+ if (dateRangeInput && !state.dateRangePicker) {
20363
+ try {
20364
+ state.dateRangePicker = await createDateRangePicker2(dateRangeInput, {
20365
+ presetStart: new Date(state.startTs).toISOString(),
20366
+ presetEnd: new Date(state.endTs).toISOString(),
20367
+ includeTime: true,
20368
+ timePrecision: "minute",
20369
+ maxRangeDays: 90,
20370
+ locale: state.locale,
20371
+ parentEl: container.querySelector(".myio-temp-modal-content"),
20372
+ onApply: (result) => {
20373
+ state.startTs = new Date(result.startISO).getTime();
20374
+ state.endTs = new Date(result.endISO).getTime();
20375
+ console.log("[TemperatureModal] Date range applied:", result);
20376
+ }
20377
+ });
20378
+ } catch (error) {
20379
+ console.warn("[TemperatureModal] DateRangePicker initialization failed:", error);
20380
+ }
20381
+ }
20382
+ document.getElementById(`${modalId}-theme-toggle`)?.addEventListener("click", async () => {
20383
+ state.theme = state.theme === "dark" ? "light" : "dark";
20384
+ localStorage.setItem("myio-temp-modal-theme", state.theme);
20385
+ state.dateRangePicker = null;
20386
+ renderModal(container, state, modalId);
20387
+ if (state.data.length > 0) drawChart(modalId, state);
20388
+ await setupEventListeners(container, state, modalId, onClose);
20389
+ });
20390
+ document.getElementById(`${modalId}-maximize`)?.addEventListener("click", async () => {
20391
+ container.__isMaximized = !container.__isMaximized;
20392
+ state.dateRangePicker = null;
20393
+ renderModal(container, state, modalId);
20394
+ if (state.data.length > 0) drawChart(modalId, state);
20395
+ await setupEventListeners(container, state, modalId, onClose);
20396
+ });
20397
+ const periodBtn = document.getElementById(`${modalId}-period-btn`);
20398
+ const periodDropdown = document.getElementById(`${modalId}-period-dropdown`);
20399
+ periodBtn?.addEventListener("click", (e) => {
20400
+ e.stopPropagation();
20401
+ if (periodDropdown) {
20402
+ periodDropdown.style.display = periodDropdown.style.display === "none" ? "block" : "none";
20403
+ }
20404
+ });
20405
+ document.addEventListener("click", (e) => {
20406
+ if (periodDropdown && !periodDropdown.contains(e.target) && e.target !== periodBtn) {
20407
+ periodDropdown.style.display = "none";
20408
+ }
20409
+ });
20410
+ const periodCheckboxes = document.querySelectorAll(`input[name="${modalId}-period"]`);
20411
+ periodCheckboxes.forEach((checkbox) => {
20412
+ checkbox.addEventListener("change", () => {
20413
+ const checked = Array.from(periodCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
20414
+ state.selectedPeriods = checked;
20415
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20416
+ if (btnLabel) {
20417
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20418
+ }
20419
+ if (state.data.length > 0) drawChart(modalId, state);
20420
+ });
20421
+ });
20422
+ document.getElementById(`${modalId}-period-select-all`)?.addEventListener("click", () => {
20423
+ periodCheckboxes.forEach((cb) => {
20424
+ cb.checked = true;
20425
+ });
20426
+ state.selectedPeriods = ["madrugada", "manha", "tarde", "noite"];
20427
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20428
+ if (btnLabel) {
20429
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20430
+ }
20431
+ if (state.data.length > 0) drawChart(modalId, state);
20432
+ });
20433
+ document.getElementById(`${modalId}-period-clear`)?.addEventListener("click", () => {
20434
+ periodCheckboxes.forEach((cb) => {
20435
+ cb.checked = false;
20436
+ });
20437
+ state.selectedPeriods = [];
20438
+ const btnLabel = periodBtn?.querySelector("span:first-child");
20439
+ if (btnLabel) {
20440
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
20441
+ }
20442
+ if (state.data.length > 0) drawChart(modalId, state);
20443
+ });
20444
+ document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
20445
+ state.granularity = e.target.value;
20446
+ localStorage.setItem("myio-temp-modal-granularity", state.granularity);
20447
+ if (state.data.length > 0) drawChart(modalId, state);
20448
+ });
20449
+ document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
20450
+ if (state.startTs >= state.endTs) {
20451
+ alert("Por favor, selecione um per\xEDodo v\xE1lido");
20452
+ return;
20453
+ }
20454
+ state.isLoading = true;
20455
+ state.dateRangePicker = null;
20456
+ renderModal(container, state, modalId);
20457
+ try {
20458
+ state.data = await fetchTemperatureData(state.token, state.deviceId, state.startTs, state.endTs);
20459
+ state.stats = calculateStats(state.data, state.clampRange);
20460
+ state.isLoading = false;
20461
+ renderModal(container, state, modalId);
20462
+ drawChart(modalId, state);
20463
+ await setupEventListeners(container, state, modalId, onClose);
20464
+ } catch (error) {
20465
+ console.error("[TemperatureModal] Error fetching data:", error);
20466
+ state.isLoading = false;
20467
+ renderModal(container, state, modalId, error);
20468
+ await setupEventListeners(container, state, modalId, onClose);
20469
+ }
20470
+ });
20471
+ document.getElementById(`${modalId}-export`)?.addEventListener("click", () => {
20472
+ if (state.data.length === 0) return;
20473
+ const startDateStr = new Date(state.startTs).toLocaleDateString(state.locale).replace(/\//g, "-");
20474
+ const endDateStr = new Date(state.endTs).toLocaleDateString(state.locale).replace(/\//g, "-");
20475
+ exportTemperatureCSV(
20476
+ state.data,
20477
+ state.label,
20478
+ state.stats,
20479
+ startDateStr,
20480
+ endDateStr
20481
+ );
20482
+ });
20483
+ }
20484
+
20485
+ // src/components/temperature/TemperatureComparisonModal.ts
20486
+ async function openTemperatureComparisonModal(params) {
20487
+ const modalId = `myio-temp-comparison-modal-${Date.now()}`;
20488
+ const defaultDateRange = getTodaySoFar();
20489
+ const startTs = params.startDate ? new Date(params.startDate).getTime() : defaultDateRange.startTs;
20490
+ const endTs = params.endDate ? new Date(params.endDate).getTime() : defaultDateRange.endTs;
20491
+ const state = {
20492
+ token: params.token,
20493
+ devices: params.devices,
20494
+ startTs,
20495
+ endTs,
20496
+ granularity: params.granularity || "hour",
20497
+ theme: params.theme || "dark",
20498
+ clampRange: params.clampRange || DEFAULT_CLAMP_RANGE,
20499
+ locale: params.locale || "pt-BR",
20500
+ deviceData: [],
20501
+ isLoading: true,
20502
+ dateRangePicker: null,
20503
+ selectedPeriods: ["madrugada", "manha", "tarde", "noite"],
20504
+ // All periods selected by default
20505
+ temperatureMin: params.temperatureMin ?? null,
20506
+ temperatureMax: params.temperatureMax ?? null
20507
+ };
20508
+ const savedGranularity = localStorage.getItem("myio-temp-comparison-granularity");
20509
+ const savedTheme = localStorage.getItem("myio-temp-comparison-theme");
20510
+ if (savedGranularity) state.granularity = savedGranularity;
20511
+ if (savedTheme) state.theme = savedTheme;
20512
+ const modalContainer = document.createElement("div");
20513
+ modalContainer.id = modalId;
20514
+ document.body.appendChild(modalContainer);
20515
+ renderModal2(modalContainer, state, modalId);
20516
+ await fetchAllDevicesData(state);
20517
+ renderModal2(modalContainer, state, modalId);
20518
+ drawComparisonChart(modalId, state);
20519
+ await setupEventListeners2(modalContainer, state, modalId, params.onClose);
20520
+ return {
20521
+ destroy: () => {
20522
+ modalContainer.remove();
20523
+ params.onClose?.();
20524
+ },
20525
+ updateData: async (startDate, endDate, granularity) => {
20526
+ state.startTs = new Date(startDate).getTime();
20527
+ state.endTs = new Date(endDate).getTime();
20528
+ if (granularity) state.granularity = granularity;
20529
+ state.isLoading = true;
20530
+ renderModal2(modalContainer, state, modalId);
20531
+ await fetchAllDevicesData(state);
20532
+ renderModal2(modalContainer, state, modalId);
20533
+ drawComparisonChart(modalId, state);
20534
+ setupEventListeners2(modalContainer, state, modalId, params.onClose);
20535
+ }
20536
+ };
20537
+ }
20538
+ async function fetchAllDevicesData(state) {
20539
+ state.isLoading = true;
20540
+ state.deviceData = [];
20541
+ try {
20542
+ const results = await Promise.all(
20543
+ state.devices.map(async (device, index) => {
20544
+ const deviceId = device.tbId || device.id;
20545
+ try {
20546
+ const data = await fetchTemperatureData(state.token, deviceId, state.startTs, state.endTs);
20547
+ const stats = calculateStats(data, state.clampRange);
20548
+ return {
20549
+ device,
20550
+ data,
20551
+ stats,
20552
+ color: CHART_COLORS[index % CHART_COLORS.length]
20553
+ };
20554
+ } catch (error) {
20555
+ console.error(`[TemperatureComparisonModal] Error fetching data for ${device.label}:`, error);
20556
+ return {
20557
+ device,
20558
+ data: [],
20559
+ stats: { avg: 0, min: 0, max: 0, count: 0 },
20560
+ color: CHART_COLORS[index % CHART_COLORS.length]
20561
+ };
20562
+ }
20563
+ })
20564
+ );
20565
+ state.deviceData = results;
20566
+ } catch (error) {
20567
+ console.error("[TemperatureComparisonModal] Error fetching data:", error);
20568
+ }
20569
+ state.isLoading = false;
20570
+ }
20571
+ function renderModal2(container, state, modalId) {
20572
+ const colors = getThemeColors(state.theme);
20573
+ const startDateStr = new Date(state.startTs).toLocaleDateString(state.locale);
20574
+ const endDateStr = new Date(state.endTs).toLocaleDateString(state.locale);
20575
+ const startDateInput = new Date(state.startTs).toISOString().slice(0, 16);
20576
+ const endDateInput = new Date(state.endTs).toISOString().slice(0, 16);
20577
+ const legendHTML = state.deviceData.map((dd) => `
20578
+ <div style="display: flex; align-items: center; gap: 8px; padding: 8px 12px;
20579
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.03)"};
20580
+ border-radius: 8px;">
20581
+ <span style="width: 12px; height: 12px; border-radius: 50%; background: ${dd.color};"></span>
20582
+ <span style="color: ${colors.text}; font-size: 13px;">${dd.device.label}</span>
20583
+ <span style="color: ${colors.textMuted}; font-size: 11px; margin-left: auto;">
20584
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.avg) : "N/A"}
20585
+ </span>
20586
+ </div>
20587
+ `).join("");
20588
+ const statsHTML = state.deviceData.map((dd) => `
20589
+ <div style="
20590
+ padding: 12px; background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#fafafa"};
20591
+ border-radius: 10px; border-left: 4px solid ${dd.color};
20592
+ min-width: 150px;
20593
+ ">
20594
+ <div style="font-weight: 600; color: ${colors.text}; font-size: 13px; margin-bottom: 8px;">
20595
+ ${dd.device.label}
20596
+ </div>
20597
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 4px; font-size: 11px;">
20598
+ <span style="color: ${colors.textMuted};">M\xE9dia:</span>
20599
+ <span style="color: ${colors.text}; font-weight: 500;">
20600
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.avg) : "N/A"}
20601
+ </span>
20602
+ <span style="color: ${colors.textMuted};">Min:</span>
20603
+ <span style="color: ${colors.text};">
20604
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.min) : "N/A"}
20605
+ </span>
20606
+ <span style="color: ${colors.textMuted};">Max:</span>
20607
+ <span style="color: ${colors.text};">
20608
+ ${dd.stats.count > 0 ? formatTemperature(dd.stats.max) : "N/A"}
20609
+ </span>
20610
+ <span style="color: ${colors.textMuted};">Leituras:</span>
20611
+ <span style="color: ${colors.text};">${dd.stats.count}</span>
20612
+ </div>
20613
+ </div>
20614
+ `).join("");
20615
+ const isMaximized = container.__isMaximized || false;
20616
+ const contentMaxWidth = isMaximized ? "100%" : "1100px";
20617
+ const contentMaxHeight = isMaximized ? "100vh" : "95vh";
20618
+ const contentBorderRadius = isMaximized ? "0" : "10px";
20619
+ container.innerHTML = `
20620
+ <div class="myio-temp-comparison-overlay" style="
20621
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
20622
+ background: rgba(0, 0, 0, 0.5); z-index: 9998;
20623
+ display: flex; justify-content: center; align-items: center;
20624
+ backdrop-filter: blur(2px);
20625
+ ">
20626
+ <div class="myio-temp-comparison-content" style="
20627
+ background: ${colors.surface}; border-radius: ${contentBorderRadius};
20628
+ max-width: ${contentMaxWidth}; width: ${isMaximized ? "100%" : "95%"};
20629
+ max-height: ${contentMaxHeight}; height: ${isMaximized ? "100%" : "auto"};
20630
+ overflow: hidden; display: flex; flex-direction: column;
20631
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20632
+ font-family: 'Roboto', Arial, sans-serif;
20633
+ ">
20634
+ <!-- Header - MyIO Premium Style -->
20635
+ <div style="
20636
+ padding: 4px 8px; display: flex; align-items: center; justify-content: space-between;
20637
+ background: #3e1a7d; color: white; border-radius: ${isMaximized ? "0" : "10px 10px 0 0"};
20638
+ min-height: 20px;
20639
+ ">
20640
+ <h2 style="margin: 6px; font-size: 18px; font-weight: 600; color: white; line-height: 2;">
20641
+ \u{1F321}\uFE0F Compara\xE7\xE3o de Temperatura - ${state.devices.length} sensores
20642
+ </h2>
20643
+ <div style="display: flex; gap: 4px; align-items: center;">
20644
+ <!-- Theme Toggle -->
20645
+ <button id="${modalId}-theme-toggle" title="Alternar tema" 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
+ ">${state.theme === "dark" ? "\u2600\uFE0F" : "\u{1F319}"}</button>
20650
+ <!-- Maximize Button -->
20651
+ <button id="${modalId}-maximize" title="${isMaximized ? "Restaurar" : "Maximizar"}" style="
20652
+ background: none; border: none; font-size: 16px; cursor: pointer;
20653
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
20654
+ transition: background-color 0.2s;
20655
+ ">${isMaximized ? "\u{1F5D7}" : "\u{1F5D6}"}</button>
20656
+ <!-- Close Button -->
20657
+ <button id="${modalId}-close" title="Fechar" style="
20658
+ background: none; border: none; font-size: 20px; cursor: pointer;
20659
+ padding: 4px 8px; border-radius: 6px; color: rgba(255,255,255,0.8);
20660
+ transition: background-color 0.2s;
20661
+ ">\xD7</button>
20662
+ </div>
20663
+ </div>
20664
+
20665
+ <!-- Body -->
20666
+ <div style="flex: 1; overflow-y: auto; padding: 16px;">
20667
+
20668
+ <!-- Controls Row -->
20669
+ <div style="
20670
+ display: flex; gap: 16px; flex-wrap: wrap; align-items: flex-end;
20671
+ margin-bottom: 16px; padding: 16px;
20672
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.05)" : "#f7f7f7"};
20673
+ border-radius: 6px; border: 1px solid ${colors.border};
20674
+ ">
20675
+ <!-- Granularity Select -->
20676
+ <div>
20677
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
20678
+ Granularidade
20679
+ </label>
20680
+ <select id="${modalId}-granularity" style="
20681
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
20682
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
20683
+ cursor: pointer; min-width: 130px;
20684
+ ">
20685
+ <option value="hour" ${state.granularity === "hour" ? "selected" : ""}>Hora (30 min)</option>
20686
+ <option value="day" ${state.granularity === "day" ? "selected" : ""}>Dia (m\xE9dia)</option>
20687
+ </select>
20688
+ </div>
20689
+ <!-- Day Period Filter (Multiselect) -->
20690
+ <div style="position: relative;">
20691
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
20692
+ Per\xEDodos do Dia
20693
+ </label>
20694
+ <button id="${modalId}-period-btn" type="button" style="
20695
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
20696
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
20697
+ cursor: pointer; min-width: 180px; text-align: left;
20698
+ display: flex; align-items: center; justify-content: space-between; gap: 8px;
20699
+ ">
20700
+ <span>${getSelectedPeriodsLabel(state.selectedPeriods)}</span>
20701
+ <span style="font-size: 10px;">\u25BC</span>
20702
+ </button>
20703
+ <div id="${modalId}-period-dropdown" style="
20704
+ display: none; position: absolute; top: 100%; left: 0; z-index: 1000;
20705
+ background: ${colors.surface}; border: 1px solid ${colors.border};
20706
+ border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,0.15);
20707
+ min-width: 200px; margin-top: 4px; padding: 8px 0;
20708
+ ">
20709
+ ${DAY_PERIODS.map((period) => `
20710
+ <label style="
20711
+ display: flex; align-items: center; gap: 8px; padding: 8px 12px;
20712
+ cursor: pointer; font-size: 13px; color: ${colors.text};
20713
+ " onmouseover="this.style.background='${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"}'"
20714
+ onmouseout="this.style.background='transparent'">
20715
+ <input type="checkbox"
20716
+ name="${modalId}-period"
20717
+ value="${period.id}"
20718
+ ${state.selectedPeriods.includes(period.id) ? "checked" : ""}
20719
+ style="width: 16px; height: 16px; cursor: pointer; accent-color: #3e1a7d;">
20720
+ ${period.label}
20721
+ </label>
20722
+ `).join("")}
20723
+ <div style="border-top: 1px solid ${colors.border}; margin-top: 8px; padding-top: 8px;">
20724
+ <button id="${modalId}-period-select-all" type="button" style="
20725
+ width: calc(100% - 16px); margin: 0 8px 4px; 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
+ ">Selecionar Todos</button>
20730
+ <button id="${modalId}-period-clear" type="button" style="
20731
+ width: calc(100% - 16px); margin: 0 8px; padding: 6px;
20732
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f0f0f0"};
20733
+ border: none; border-radius: 4px; cursor: pointer;
20734
+ font-size: 12px; color: ${colors.text};
20735
+ ">Limpar Sele\xE7\xE3o</button>
20736
+ </div>
20737
+ </div>
20738
+ </div>
20739
+ <!-- Date Range Picker -->
20740
+ <div style="flex: 1; min-width: 220px;">
20741
+ <label style="color: ${colors.textMuted}; font-size: 12px; font-weight: 500; display: block; margin-bottom: 4px;">
20742
+ Per\xEDodo
20743
+ </label>
20744
+ <input type="text" id="${modalId}-date-range" readonly placeholder="Selecione o per\xEDodo..." style="
20745
+ padding: 8px 12px; border: 1px solid ${colors.border}; border-radius: 6px;
20746
+ font-size: 14px; color: ${colors.text}; background: ${colors.surface};
20747
+ width: 100%; cursor: pointer; box-sizing: border-box;
20748
+ "/>
20749
+ </div>
20750
+ <!-- Query Button -->
20751
+ <button id="${modalId}-query" style="
20752
+ background: #3e1a7d; color: white; border: none;
20753
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
20754
+ font-size: 14px; font-weight: 500; height: 38px;
20755
+ display: flex; align-items: center; gap: 8px;
20756
+ font-family: 'Roboto', Arial, sans-serif;
20757
+ " ${state.isLoading ? "disabled" : ""}>
20758
+ ${state.isLoading ? '<span style="animation: spin 1s linear infinite; display: inline-block;">\u21BB</span> Carregando...' : "Carregar"}
20759
+ </button>
20760
+ </div>
20761
+
20762
+ <!-- Legend -->
20763
+ <div style="
20764
+ display: flex; flex-wrap: wrap; gap: 10px;
20765
+ margin-bottom: 20px;
20766
+ ">
20767
+ ${legendHTML}
20768
+ </div>
20769
+
20770
+ <!-- Chart Container -->
20771
+ <div style="margin-bottom: 24px;">
20772
+ <div id="${modalId}-chart" style="
20773
+ height: 380px;
20774
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.03)" : "#fafafa"};
20775
+ border-radius: 14px; display: flex; justify-content: center; align-items: center;
20776
+ border: 1px solid ${colors.border}; position: relative;
20777
+ ">
20778
+ ${state.isLoading ? `<div style="text-align: center; color: ${colors.textMuted};">
20779
+ <div style="animation: spin 1s linear infinite; font-size: 36px; margin-bottom: 12px;">\u21BB</div>
20780
+ <div style="font-size: 15px;">Carregando dados de ${state.devices.length} sensores...</div>
20781
+ </div>` : state.deviceData.every((dd) => dd.data.length === 0) ? `<div style="text-align: center; color: ${colors.textMuted};">
20782
+ <div style="font-size: 48px; margin-bottom: 12px;">\u{1F4ED}</div>
20783
+ <div style="font-size: 16px;">Sem dados para o per\xEDodo selecionado</div>
20784
+ </div>` : `<canvas id="${modalId}-canvas" style="width: 100%; height: 100%;"></canvas>`}
20785
+ </div>
20786
+ </div>
20787
+
20788
+ <!-- Stats Cards -->
20789
+ <div style="
20790
+ display: flex; flex-wrap: wrap; gap: 12px;
20791
+ margin-bottom: 24px;
20792
+ ">
20793
+ ${statsHTML}
20794
+ </div>
20795
+
20796
+ <!-- Actions -->
20797
+ <div style="display: flex; justify-content: flex-end; gap: 12px;">
20798
+ <button id="${modalId}-export" style="
20799
+ background: ${state.theme === "dark" ? "rgba(255,255,255,0.1)" : "#f7f7f7"};
20800
+ color: ${colors.text}; border: 1px solid ${colors.border};
20801
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
20802
+ font-size: 14px; display: flex; align-items: center; gap: 8px;
20803
+ font-family: 'Roboto', Arial, sans-serif;
20804
+ " ${state.deviceData.every((dd) => dd.data.length === 0) ? "disabled" : ""}>
20805
+ \u{1F4E5} Exportar CSV
20806
+ </button>
20807
+ <button id="${modalId}-close-btn" style="
20808
+ background: #3e1a7d; color: white; border: none;
20809
+ padding: 8px 16px; border-radius: 6px; cursor: pointer;
20810
+ font-size: 14px; font-weight: 500;
20811
+ font-family: 'Roboto', Arial, sans-serif;
20812
+ ">
20813
+ Fechar
20814
+ </button>
20815
+ </div>
20816
+ </div><!-- End Body -->
20817
+ </div>
20818
+ </div>
20819
+ <style>
20820
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
20821
+ #${modalId} select:focus, #${modalId} input:focus {
20822
+ outline: 2px solid #3e1a7d;
20823
+ outline-offset: 2px;
20824
+ }
20825
+ #${modalId} button:hover:not(:disabled) {
20826
+ opacity: 0.9;
20827
+ }
20828
+ #${modalId} button:disabled {
20829
+ opacity: 0.5;
20830
+ cursor: not-allowed;
20831
+ }
20832
+ #${modalId} .myio-temp-comparison-content > div:first-child button:hover {
20833
+ background: rgba(255, 255, 255, 0.1) !important;
20834
+ color: white !important;
20835
+ }
20836
+ </style>
20837
+ `;
20838
+ }
20839
+ function drawComparisonChart(modalId, state) {
20840
+ const chartContainer = document.getElementById(`${modalId}-chart`);
20841
+ const canvas = document.getElementById(`${modalId}-canvas`);
20842
+ if (!chartContainer || !canvas) return;
20843
+ const hasData = state.deviceData.some((dd) => dd.data.length > 0);
20844
+ if (!hasData) return;
20845
+ const ctx = canvas.getContext("2d");
20846
+ if (!ctx) return;
20847
+ const colors = getThemeColors(state.theme);
20848
+ const width = chartContainer.clientWidth - 2;
20849
+ const height = 380;
20850
+ canvas.width = width;
20851
+ canvas.height = height;
20852
+ const paddingLeft = 65;
20853
+ const paddingRight = 25;
20854
+ const paddingTop = 25;
20855
+ const paddingBottom = 55;
20856
+ ctx.clearRect(0, 0, width, height);
20857
+ const processedData = [];
20858
+ state.deviceData.forEach((dd) => {
20859
+ if (dd.data.length === 0) return;
20860
+ const filteredData = filterByDayPeriods(dd.data, state.selectedPeriods);
20861
+ if (filteredData.length === 0) return;
20862
+ let points;
20863
+ if (state.granularity === "hour") {
20864
+ const interpolated = interpolateTemperature(filteredData, {
20865
+ intervalMinutes: 30,
20866
+ startTs: state.startTs,
20867
+ endTs: state.endTs,
20868
+ clampRange: state.clampRange
20869
+ });
20870
+ const filteredInterpolated = filterByDayPeriods(interpolated, state.selectedPeriods);
20871
+ points = filteredInterpolated.map((item) => ({
20872
+ x: item.ts,
20873
+ y: Number(item.value),
20874
+ screenX: 0,
20875
+ screenY: 0,
20876
+ deviceLabel: dd.device.label,
20877
+ deviceColor: dd.color
20878
+ }));
20879
+ } else {
20880
+ const daily = aggregateByDay(filteredData, state.clampRange);
20881
+ points = daily.map((item) => ({
20882
+ x: item.dateTs,
20883
+ y: item.avg,
20884
+ screenX: 0,
20885
+ screenY: 0,
20886
+ deviceLabel: dd.device.label,
20887
+ deviceColor: dd.color
20888
+ }));
20889
+ }
20890
+ if (points.length > 0) {
20891
+ processedData.push({ device: dd, points });
20892
+ }
20893
+ });
20894
+ if (processedData.length === 0) {
20895
+ ctx.fillStyle = colors.textMuted;
20896
+ ctx.font = "14px Roboto, Arial, sans-serif";
20897
+ ctx.textAlign = "center";
20898
+ ctx.fillText("Nenhum dado para os per\xEDodos selecionados", width / 2, height / 2);
20899
+ return;
20900
+ }
20901
+ const isPeriodsFiltered = state.selectedPeriods.length < 4 && state.selectedPeriods.length > 0;
20902
+ let dataMinY = Infinity;
20903
+ let dataMaxY = -Infinity;
20904
+ processedData.forEach(({ points }) => {
20905
+ points.forEach((point) => {
20906
+ if (point.y < dataMinY) dataMinY = point.y;
20907
+ if (point.y > dataMaxY) dataMaxY = point.y;
20908
+ });
20909
+ });
20910
+ const rangeMap = /* @__PURE__ */ new Map();
20911
+ state.deviceData.forEach((dd, index) => {
20912
+ const device = dd.device;
20913
+ const min = device.temperatureMin;
20914
+ const max = device.temperatureMax;
20915
+ if (min !== void 0 && min !== null && max !== void 0 && max !== null) {
20916
+ const key = `${min}-${max}`;
20917
+ if (!rangeMap.has(key)) {
20918
+ rangeMap.set(key, {
20919
+ min,
20920
+ max,
20921
+ customerName: device.customerName || "",
20922
+ color: CHART_COLORS[index % CHART_COLORS.length],
20923
+ deviceLabels: [device.label]
20924
+ });
20925
+ } else {
20926
+ rangeMap.get(key).deviceLabels.push(device.label);
20927
+ }
20928
+ }
20929
+ });
20930
+ if (rangeMap.size === 0 && state.temperatureMin !== null && state.temperatureMax !== null) {
20931
+ rangeMap.set("global", {
20932
+ min: state.temperatureMin,
20933
+ max: state.temperatureMax,
20934
+ customerName: "Global",
20935
+ color: colors.success,
20936
+ deviceLabels: []
20937
+ });
20938
+ }
20939
+ const temperatureRanges = Array.from(rangeMap.values());
20940
+ let thresholdMinY = dataMinY;
20941
+ let thresholdMaxY = dataMaxY;
20942
+ temperatureRanges.forEach((range) => {
20943
+ if (range.min < thresholdMinY) thresholdMinY = range.min;
20944
+ if (range.max > thresholdMaxY) thresholdMaxY = range.max;
20945
+ });
20946
+ const globalMinY = Math.floor(Math.min(dataMinY, thresholdMinY)) - 1;
20947
+ const globalMaxY = Math.ceil(Math.max(dataMaxY, thresholdMaxY)) + 1;
20948
+ const chartWidth = width - paddingLeft - paddingRight;
20949
+ const chartHeight = height - paddingTop - paddingBottom;
20950
+ const scaleY = chartHeight / (globalMaxY - globalMinY || 1);
20951
+ if (isPeriodsFiltered) {
20952
+ const maxPoints = Math.max(...processedData.map(({ points }) => points.length));
20953
+ const pointSpacing = chartWidth / Math.max(1, maxPoints - 1);
20954
+ processedData.forEach(({ points }) => {
20955
+ points.forEach((point, index) => {
20956
+ point.screenX = paddingLeft + index * pointSpacing;
20957
+ point.screenY = height - paddingBottom - (point.y - globalMinY) * scaleY;
20958
+ });
20959
+ });
20960
+ } else {
20961
+ let globalMinX = Infinity;
20962
+ let globalMaxX = -Infinity;
20963
+ processedData.forEach(({ points }) => {
20964
+ points.forEach((point) => {
20965
+ if (point.x < globalMinX) globalMinX = point.x;
20966
+ if (point.x > globalMaxX) globalMaxX = point.x;
20967
+ });
20968
+ });
20969
+ const timeRange = globalMaxX - globalMinX || 1;
20970
+ const scaleX = chartWidth / timeRange;
20971
+ processedData.forEach(({ points }) => {
20972
+ points.forEach((point) => {
20973
+ point.screenX = paddingLeft + (point.x - globalMinX) * scaleX;
20974
+ point.screenY = height - paddingBottom - (point.y - globalMinY) * scaleY;
20975
+ });
20976
+ });
20977
+ }
20978
+ ctx.strokeStyle = colors.chartGrid;
20979
+ ctx.lineWidth = 1;
20980
+ for (let i = 0; i <= 5; i++) {
20981
+ const y = paddingTop + chartHeight * i / 5;
20982
+ ctx.beginPath();
20983
+ ctx.moveTo(paddingLeft, y);
20984
+ ctx.lineTo(width - paddingRight, y);
20985
+ ctx.stroke();
20986
+ }
20987
+ const rangeColors = [
20988
+ { fill: "rgba(76, 175, 80, 0.12)", stroke: "#4CAF50" },
20989
+ // Green
20990
+ { fill: "rgba(33, 150, 243, 0.12)", stroke: "#2196F3" },
20991
+ // Blue
20992
+ { fill: "rgba(255, 152, 0, 0.12)", stroke: "#FF9800" },
20993
+ // Orange
20994
+ { fill: "rgba(156, 39, 176, 0.12)", stroke: "#9C27B0" }
20995
+ // Purple
20996
+ ];
20997
+ temperatureRanges.forEach((range, index) => {
20998
+ const rangeMinY = height - paddingBottom - (range.min - globalMinY) * scaleY;
20999
+ const rangeMaxY = height - paddingBottom - (range.max - globalMinY) * scaleY;
21000
+ const colorSet = rangeColors[index % rangeColors.length];
21001
+ ctx.fillStyle = colorSet.fill;
21002
+ ctx.fillRect(paddingLeft, rangeMaxY, chartWidth, rangeMinY - rangeMaxY);
21003
+ ctx.strokeStyle = colorSet.stroke;
21004
+ ctx.lineWidth = 1.5;
21005
+ ctx.setLineDash([6, 4]);
21006
+ ctx.beginPath();
21007
+ ctx.moveTo(paddingLeft, rangeMinY);
21008
+ ctx.lineTo(width - paddingRight, rangeMinY);
21009
+ ctx.moveTo(paddingLeft, rangeMaxY);
21010
+ ctx.lineTo(width - paddingRight, rangeMaxY);
21011
+ ctx.stroke();
21012
+ ctx.setLineDash([]);
21013
+ if (temperatureRanges.length > 1 || range.customerName) {
21014
+ ctx.fillStyle = colorSet.stroke;
21015
+ ctx.font = "10px system-ui, sans-serif";
21016
+ ctx.textAlign = "left";
21017
+ const labelY = (rangeMinY + rangeMaxY) / 2;
21018
+ const labelText = range.customerName || `${range.min}\xB0-${range.max}\xB0C`;
21019
+ ctx.fillText(labelText, width - paddingRight + 5, labelY + 3);
21020
+ }
21021
+ });
21022
+ processedData.forEach(({ device, points }) => {
21023
+ ctx.strokeStyle = device.color;
21024
+ ctx.lineWidth = 2.5;
21025
+ ctx.beginPath();
21026
+ points.forEach((point, i) => {
21027
+ if (i === 0) ctx.moveTo(point.screenX, point.screenY);
21028
+ else ctx.lineTo(point.screenX, point.screenY);
21029
+ });
21030
+ ctx.stroke();
21031
+ ctx.fillStyle = device.color;
21032
+ points.forEach((point) => {
21033
+ ctx.beginPath();
21034
+ ctx.arc(point.screenX, point.screenY, 4, 0, Math.PI * 2);
21035
+ ctx.fill();
21036
+ });
21037
+ });
21038
+ ctx.fillStyle = colors.textMuted;
21039
+ ctx.font = "12px system-ui, sans-serif";
21040
+ ctx.textAlign = "right";
21041
+ for (let i = 0; i <= 5; i++) {
21042
+ const val = globalMinY + (globalMaxY - globalMinY) * (5 - i) / 5;
21043
+ const y = paddingTop + chartHeight * i / 5;
21044
+ ctx.fillText(val.toFixed(1) + "\xB0C", paddingLeft - 10, y + 4);
21045
+ }
21046
+ ctx.textAlign = "center";
21047
+ const xAxisPoints = processedData[0]?.points || [];
21048
+ const numLabels = Math.min(8, xAxisPoints.length);
21049
+ const labelInterval = Math.max(1, Math.floor(xAxisPoints.length / numLabels));
21050
+ for (let i = 0; i < xAxisPoints.length; i += labelInterval) {
21051
+ const point = xAxisPoints[i];
21052
+ const date = new Date(point.x);
21053
+ let label;
21054
+ if (state.granularity === "hour") {
21055
+ label = date.toLocaleTimeString(state.locale, { hour: "2-digit", minute: "2-digit" });
21056
+ } else {
21057
+ label = date.toLocaleDateString(state.locale, { day: "2-digit", month: "2-digit" });
21058
+ }
21059
+ ctx.strokeStyle = colors.chartGrid;
21060
+ ctx.lineWidth = 1;
21061
+ ctx.beginPath();
21062
+ ctx.moveTo(point.screenX, paddingTop);
21063
+ ctx.lineTo(point.screenX, height - paddingBottom);
21064
+ ctx.stroke();
21065
+ ctx.fillStyle = colors.textMuted;
21066
+ ctx.fillText(label, point.screenX, height - paddingBottom + 18);
21067
+ }
21068
+ ctx.strokeStyle = colors.border;
21069
+ ctx.lineWidth = 1;
21070
+ ctx.beginPath();
21071
+ ctx.moveTo(paddingLeft, paddingTop);
21072
+ ctx.lineTo(paddingLeft, height - paddingBottom);
21073
+ ctx.lineTo(width - paddingRight, height - paddingBottom);
21074
+ ctx.stroke();
21075
+ const allChartPoints = processedData.flatMap((pd) => pd.points);
21076
+ setupComparisonChartTooltip(canvas, chartContainer, allChartPoints, state, colors);
21077
+ }
21078
+ function setupComparisonChartTooltip(canvas, container, chartData, state, colors) {
21079
+ const existingTooltip = container.querySelector(".myio-chart-tooltip");
21080
+ if (existingTooltip) existingTooltip.remove();
21081
+ const tooltip = document.createElement("div");
21082
+ tooltip.className = "myio-chart-tooltip";
21083
+ tooltip.style.cssText = `
21084
+ position: absolute;
21085
+ background: ${state.theme === "dark" ? "rgba(30, 30, 40, 0.95)" : "rgba(255, 255, 255, 0.98)"};
21086
+ border: 1px solid ${colors.border};
21087
+ border-radius: 8px;
21088
+ padding: 10px 14px;
21089
+ font-size: 13px;
21090
+ color: ${colors.text};
21091
+ pointer-events: none;
21092
+ opacity: 0;
21093
+ transition: opacity 0.15s;
21094
+ z-index: 1000;
21095
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
21096
+ min-width: 160px;
21097
+ `;
21098
+ container.appendChild(tooltip);
21099
+ const findNearestPoint = (mouseX, mouseY) => {
21100
+ const threshold = 20;
21101
+ let nearest = null;
21102
+ let minDist = Infinity;
21103
+ for (const point of chartData) {
21104
+ const dist = Math.sqrt(
21105
+ Math.pow(mouseX - point.screenX, 2) + Math.pow(mouseY - point.screenY, 2)
21106
+ );
21107
+ if (dist < minDist && dist < threshold) {
21108
+ minDist = dist;
21109
+ nearest = point;
21110
+ }
21111
+ }
21112
+ return nearest;
21113
+ };
21114
+ canvas.addEventListener("mousemove", (e) => {
21115
+ const rect = canvas.getBoundingClientRect();
21116
+ const mouseX = e.clientX - rect.left;
21117
+ const mouseY = e.clientY - rect.top;
21118
+ const point = findNearestPoint(mouseX, mouseY);
21119
+ if (point) {
21120
+ const date = new Date(point.x);
21121
+ let dateStr;
21122
+ if (state.granularity === "hour") {
21123
+ dateStr = date.toLocaleDateString(state.locale, {
21124
+ day: "2-digit",
21125
+ month: "2-digit",
21126
+ year: "numeric"
21127
+ }) + " " + date.toLocaleTimeString(state.locale, {
21128
+ hour: "2-digit",
21129
+ minute: "2-digit"
21130
+ });
21131
+ } else {
21132
+ dateStr = date.toLocaleDateString(state.locale, {
21133
+ day: "2-digit",
21134
+ month: "2-digit",
21135
+ year: "numeric"
21136
+ });
21137
+ }
21138
+ tooltip.innerHTML = `
21139
+ <div style="display: flex; align-items: center; gap: 8px; margin-bottom: 6px;">
21140
+ <span style="width: 10px; height: 10px; border-radius: 50%; background: ${point.deviceColor};"></span>
21141
+ <span style="font-weight: 600;">${point.deviceLabel}</span>
21142
+ </div>
21143
+ <div style="font-weight: 600; font-size: 16px; color: ${point.deviceColor}; margin-bottom: 4px;">
21144
+ ${formatTemperature(point.y)}
21145
+ </div>
21146
+ <div style="font-size: 11px; color: ${colors.textMuted};">
21147
+ \u{1F4C5} ${dateStr}
21148
+ </div>
21149
+ `;
21150
+ let tooltipX = point.screenX + 15;
21151
+ let tooltipY = point.screenY - 15;
21152
+ const tooltipRect = tooltip.getBoundingClientRect();
21153
+ const containerRect = container.getBoundingClientRect();
21154
+ if (tooltipX + tooltipRect.width > containerRect.width - 10) {
21155
+ tooltipX = point.screenX - tooltipRect.width - 15;
21156
+ }
21157
+ if (tooltipY < 10) {
21158
+ tooltipY = point.screenY + 15;
21159
+ }
21160
+ tooltip.style.left = `${tooltipX}px`;
21161
+ tooltip.style.top = `${tooltipY}px`;
21162
+ tooltip.style.opacity = "1";
21163
+ canvas.style.cursor = "pointer";
21164
+ } else {
21165
+ tooltip.style.opacity = "0";
21166
+ canvas.style.cursor = "default";
21167
+ }
21168
+ });
21169
+ canvas.addEventListener("mouseleave", () => {
21170
+ tooltip.style.opacity = "0";
21171
+ canvas.style.cursor = "default";
21172
+ });
21173
+ }
21174
+ async function setupEventListeners2(container, state, modalId, onClose) {
21175
+ const closeModal = () => {
21176
+ container.remove();
21177
+ onClose?.();
21178
+ };
21179
+ container.querySelector(".myio-temp-comparison-overlay")?.addEventListener("click", (e) => {
21180
+ if (e.target === e.currentTarget) closeModal();
21181
+ });
21182
+ document.getElementById(`${modalId}-close`)?.addEventListener("click", closeModal);
21183
+ document.getElementById(`${modalId}-close-btn`)?.addEventListener("click", closeModal);
21184
+ const dateRangeInput = document.getElementById(`${modalId}-date-range`);
21185
+ if (dateRangeInput && !state.dateRangePicker) {
21186
+ try {
21187
+ state.dateRangePicker = await createDateRangePicker2(dateRangeInput, {
21188
+ presetStart: new Date(state.startTs).toISOString(),
21189
+ presetEnd: new Date(state.endTs).toISOString(),
21190
+ includeTime: true,
21191
+ timePrecision: "minute",
21192
+ maxRangeDays: 90,
21193
+ locale: state.locale,
21194
+ parentEl: container.querySelector(".myio-temp-comparison-content"),
21195
+ onApply: (result) => {
21196
+ state.startTs = new Date(result.startISO).getTime();
21197
+ state.endTs = new Date(result.endISO).getTime();
21198
+ console.log("[TemperatureComparisonModal] Date range applied:", result);
21199
+ }
21200
+ });
21201
+ } catch (error) {
21202
+ console.warn("[TemperatureComparisonModal] DateRangePicker initialization failed:", error);
21203
+ }
21204
+ }
21205
+ document.getElementById(`${modalId}-theme-toggle`)?.addEventListener("click", async () => {
21206
+ state.theme = state.theme === "dark" ? "light" : "dark";
21207
+ localStorage.setItem("myio-temp-comparison-theme", state.theme);
21208
+ state.dateRangePicker = null;
21209
+ renderModal2(container, state, modalId);
21210
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21211
+ drawComparisonChart(modalId, state);
21212
+ }
21213
+ await setupEventListeners2(container, state, modalId, onClose);
21214
+ });
21215
+ document.getElementById(`${modalId}-maximize`)?.addEventListener("click", async () => {
21216
+ container.__isMaximized = !container.__isMaximized;
21217
+ state.dateRangePicker = null;
21218
+ renderModal2(container, state, modalId);
21219
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21220
+ drawComparisonChart(modalId, state);
21221
+ }
21222
+ await setupEventListeners2(container, state, modalId, onClose);
21223
+ });
21224
+ const periodBtn = document.getElementById(`${modalId}-period-btn`);
21225
+ const periodDropdown = document.getElementById(`${modalId}-period-dropdown`);
21226
+ periodBtn?.addEventListener("click", (e) => {
21227
+ e.stopPropagation();
21228
+ if (periodDropdown) {
21229
+ periodDropdown.style.display = periodDropdown.style.display === "none" ? "block" : "none";
21230
+ }
21231
+ });
21232
+ document.addEventListener("click", (e) => {
21233
+ if (periodDropdown && !periodDropdown.contains(e.target) && e.target !== periodBtn) {
21234
+ periodDropdown.style.display = "none";
21235
+ }
21236
+ });
21237
+ const periodCheckboxes = document.querySelectorAll(`input[name="${modalId}-period"]`);
21238
+ periodCheckboxes.forEach((checkbox) => {
21239
+ checkbox.addEventListener("change", () => {
21240
+ const checked = Array.from(periodCheckboxes).filter((cb) => cb.checked).map((cb) => cb.value);
21241
+ state.selectedPeriods = checked;
21242
+ const btnLabel = periodBtn?.querySelector("span:first-child");
21243
+ if (btnLabel) {
21244
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
21245
+ }
21246
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21247
+ drawComparisonChart(modalId, state);
21248
+ }
21249
+ });
21250
+ });
21251
+ document.getElementById(`${modalId}-period-select-all`)?.addEventListener("click", () => {
21252
+ periodCheckboxes.forEach((cb) => {
21253
+ cb.checked = true;
21254
+ });
21255
+ state.selectedPeriods = ["madrugada", "manha", "tarde", "noite"];
21256
+ const btnLabel = periodBtn?.querySelector("span:first-child");
21257
+ if (btnLabel) {
21258
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
21259
+ }
21260
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21261
+ drawComparisonChart(modalId, state);
21262
+ }
21263
+ });
21264
+ document.getElementById(`${modalId}-period-clear`)?.addEventListener("click", () => {
21265
+ periodCheckboxes.forEach((cb) => {
21266
+ cb.checked = false;
21267
+ });
21268
+ state.selectedPeriods = [];
21269
+ const btnLabel = periodBtn?.querySelector("span:first-child");
21270
+ if (btnLabel) {
21271
+ btnLabel.textContent = getSelectedPeriodsLabel(state.selectedPeriods);
21272
+ }
21273
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21274
+ drawComparisonChart(modalId, state);
21275
+ }
21276
+ });
21277
+ document.getElementById(`${modalId}-granularity`)?.addEventListener("change", (e) => {
21278
+ state.granularity = e.target.value;
21279
+ localStorage.setItem("myio-temp-comparison-granularity", state.granularity);
21280
+ if (state.deviceData.some((dd) => dd.data.length > 0)) {
21281
+ drawComparisonChart(modalId, state);
21282
+ }
21283
+ });
21284
+ document.getElementById(`${modalId}-query`)?.addEventListener("click", async () => {
21285
+ if (state.startTs >= state.endTs) {
21286
+ alert("Por favor, selecione um per\xEDodo v\xE1lido");
21287
+ return;
21288
+ }
21289
+ state.isLoading = true;
21290
+ state.dateRangePicker = null;
21291
+ renderModal2(container, state, modalId);
21292
+ await fetchAllDevicesData(state);
21293
+ renderModal2(container, state, modalId);
21294
+ drawComparisonChart(modalId, state);
21295
+ await setupEventListeners2(container, state, modalId, onClose);
21296
+ });
21297
+ document.getElementById(`${modalId}-export`)?.addEventListener("click", () => {
21298
+ if (state.deviceData.every((dd) => dd.data.length === 0)) return;
21299
+ exportComparisonCSV(state);
21300
+ });
21301
+ }
21302
+ function exportComparisonCSV(state) {
21303
+ const startDateStr = new Date(state.startTs).toLocaleDateString(state.locale).replace(/\//g, "-");
21304
+ const endDateStr = new Date(state.endTs).toLocaleDateString(state.locale).replace(/\//g, "-");
21305
+ const BOM = "\uFEFF";
21306
+ let csvContent = BOM;
21307
+ csvContent += `Compara\xE7\xE3o de Temperatura
21308
+ `;
21309
+ csvContent += `Per\xEDodo: ${startDateStr} at\xE9 ${endDateStr}
21310
+ `;
21311
+ csvContent += `Sensores: ${state.devices.map((d) => d.label).join(", ")}
21312
+ `;
21313
+ csvContent += "\n";
21314
+ csvContent += "Estat\xEDsticas por Sensor:\n";
21315
+ csvContent += "Sensor,M\xE9dia (\xB0C),Min (\xB0C),Max (\xB0C),Leituras\n";
21316
+ state.deviceData.forEach((dd) => {
21317
+ csvContent += `"${dd.device.label}",${dd.stats.avg.toFixed(2)},${dd.stats.min.toFixed(2)},${dd.stats.max.toFixed(2)},${dd.stats.count}
21318
+ `;
21319
+ });
21320
+ csvContent += "\n";
21321
+ csvContent += "Dados Detalhados:\n";
21322
+ csvContent += "Data/Hora,Sensor,Temperatura (\xB0C)\n";
21323
+ state.deviceData.forEach((dd) => {
21324
+ dd.data.forEach((item) => {
21325
+ const date = new Date(item.ts).toLocaleString(state.locale);
21326
+ const temp = Number(item.value).toFixed(2);
21327
+ csvContent += `"${date}","${dd.device.label}",${temp}
21328
+ `;
21329
+ });
21330
+ });
21331
+ const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
21332
+ const url = URL.createObjectURL(blob);
21333
+ const link = document.createElement("a");
21334
+ link.href = url;
21335
+ link.download = `comparacao_temperatura_${startDateStr}_${endDateStr}.csv`;
21336
+ document.body.appendChild(link);
21337
+ link.click();
21338
+ document.body.removeChild(link);
21339
+ URL.revokeObjectURL(url);
21340
+ }
21341
+
21342
+ // src/components/temperature/TemperatureSettingsModal.ts
21343
+ var DARK_THEME2 = {
21344
+ modalBg: "linear-gradient(180deg, #1e1e2e 0%, #151521 100%)",
21345
+ headerBg: "#3e1a7d",
21346
+ textPrimary: "#ffffff",
21347
+ textSecondary: "rgba(255, 255, 255, 0.7)",
21348
+ textMuted: "rgba(255, 255, 255, 0.5)",
21349
+ inputBg: "rgba(255, 255, 255, 0.08)",
21350
+ inputBorder: "rgba(255, 255, 255, 0.2)",
21351
+ inputText: "#ffffff",
21352
+ buttonPrimary: "#3e1a7d",
21353
+ buttonPrimaryHover: "#5a2da8",
21354
+ buttonSecondary: "rgba(255, 255, 255, 0.1)",
21355
+ success: "#4CAF50",
21356
+ error: "#f44336",
21357
+ overlay: "rgba(0, 0, 0, 0.85)"
21358
+ };
21359
+ var LIGHT_THEME2 = {
21360
+ modalBg: "#ffffff",
21361
+ headerBg: "#3e1a7d",
21362
+ textPrimary: "#1a1a2e",
21363
+ textSecondary: "rgba(0, 0, 0, 0.7)",
21364
+ textMuted: "rgba(0, 0, 0, 0.5)",
21365
+ inputBg: "#f5f5f5",
21366
+ inputBorder: "rgba(0, 0, 0, 0.2)",
21367
+ inputText: "#1a1a2e",
21368
+ buttonPrimary: "#3e1a7d",
21369
+ buttonPrimaryHover: "#5a2da8",
21370
+ buttonSecondary: "rgba(0, 0, 0, 0.05)",
21371
+ success: "#4CAF50",
21372
+ error: "#f44336",
21373
+ overlay: "rgba(0, 0, 0, 0.5)"
21374
+ };
21375
+ function getColors(theme) {
21376
+ return theme === "dark" ? DARK_THEME2 : LIGHT_THEME2;
21377
+ }
21378
+ async function fetchCustomerAttributes(customerId, token) {
21379
+ const url = `/api/plugins/telemetry/CUSTOMER/${customerId}/values/attributes/SERVER_SCOPE`;
21380
+ const response = await fetch(url, {
21381
+ method: "GET",
21382
+ headers: {
21383
+ "Content-Type": "application/json",
21384
+ "X-Authorization": `Bearer ${token}`
21385
+ }
21386
+ });
21387
+ if (!response.ok) {
21388
+ if (response.status === 404 || response.status === 400) {
21389
+ return { minTemperature: null, maxTemperature: null };
21390
+ }
21391
+ throw new Error(`Failed to fetch attributes: ${response.status}`);
21392
+ }
21393
+ const attributes = await response.json();
21394
+ let minTemperature = null;
21395
+ let maxTemperature = null;
21396
+ if (Array.isArray(attributes)) {
21397
+ for (const attr of attributes) {
21398
+ if (attr.key === "minTemperature") {
21399
+ minTemperature = Number(attr.value);
21400
+ } else if (attr.key === "maxTemperature") {
21401
+ maxTemperature = Number(attr.value);
21402
+ }
21403
+ }
21404
+ }
21405
+ return { minTemperature, maxTemperature };
21406
+ }
21407
+ async function saveCustomerAttributes(customerId, token, minTemperature, maxTemperature) {
21408
+ const url = `/api/plugins/telemetry/CUSTOMER/${customerId}/SERVER_SCOPE`;
21409
+ const attributes = {
21410
+ minTemperature,
21411
+ maxTemperature
21412
+ };
21413
+ const response = await fetch(url, {
21414
+ method: "POST",
21415
+ headers: {
21416
+ "Content-Type": "application/json",
21417
+ "X-Authorization": `Bearer ${token}`
21418
+ },
21419
+ body: JSON.stringify(attributes)
21420
+ });
21421
+ if (!response.ok) {
21422
+ throw new Error(`Failed to save attributes: ${response.status}`);
21423
+ }
21424
+ }
21425
+ function renderModal3(container, state, modalId, onClose, onSave) {
21426
+ const colors = getColors(state.theme);
21427
+ const minValue = state.minTemperature !== null ? state.minTemperature : "";
21428
+ const maxValue = state.maxTemperature !== null ? state.maxTemperature : "";
21429
+ container.innerHTML = `
21430
+ <style>
21431
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
21432
+ @keyframes slideIn { from { transform: translateY(-20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
21433
+ @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
21434
+
21435
+ #${modalId} {
21436
+ position: fixed;
21437
+ top: 0;
21438
+ left: 0;
21439
+ width: 100%;
21440
+ height: 100%;
21441
+ background: ${colors.overlay};
21442
+ z-index: 10000;
21443
+ display: flex;
21444
+ align-items: center;
21445
+ justify-content: center;
21446
+ animation: fadeIn 0.2s ease-out;
21447
+ }
21448
+
21449
+ #${modalId} .modal-content {
21450
+ background: ${colors.modalBg};
21451
+ border-radius: 16px;
21452
+ width: 90%;
21453
+ max-width: 480px;
21454
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
21455
+ border: 1px solid rgba(255, 255, 255, 0.1);
21456
+ animation: slideIn 0.3s ease-out;
21457
+ overflow: hidden;
21458
+ }
21459
+
21460
+ #${modalId} .modal-header {
21461
+ background: ${colors.headerBg};
21462
+ padding: 20px 24px;
21463
+ display: flex;
21464
+ align-items: center;
21465
+ justify-content: space-between;
21466
+ }
21467
+
21468
+ #${modalId} .modal-title {
21469
+ margin: 0;
21470
+ font-size: 18px;
21471
+ font-weight: 600;
21472
+ color: #fff;
21473
+ font-family: 'Roboto', sans-serif;
21474
+ display: flex;
21475
+ align-items: center;
21476
+ gap: 10px;
21477
+ }
21478
+
21479
+ #${modalId} .close-btn {
21480
+ width: 32px;
21481
+ height: 32px;
21482
+ background: rgba(255, 255, 255, 0.1);
21483
+ border: 1px solid rgba(255, 255, 255, 0.2);
21484
+ border-radius: 8px;
21485
+ cursor: pointer;
21486
+ display: flex;
21487
+ align-items: center;
21488
+ justify-content: center;
21489
+ transition: all 0.2s;
21490
+ color: #fff;
21491
+ font-size: 18px;
21492
+ }
21493
+
21494
+ #${modalId} .close-btn:hover {
21495
+ background: rgba(255, 68, 68, 0.25);
21496
+ border-color: rgba(255, 68, 68, 0.5);
21497
+ }
21498
+
21499
+ #${modalId} .modal-body {
21500
+ padding: 24px;
21501
+ }
21502
+
21503
+ #${modalId} .customer-info {
21504
+ margin-bottom: 24px;
21505
+ padding: 12px 16px;
21506
+ background: ${colors.inputBg};
21507
+ border-radius: 8px;
21508
+ border: 1px solid ${colors.inputBorder};
21509
+ }
21510
+
21511
+ #${modalId} .customer-label {
21512
+ font-size: 12px;
21513
+ color: ${colors.textMuted};
21514
+ margin-bottom: 4px;
21515
+ }
21516
+
21517
+ #${modalId} .customer-name {
21518
+ font-size: 16px;
21519
+ font-weight: 500;
21520
+ color: ${colors.textPrimary};
21521
+ }
21522
+
21523
+ #${modalId} .form-group {
21524
+ margin-bottom: 20px;
21525
+ }
21526
+
21527
+ #${modalId} .form-label {
21528
+ display: block;
21529
+ font-size: 14px;
21530
+ font-weight: 500;
21531
+ color: ${colors.textSecondary};
21532
+ margin-bottom: 8px;
21533
+ }
21534
+
21535
+ #${modalId} .form-input {
21536
+ width: 100%;
21537
+ padding: 12px 16px;
21538
+ font-size: 16px;
21539
+ background: ${colors.inputBg};
21540
+ border: 1px solid ${colors.inputBorder};
21541
+ border-radius: 8px;
21542
+ color: ${colors.inputText};
21543
+ outline: none;
21544
+ transition: border-color 0.2s;
21545
+ box-sizing: border-box;
21546
+ }
21547
+
21548
+ #${modalId} .form-input:focus {
21549
+ border-color: ${colors.buttonPrimary};
21550
+ }
21551
+
21552
+ #${modalId} .form-input::placeholder {
21553
+ color: ${colors.textMuted};
21554
+ }
21555
+
21556
+ #${modalId} .form-hint {
21557
+ font-size: 12px;
21558
+ color: ${colors.textMuted};
21559
+ margin-top: 6px;
21560
+ }
21561
+
21562
+ #${modalId} .temperature-range {
21563
+ display: grid;
21564
+ grid-template-columns: 1fr 1fr;
21565
+ gap: 16px;
21566
+ }
21567
+
21568
+ #${modalId} .range-preview {
21569
+ margin-top: 20px;
21570
+ padding: 16px;
21571
+ background: rgba(76, 175, 80, 0.1);
21572
+ border: 1px dashed ${colors.success};
21573
+ border-radius: 8px;
21574
+ text-align: center;
21575
+ }
21576
+
21577
+ #${modalId} .range-preview-label {
21578
+ font-size: 12px;
21579
+ color: ${colors.textMuted};
21580
+ margin-bottom: 8px;
21581
+ }
21582
+
21583
+ #${modalId} .range-preview-value {
21584
+ font-size: 24px;
21585
+ font-weight: 600;
21586
+ color: ${colors.success};
21587
+ }
21588
+
21589
+ #${modalId} .modal-footer {
21590
+ padding: 16px 24px;
21591
+ border-top: 1px solid ${colors.inputBorder};
21592
+ display: flex;
21593
+ justify-content: flex-end;
21594
+ gap: 12px;
21595
+ }
21596
+
21597
+ #${modalId} .btn {
21598
+ padding: 10px 24px;
21599
+ font-size: 14px;
21600
+ font-weight: 500;
21601
+ border-radius: 8px;
21602
+ cursor: pointer;
21603
+ transition: all 0.2s;
21604
+ border: none;
21605
+ display: flex;
21606
+ align-items: center;
21607
+ gap: 8px;
21608
+ }
21609
+
21610
+ #${modalId} .btn-secondary {
21611
+ background: ${colors.buttonSecondary};
21612
+ color: ${colors.textSecondary};
21613
+ border: 1px solid ${colors.inputBorder};
21614
+ }
21615
+
21616
+ #${modalId} .btn-secondary:hover {
21617
+ background: ${colors.inputBg};
21618
+ }
21619
+
21620
+ #${modalId} .btn-primary {
21621
+ background: ${colors.buttonPrimary};
21622
+ color: #fff;
21623
+ }
21624
+
21625
+ #${modalId} .btn-primary:hover {
21626
+ background: ${colors.buttonPrimaryHover};
21627
+ }
21628
+
21629
+ #${modalId} .btn-primary:disabled {
21630
+ opacity: 0.6;
21631
+ cursor: not-allowed;
21632
+ }
21633
+
21634
+ #${modalId} .spinner {
21635
+ width: 16px;
21636
+ height: 16px;
21637
+ border: 2px solid rgba(255,255,255,0.3);
21638
+ border-top-color: #fff;
21639
+ border-radius: 50%;
21640
+ animation: spin 1s linear infinite;
21641
+ }
21642
+
21643
+ #${modalId} .message {
21644
+ padding: 12px 16px;
21645
+ border-radius: 8px;
21646
+ margin-bottom: 16px;
21647
+ font-size: 14px;
21648
+ }
21649
+
21650
+ #${modalId} .message-error {
21651
+ background: rgba(244, 67, 54, 0.1);
21652
+ border: 1px solid ${colors.error};
21653
+ color: ${colors.error};
21654
+ }
21655
+
21656
+ #${modalId} .message-success {
21657
+ background: rgba(76, 175, 80, 0.1);
21658
+ border: 1px solid ${colors.success};
21659
+ color: ${colors.success};
21660
+ }
21661
+
21662
+ #${modalId} .loading-overlay {
21663
+ display: flex;
21664
+ flex-direction: column;
21665
+ align-items: center;
21666
+ justify-content: center;
21667
+ padding: 48px;
21668
+ color: ${colors.textSecondary};
21669
+ }
21670
+
21671
+ #${modalId} .loading-spinner {
21672
+ width: 40px;
21673
+ height: 40px;
21674
+ border: 3px solid ${colors.inputBorder};
21675
+ border-top-color: ${colors.buttonPrimary};
21676
+ border-radius: 50%;
21677
+ animation: spin 1s linear infinite;
21678
+ margin-bottom: 16px;
21679
+ }
21680
+ </style>
21681
+
21682
+ <div id="${modalId}" class="modal-overlay">
21683
+ <div class="modal-content">
21684
+ <div class="modal-header">
21685
+ <h2 class="modal-title">
21686
+ <span>\u{1F321}\uFE0F</span>
21687
+ Configurar Temperatura
21688
+ </h2>
21689
+ <button class="close-btn" id="${modalId}-close">&times;</button>
21690
+ </div>
21691
+
21692
+ <div class="modal-body">
21693
+ ${state.isLoading ? `
21694
+ <div class="loading-overlay">
21695
+ <div class="loading-spinner"></div>
21696
+ <div>Carregando configura\xE7\xF5es...</div>
21697
+ </div>
21698
+ ` : `
21699
+ ${state.error ? `
21700
+ <div class="message message-error">${state.error}</div>
21701
+ ` : ""}
21702
+
21703
+ ${state.successMessage ? `
21704
+ <div class="message message-success">${state.successMessage}</div>
21705
+ ` : ""}
21706
+
21707
+ <div class="customer-info">
21708
+ <div class="customer-label">Shopping / Cliente</div>
21709
+ <div class="customer-name">${state.customerName || "N\xE3o identificado"}</div>
21710
+ </div>
21711
+
21712
+ <div class="form-group">
21713
+ <label class="form-label">Faixa de Temperatura Ideal</label>
21714
+ <div class="temperature-range">
21715
+ <div>
21716
+ <input
21717
+ type="number"
21718
+ id="${modalId}-min"
21719
+ class="form-input"
21720
+ placeholder="M\xEDnima"
21721
+ value="${minValue}"
21722
+ step="0.5"
21723
+ min="0"
21724
+ max="50"
21725
+ />
21726
+ <div class="form-hint">Temperatura m\xEDnima (\xB0C)</div>
21727
+ </div>
21728
+ <div>
21729
+ <input
21730
+ type="number"
21731
+ id="${modalId}-max"
21732
+ class="form-input"
21733
+ placeholder="M\xE1xima"
21734
+ value="${maxValue}"
21735
+ step="0.5"
21736
+ min="0"
21737
+ max="50"
21738
+ />
21739
+ <div class="form-hint">Temperatura m\xE1xima (\xB0C)</div>
21740
+ </div>
21741
+ </div>
21742
+ </div>
21743
+
21744
+ <div class="range-preview" id="${modalId}-preview">
21745
+ <div class="range-preview-label">Faixa configurada</div>
21746
+ <div class="range-preview-value" id="${modalId}-preview-value">
21747
+ ${minValue && maxValue ? `${minValue}\xB0C - ${maxValue}\xB0C` : "N\xE3o definida"}
21748
+ </div>
21749
+ </div>
21750
+ `}
21751
+ </div>
21752
+
21753
+ ${!state.isLoading ? `
21754
+ <div class="modal-footer">
21755
+ <button class="btn btn-secondary" id="${modalId}-cancel">Cancelar</button>
21756
+ <button class="btn btn-primary" id="${modalId}-save" ${state.isSaving ? "disabled" : ""}>
21757
+ ${state.isSaving ? '<div class="spinner"></div> Salvando...' : "Salvar"}
21758
+ </button>
21759
+ </div>
21760
+ ` : ""}
21761
+ </div>
21762
+ </div>
21763
+ `;
21764
+ const closeBtn = document.getElementById(`${modalId}-close`);
21765
+ const cancelBtn = document.getElementById(`${modalId}-cancel`);
21766
+ const saveBtn = document.getElementById(`${modalId}-save`);
21767
+ const minInput = document.getElementById(`${modalId}-min`);
21768
+ const maxInput = document.getElementById(`${modalId}-max`);
21769
+ const previewValue = document.getElementById(`${modalId}-preview-value`);
21770
+ const overlay = document.getElementById(modalId);
21771
+ closeBtn?.addEventListener("click", onClose);
21772
+ cancelBtn?.addEventListener("click", onClose);
21773
+ overlay?.addEventListener("click", (e) => {
21774
+ if (e.target === overlay) onClose();
21775
+ });
21776
+ const updatePreview = () => {
21777
+ if (previewValue && minInput && maxInput) {
21778
+ const min = minInput.value;
21779
+ const max = maxInput.value;
21780
+ if (min && max) {
21781
+ previewValue.textContent = `${min}\xB0C - ${max}\xB0C`;
21782
+ } else {
21783
+ previewValue.textContent = "N\xE3o definida";
21784
+ }
21785
+ }
21786
+ };
21787
+ minInput?.addEventListener("input", updatePreview);
21788
+ maxInput?.addEventListener("input", updatePreview);
21789
+ saveBtn?.addEventListener("click", async () => {
21790
+ if (!minInput || !maxInput) return;
21791
+ const min = parseFloat(minInput.value);
21792
+ const max = parseFloat(maxInput.value);
21793
+ if (isNaN(min) || isNaN(max)) {
21794
+ state.error = "Por favor, preencha ambos os valores.";
21795
+ renderModal3(container, state, modalId, onClose, onSave);
21796
+ return;
21797
+ }
21798
+ if (min >= max) {
21799
+ state.error = "A temperatura m\xEDnima deve ser menor que a m\xE1xima.";
21800
+ renderModal3(container, state, modalId, onClose, onSave);
21801
+ return;
21802
+ }
21803
+ if (min < 0 || max > 50) {
21804
+ state.error = "Os valores devem estar entre 0\xB0C e 50\xB0C.";
21805
+ renderModal3(container, state, modalId, onClose, onSave);
21806
+ return;
21807
+ }
21808
+ await onSave(min, max);
21809
+ });
21810
+ }
21811
+ function openTemperatureSettingsModal(params) {
21812
+ const modalId = `myio-temp-settings-${Date.now()}`;
21813
+ const state = {
21814
+ customerId: params.customerId,
21815
+ customerName: params.customerName || "",
21816
+ token: params.token,
21817
+ theme: params.theme || "dark",
21818
+ minTemperature: null,
21819
+ maxTemperature: null,
21820
+ isLoading: true,
21821
+ isSaving: false,
21822
+ error: null,
21823
+ successMessage: null
21824
+ };
21825
+ const container = document.createElement("div");
21826
+ container.id = `${modalId}-container`;
21827
+ document.body.appendChild(container);
21828
+ const destroy = () => {
21829
+ container.remove();
21830
+ params.onClose?.();
21831
+ };
21832
+ const handleSave = async (min, max) => {
21833
+ state.isSaving = true;
21834
+ state.error = null;
21835
+ state.successMessage = null;
21836
+ renderModal3(container, state, modalId, destroy, handleSave);
21837
+ try {
21838
+ await saveCustomerAttributes(state.customerId, state.token, min, max);
21839
+ state.minTemperature = min;
21840
+ state.maxTemperature = max;
21841
+ state.isSaving = false;
21842
+ state.successMessage = "Configura\xE7\xF5es salvas com sucesso!";
21843
+ renderModal3(container, state, modalId, destroy, handleSave);
21844
+ params.onSave?.({ minTemperature: min, maxTemperature: max });
21845
+ setTimeout(() => {
21846
+ destroy();
21847
+ }, 1500);
21848
+ } catch (error) {
21849
+ state.isSaving = false;
21850
+ state.error = `Erro ao salvar: ${error.message}`;
21851
+ renderModal3(container, state, modalId, destroy, handleSave);
21852
+ }
21853
+ };
21854
+ renderModal3(container, state, modalId, destroy, handleSave);
21855
+ fetchCustomerAttributes(state.customerId, state.token).then(({ minTemperature, maxTemperature }) => {
21856
+ state.minTemperature = minTemperature;
21857
+ state.maxTemperature = maxTemperature;
21858
+ state.isLoading = false;
21859
+ renderModal3(container, state, modalId, destroy, handleSave);
21860
+ }).catch((error) => {
21861
+ state.isLoading = false;
21862
+ state.error = `Erro ao carregar: ${error.message}`;
21863
+ renderModal3(container, state, modalId, destroy, handleSave);
21864
+ });
21865
+ return { destroy };
21866
+ }
19545
21867
  export {
21868
+ CHART_COLORS,
19546
21869
  ConnectionStatusType,
21870
+ DEFAULT_CLAMP_RANGE,
19547
21871
  DeviceStatusType,
19548
21872
  MyIOChartModal,
19549
21873
  MyIODraggableCard,
@@ -19552,6 +21876,7 @@ export {
19552
21876
  MyIOToast,
19553
21877
  addDetectionContext,
19554
21878
  addNamespace,
21879
+ aggregateByDay,
19555
21880
  averageByDay,
19556
21881
  buildListItemsThingsboardByUniqueDatasource,
19557
21882
  buildMyioIngestionAuth,
@@ -19560,6 +21885,8 @@ export {
19560
21885
  calcDeltaPercent,
19561
21886
  calculateDeviceStatus,
19562
21887
  calculateDeviceStatusWithRanges,
21888
+ calculateStats,
21889
+ clampTemperature,
19563
21890
  classify,
19564
21891
  classifyWaterLabel,
19565
21892
  classifyWaterLabels,
@@ -19572,9 +21899,11 @@ export {
19572
21899
  detectDeviceType,
19573
21900
  determineInterval,
19574
21901
  deviceStatusIcons,
21902
+ exportTemperatureCSV,
19575
21903
  exportToCSV,
19576
21904
  exportToCSVAll,
19577
21905
  extractMyIOCredentials,
21906
+ fetchTemperatureData,
19578
21907
  fetchThingsboardCustomerAttrsFromStorage,
19579
21908
  fetchThingsboardCustomerServerScopeAttrs,
19580
21909
  findValue,
@@ -19588,6 +21917,7 @@ export {
19588
21917
  formatEnergy,
19589
21918
  formatNumberReadable,
19590
21919
  formatTankHeadFromCm,
21920
+ formatTemperature,
19591
21921
  formatWaterByGroup,
19592
21922
  formatWaterVolumeM3,
19593
21923
  getAuthCacheStats,
@@ -19602,6 +21932,7 @@ export {
19602
21932
  getValueByDatakeyLegacy,
19603
21933
  getWaterCategories,
19604
21934
  groupByDay,
21935
+ interpolateTemperature,
19605
21936
  isDeviceOffline,
19606
21937
  isValidConnectionStatus,
19607
21938
  isValidDeviceStatus,
@@ -19619,6 +21950,9 @@ export {
19619
21950
  openDemandModal,
19620
21951
  openGoalsPanel,
19621
21952
  openRealTimeTelemetryModal,
21953
+ openTemperatureComparisonModal,
21954
+ openTemperatureModal,
21955
+ openTemperatureSettingsModal,
19622
21956
  parseInputDateToDate,
19623
21957
  renderCardComponent,
19624
21958
  renderCardComponent2 as renderCardComponentEnhanced,