<template>
  <div>

    <div class="row">
      <!--   left contents   -->
      <div class="col-8" style="padding-right: 12px">
        <div class="row">
          <div class="col-4">
            <card type="chart">
              <img src="../../public/img/smaple_image01.png" alt="sample_img">
              <!--              <img src="http://localhost:5001/stream" alt="sample_img" style="height: 100%">-->
            </card>
          </div>
          <div class="col-4">
            <card type="chart">
              <template slot="header">
                <h5 class="chart-title">Co2(ppm)</h5>
              </template>              <!--      co2 chart        -->
              <div class="chart-area">
                <line-chart style="height: 100%"
                            ref="co2Chart"
                            chart-id="co2Chart"
                            :chart-data="co2Chart.chartData"
                            :gradient-colors="co2Chart.gradientColors"
                            :gradient-stops="co2Chart.gradientStops"
                            :extra-options="co2Chart.extraOptions">
                </line-chart>
              </div>
            </card>
          </div>
          <div class="col-4">
            <card type="chart">
              <template slot="header">
                <h5 class="chart-title">TvOC(ppb)</h5>
              </template>
              <!--       tvoc chart       -->
              <div class="chart-area">
                <line-chart style="height: 100%"
                            ref="tvocChart"
                            chart-id="tvocChart"
                            :chart-data="tvocChart.chartData"
                            :gradient-colors="tvocChart.gradientColors"
                            :gradient-stops="tvocChart.gradientStops"
                            :extra-options="tvocChart.extraOptions">
                </line-chart>
              </div>
            </card>
          </div>
        </div>
        <div class="row">
          <!--    doughnut chart      -->
          <div class="col-3">
            <card type="chart">
              <h5 class="chart-title">Humidity</h5>
              <div class="chart-area">
                <h3 class="doughnut-value">{{ doughnutChart.chartData.datasets[0]['data'][0] }}%</h3>
                <doughnut-chart style="height: 80%"
                                chart-id="hum-chart"
                                :chart-data="doughnutChart.chartData"
                                :extra-options="doughnutChart.extraOptions"
                ></doughnut-chart>
              </div>
            </card>
          </div>
          <div class="col-3">
            <card type="chart">
              <h5 class="chart-title">Battery</h5>
              <div class="chart-area">
                <h3 class="doughnut-value">{{ doughnutChart.soilChartData.datasets[0]['data'][0] }}%</h3>
                <doughnut-chart style="height: 80%"
                                chart-id="soil-chart"
                                :chart-data="doughnutChart.soilChartData"
                                :gradient-colors="doughnutChart.gradientColors"
                                :extra-options="doughnutChart.extraOptions"
                                :gradient-stops="doughnutChart.gradientStops">

                </doughnut-chart>
              </div>
            </card>
          </div>
          <!--     air pollution chart     -->
          <div class="col-6">
            <card type="chart">
              <h5 class="chart-title">Air pollution(㎥)</h5>
              <div class="chart-area">
                <line-chart style="height: 100%"
                            chart-id="green-line-chart"
                            :chart-data="greenLineChart.chartData"
                            :gradient-stops="greenLineChart.gradientStops"
                            :extra-options="greenLineChart.extraOptions">
                </line-chart>
              </div>
            </card>
          </div>
        </div>
        <div class="row">
          <div class="col-12">
            <card type="chart">
              <h5 class="chart-title">All Temperature(°C)</h5>
              <div class="chart-area">
                <line-chart style="height: 100%"
                            ref="bigChart"
                            chart-id="big-line-chart"
                            :chart-data="bigLineChart.chartData"
                            :gradient-colors="bigLineChart.gradientColors"
                            :gradient-stops="bigLineChart.gradientStops"
                            :extra-options="bigLineChart.extraOptions">
                </line-chart>
              </div>
            </card>
          </div>
        </div>
      </div>
      <!--   right contents   -->
      <div class="col-4">
        <card style="margin-left: 1px">
          <template slot="header">
            <h5 class="card-category">Information sensor data</h5>
            <h3 class="card-title"><strong>Case A</strong> : Info</h3>
          </template>
          <base-alert type="default" style="background-color: rgba(10,10,22,0.4); padding: 20px 0 20px 40px;">
            <div class="row">
              <div class="col-3 data-view">
                Temp :<br/>
                <i class="fa-solid fa-temperature-half fa-xl"></i>
                <p class="h4 data-value">22.8 °C</p>
              </div>
              <div class="col-3 data-view">
                OutDoor-Temp :<br/>
                <i class="fa-solid fa-temperature-low fa-xl"></i>
                <p class="h4 data-value">6.3 °C</p>
              </div>
              <div class="col-3 data-view">
                Humidity :<br/>
                <i class="fa-solid fa-droplet fa-xl"></i>
                <p class="h4 data-value">63%</p>
              </div>
              <div class="col-3 data-view">
                Soil-hum :<br/>
                <i class="fa-solid fa-glass-water-droplet fa-xl"></i>
                <p class="h4 data-value">87%</p>
              </div>
            </div>
            <div class="row toggle-group">
              <div class="col-6">
                <i class="fa-solid fa-fan fa-2xl toggle-icon"></i>
                <toggle-switch :category="controlDevice[0]" :fanState="fanState" @toggled="onToggled"/>
              </div>
              <div class="col-6">
                <i class="fa-regular fa-lightbulb fa-2xl toggle-icon"></i>
                <toggle-switch :category="controlDevice[1]" :uvState="uvState" @toggled="onToggled"/>
              </div>
              <div class="col-6" style="margin-top: 15px">
                <i class="fa-solid fa-lock fa-2xl toggle-icon"></i>
                <toggle-switch :category="controlDevice[2]" @toggled="onToggled"></toggle-switch>
              </div>
              <div class="col-6" style="margin-top: 15px">
                <i class="fa-solid fa-wind fa-xl toggle-icon"></i>
                <toggle-switch :category="controlDevice[3]" @toggled="onToggled"></toggle-switch>
              </div>
            </div>
          </base-alert>
          <div class="mt-30">
            <h5 class="card-category">check the system log</h5>
            <h3 class="card-title"><strong>Case A</strong> : System Log</h3>
          </div>
          <user-table></user-table>
        </card>
      </div>
    </div>

  </div>
