<template>
  <div id="temperature-container"></div>
</template>

<script setup>
import { nextTick } from 'vue';

async function getData() {
  try {
    const { data: rawData } = await useFetch('/api/datas');
    const { code, msg, data } = rawData.value;
    if (code === 200) {
      await nextTick();
      initChart(data);
    } else {
      throw new Error(msg);
    }
  } catch (error) {
    console.error(error);
  }
}

getData();

// 初始化图表
function initChart(data) {
  const chartDom = document.getElementById('temperature-container');
  const option = initOption(data);
  const myChart = echarts.init(chartDom);
  myChart.setOption(option);
}

function initData(data) {
  console.log('data1: ', data);
  const result = { times: [], roomT: [], outT: [] };
  data.forEach(item => {
    result.times.push(item.time);
    result.roomT.push(item.roomT);
    result.outT.push(item.outT);
  });
  return result;
}

function initOption(data) {
  const { time, roomT, outT } = initData(data);
  return {
    tooltip: {
      trigger: 'axis',
    },
    grid: {
      left: 5,
      right: 5,
      top: 30,
      bottom: 30,
    },
    darkMode: true,
    legend: { show: true, textStyle: { color: '#fff' } },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: time,
      axisTick: { alignWithLabel: true },
      axisLabel: { color: '#fff' },
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} °C',
      },
    },
    series: [
      {
        name: '室内温度',
        type: 'line',
        data: roomT,
      },
      {
        name: '室外温度',
        type: 'line',
        data: outT,
      },
    ],
  };
}
</script>

<style scoped>
#temperature-container {
  width: 100%;
  height: 100%;
}
</style>