</template>
<script>
import LineChart from '@/components/Charts/LineChart';
import BarChart from '@/components/Charts/BarChart';
import * as chartConfigs from '@/components/Charts/config';
import TaskList from './Dashboard/TaskList';
import UserTable from './Dashboard/UserTable';
import config from '@/config';
import BaseAlert from "@/components/BaseAlert.vue";
import ToggleSwitch from "@/components/ToggleSwitch.vue";
import DoughnutChart from "@/components/Charts/DoughnutChart";

const sampleData = require('../assets/data/sample_weather_data.json');

export default {
  components: {
    DoughnutChart,
    ToggleSwitch,
    BaseAlert,
    LineChart,
    BarChart,
    TaskList,
    UserTable
  },
  data() {
    return {
      controlDevice: ['Fan', 'UV', 'Lock', 'Etc'],
      checked: false,
      chartIndex: 0,
      bigLineChart: {},
      greenLineChart: {},
      co2Chart: {},
      tvocChart: {},
      pct: {},
      humi: {},
      fanState: "off",
      uvState: "off",
      doughnutChart: {
        extraOptions: chartConfigs.doughnutChartOption,
        chartData: {
          labels: ['data', ''],
          datasets: [{
            data: [0, 100],
            backgroundColor: ['#1d8cf8', '#151528'],
            borderWidth: 0,
          }]
        },
        soilChartData: {
          // labels: ['data', ''],
          labels: ['Battery', 'Remaining'],
          datasets: [{
            data: [0, 100],
            backgroundColor: ['#1d8cf8', '#151528'],
            borderWidth: 0,
          }]
        }
      },
      blueBarChart: {
        extraOptions: chartConfigs.barChartOptions,
        chartData: {
          labels: ['PM1.0', 'PM2.5', 'PM10'],
          datasets: [{
            label: "Countries",
            fill: 'start',
            borderColor: config.colors.info,
            borderWidth: 2,
            borderDash: [],
            borderDashOffset: 0.0,
            data: [6, 9, 11],
          }]
        },
        gradientColors: config.colors.primaryGradient,
        gradientStops: [1, 0.4, 0],
      }
    }
  },
  computed: {},
  methods: {
    async getData() {
      // 배터리, 습도데이터 가져오기
      try {
        const API_BASE = (process && process.env && process.env.VUE_APP_MODBUS_API)
          ? process.env.VUE_APP_MODBUS_API
          : `${window.location.protocol}//${window.location.hostname}:8182`;
        const saved = localStorage.getItem('modbusTarget');
        const fallbackTarget = "*";
        const TARGET = (process && process.env && process.env.VUE_APP_MODBUS_TARGET)
          ? process.env.VUE_APP_MODBUS_TARGET
          : (saved || fallbackTarget);

        const res = await fetch(`${API_BASE}/timeseries/get`, {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({target: TARGET, limit: 1})
        });
        if (!res.ok) {
          const txt = await res.text();
          throw new Error(txt || ('HTTP ' + res.status));
        }
        const j = await res.json();
        const last = (j && j.samples && j.samples.length) ? j.samples[j.samples.length - 1] : null;
        const pctRaw = Number(last && (last.batt_pct ?? last.battery ?? last.batt));
        const humiRaw = Number(last && (last.humi ?? last.humi ?? last.humi));
        const fanRaw = Number(last && (last.fan_state ?? last.fan_state ?? last.fan_state));
        const uvRaw = Number(last && (last.uv_state ?? last.uv_state ?? last.uv_state));
        this.$data.pct = Math.round(Math.max(0, Math.min(100, isFinite(pctRaw) ? pctRaw : 0)));
        this.$data.humi = Math.round(Math.max(0, Math.min(100, isFinite(humiRaw) ? humiRaw : 0)));
        this.$data.fanState = (fanRaw === 1) ? "on" : "off";
        this.$data.uvState = (uvRaw === 1) ? "on" : "off";


      } catch (err) {
        console.error('initDoughnutChart battery update failed:', err);
      }
    },

    async sendLock(on) {
      const API_BASE = (process && process.env && process.env.VUE_APP_MODBUS_API)
        ? process.env.VUE_APP_MODBUS_API
        : `${window.location.protocol}//${window.location.hostname}:8182`;
      const saved = localStorage.getItem('modbusTarget');
      const fallbackTarget = "*";
      const TARGET = (process && process.env && process.env.VUE_APP_MODBUS_TARGET)
        ? process.env.VUE_APP_MODBUS_TARGET
        : (saved || fallbackTarget);

      // Lock 주소: 22 (요청사항)
      const payload = {target: TARGET, unit: 1, addr: 0x0016, value: on ? 1 : 0};

      const res = await fetch(`${API_BASE}/modbus/write`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(payload)
      });
      if (!res.ok) {
        const text = await res.text();
        throw new Error(text || ('HTTP ' + res.status));
      }
      await res.json().catch(() => ({}));
    },

    async sendFan(on) {
      const API_BASE = (process && process.env && process.env.VUE_APP_MODBUS_API)
        ? process.env.VUE_APP_MODBUS_API
        : `${window.location.protocol}//${window.location.hostname}:8182`;
      const saved = localStorage.getItem('modbusTarget');
      const fallbackTarget = "*";                       // DHCP 대응: 최신 연결 자동
      const TARGET = (process && process.env && process.env.VUE_APP_MODBUS_TARGET)
        ? process.env.VUE_APP_MODBUS_TARGET
        : (saved || fallbackTarget);

      const payload = {target: TARGET, unit: 1, addr: 0x0015, value: on ? 1 : 0}; // FAN=0x0015(21)
      try {
        const res = await fetch(`${API_BASE}/modbus/write`, {
          method: 'POST', headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(payload)
        });
        if (!res.ok) throw new Error(await res.text() || ('HTTP ' + res.status));
        await res.json().catch(() => ({}));
      } catch (err) {
        console.error('FAN control error', err);
        // alert('FAN 제어 실패: ' + (err.message || err));
      }
    },

    async sendUV(on) {
      const API_BASE = (process && process.env && process.env.VUE_APP_MODBUS_API)
        ? process.env.VUE_APP_MODBUS_API
        : `${window.location.protocol}//${window.location.hostname}:8182`;
      const saved = localStorage.getItem('modbusTarget');
      const fallbackTarget = "*";
      const TARGET = (process && process.env && process.env.VUE_APP_MODBUS_TARGET)
        ? process.env.VUE_APP_MODBUS_TARGET
        : (saved || fallbackTarget);

      const payload = {target: TARGET, unit: 1, addr: 0x0014, value: on ? 1 : 0}; // UV=0x0014(20) (환경 다르면 여기만 변경)
      try {
        const res = await fetch(`${API_BASE}/modbus/write`, {
          method: 'POST', headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(payload)
        });
        if (!res.ok) throw new Error(await res.text() || ('HTTP ' + res.status));
        await res.json().catch(() => ({}));
      } catch (err) {
        console.error('UV control error', err);
        // alert('UV 제어 실패: ' + (err.message || err));
      }
    },

    onToggled(ev) {
      if (!ev || !ev.category) {
        return;
      }
      const cat = String(ev.category).toLowerCase();
      if (cat === 'fan') {
        return this.sendFan(!!ev.on);
      }
      if (cat === 'uv') {
        return this.sendUV(!!ev.on);
      }
      if (cat === 'lock') {
        return this.sendLock && this.sendLock(!!ev.on);
      }
    },
    initBigChart(chartIndex) {
      let testTemp = []
      let testTemp2 = []
      let testTemp3 = []
      let index = []
      for (let i = 0 + chartIndex; i <= Object.keys(sampleData).length - 5600 + chartIndex; i++) {
        testTemp.push(sampleData[i].mean_temp)
        testTemp2.push(sampleData[i].ground_temp)
        testTemp3.push(sampleData[i].max_temp)
        index.push(sampleData[i].date)
      }
      let bigLineChart = {
        chartData: {
          labels: index,
          datasets: [{
            fill: false,
            borderColor: config.colors.danger,
            borderWidth: 1,
            borderDash: [0],
            borderDashOffset: 0.0,
            pointRadius: 0,
            label: 'temperature',
            data: testTemp,
          }, {
            fill: false,
            borderColor: config.colors.info,
            borderWidth: 1,
            borderDash: [0],
            borderDashOffset: 0.0,
            pointRadius: 0,
            label: 'ground-temp',
            data: testTemp2,
          }, {
            fill: false,
            borderColor: config.colors.primary,
            borderWidth: 1,
            borderDash: [0],
            borderDashOffset: 0.0,
            pointRadius: 0,
            label: 'outdoor-temp',
            data: testTemp3,
          }],
        },
        extraOptions: chartConfigs.bigChartOptions,
        gradientColors: config.colors.primaryGradient,
        gradientStops: [1, 0.4, 0],
        categories: []
      }
      this.$refs.bigChart.updateGradients(bigLineChart.chartData);
      this.bigLineChart = bigLineChart;
    },
    initAirChart(chartIndex) {
      let testData = []
      let testData2 = []
      let testData3 = []
      let index = []
      for (let i = 0 + chartIndex; i <= Object.keys(sampleData).length - 5700 + chartIndex; i++) {
        testData.push(sampleData[i].max_wind)
        testData2.push(sampleData[i].mean_wind)
        testData3.push(sampleData[i].cloud)
        index.push(sampleData[i].date)
      }
      let chartData = {
        chartData: {
          labels: index,
          datasets: [{
            label: "PM 1.0",
            fill: false,
            borderColor: config.colors.primary,
            borderWidth: 1,
            borderDash: [],
            borderDashOffset: 0.0,
            pointRadius: 0,
            data: testData,
            lineTension: 0,
          }, {
            label: "PM 2.5",
            fill: false,
            borderColor: config.colors.info,
            borderWidth: 1,
            borderDash: [],
            borderDashOffset: 0.0,
            pointRadius: 0,
            data: testData2,
            lineTension: 0,
          }, {
            label: "PM 10",
            fill: false,
            borderColor: config.colors.danger,
            borderWidth: 1,
            borderDash: [],
            borderDashOffset: 0.0,
            pointRadius: 0,
            data: testData3,
            lineTension: 0,
          }]
        },
        extraOptions: chartConfigs.greenChartOptions,
        gradientColors: ['rgba(66,134,121,0.15)', 'rgba(66,134,121,0.0)', 'rgba(66,134,121,0)'],
        gradientStops: [1, 0.4, 0],
      }
      this.greenLineChart = chartData;
    },
    initDoughnutChart() {

      let humi = this.$data.humi;
      let pct = this.$data.pct;

      let doughnutChart = {
        extraOptions: chartConfigs.doughnutChartOption,
        chartData: {
          labels: ['data', ''],
          datasets: [{
            data: [humi, 100 - humi],
            backgroundColor: ['#1d8cf8', '#151528'],
            borderWidth: 0,
          }]
        },
        soilChartData: {
          labels: ['data', ''],
          datasets: [{
            data: [pct, 100 - pct],
            backgroundColor: ['#1d8cf8', '#151528'],
            borderWidth: 0,
          }]
        }
      }
      this.doughnutChart = doughnutChart;
    },
    initCo2Chart(chartIndex) {
      let testData = []
      let index = []
      for (let i = 0 + chartIndex; i <= Object.keys(sampleData).length - 5700 + chartIndex; i++) {
        testData.push(sampleData[i].mean_temp)
        index.push(sampleData[i].date)
      }
      var co2Chart = {
        extraOptions: chartConfigs.purpleChartOptions,
        chartData: {
          labels: index,
          datasets: [{
            label: "Data",
            fill: 'start',
            borderColor: config.colors.teal,
            borderWidth: 1,
            borderDash: [],
            borderDashOffset: 0.0,
            pointRadius: 0,
            data: testData,
            lineTension: 0,
          }]
        },
        gradientColors: ['rgba(66,134,121,0.15)', 'rgba(66,134,121,0.0)', 'rgba(66,134,121,0)'],
        gradientStops: [1, 0.1, 0],
      }
      this.$refs.co2Chart.updateGradients(co2Chart.chartData);
      this.co2Chart = co2Chart;
    },
    initTvocChart(chartIndex) {
      let testData = []
      let index = []
      for (let i = 0 + chartIndex; i <= Object.keys(sampleData).length - 5700 + chartIndex; i++) {
        testData.push(sampleData[i].mean_hum)
        index.push(sampleData[i].date)
      }
      var tvocChart = {
        extraOptions: chartConfigs.purpleChartOptions,
        chartData: {
          labels: index,
          datasets: [{
            label: "Data",
            fill: 'start',
            borderColor: config.colors.teal,
            borderWidth: 1,
            borderDash: [],
            borderDashOffset: 0.0,
            pointRadius: 0,
            data: testData,
            lineTension: 0,
          }]
        },
        gradientColors: ['rgba(66,134,121,0.15)', 'rgba(66,134,121,0.0)', 'rgba(66,134,121,0)'],
        gradientStops: [1, 0.1, 0],
      }
      this.$refs.tvocChart.updateGradients(tvocChart.chartData);
      this.tvocChart = tvocChart;
    },
    initChart() {
      this.getData();
      this.initCo2Chart(this.chartIndex);
      this.initTvocChart(this.chartIndex);
      this.initDoughnutChart();
      this.initAirChart(this.chartIndex);
      this.initBigChart(this.chartIndex);
      this.chartIndex = this.chartIndex + 1;
    }
  },
  mounted() {
    this.initBigChart();
    this.initAirChart()
    setInterval(this.initChart, 2000);
  },
  beforeDestroy() {
  }
};
</script>
<style>
.toggle-group {
  padding-top: 10px;
  padding-bottom: 10px;
}

.toggle-icon {
  padding-left: 10px;
  position: relative;
  bottom: 15px;
}

.data-view {
  font-size: 12px;
}

.data-value {
  padding-top: 14px;
  padding-left: 8px;
  text-align: center;
  display: inline-block;
}

.green-light {
  padding: 10px;
  margin-top: 0;
}

.data-view i {
  margin-left: 15px;
}

.mt-30 {
  margin-top: 30px;
}

.chart-title {
  position: relative;
  left: 10px;
  height: 0;
  font-size: 16px;
}

.col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12 {
  padding: 0 6px;
}

.card {
  margin-bottom: 12px;
}

#hum-chart {
  position: relative;
  bottom: 20px;
}

#soil-chart {
  position: relative;
  bottom: 20px;
}

.doughnut-value {
  display: inline;
  position: relative;
  left: 40%;
  top: 42%;
  font-size: 32px;
}

.card.card-chart {
  height: 17.62rem;
}
</style>
