<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';

import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import { onMounted, ref } from 'vue';
import { meterRecordTrend } from '#/api/property/energyManagement/meterRecord';
import dayjs from 'dayjs';

const chartRef = ref<EchartsUIType>();
const { renderEcharts } = useEcharts(chartRef);
// 添加日期选择相关逻辑
const selectedDate = ref<string>(dayjs().format('YYYY-MM'));
// 获取当月天数
const getDaysInMonth = (date: string) => {
  const year = parseInt(date.split('-')[0]);
  const month = parseInt(date.split('-')[1]);
  const daysInMonth = new Date(year, month, 0).getDate();
  return Array.from({ length: daysInMonth }, (_, i) => i + 1);
};

const handleDateChange = () => {
  console.log('selectedDate', selectedDate.value);

  getMeterRecordTrend();
};
const getMeterRecordTrend = async () => {
      const res = await meterRecordTrend(
    {
       day: dayjs().format('YYYY-MM-DD'),
    month: selectedDate.value || dayjs().format('YYYY-MM'),
    year: dayjs().format('YYYY'),
    meterType: 1,
    meterId: null,
    floorId: null,
  }
  );
console.log(res);

  // 处理返回的数据
  const chartData = res.day.nowMonth.data || [];
console.log(chartData);

  // 创建一个映射，将日期和数值对应起来
  const dataMap: Record<string, string> = {};
  chartData.forEach(([day, value]: [string, string]) => {
    dataMap[day] = value;
  });

  // 获取当月所有日期
  const days = getDaysInMonth(selectedDate.value);

  // 为没有数据的日期填充0，构建完整的数据数组
  const seriesData = days.map(day => {
    return parseFloat(dataMap[day.toString()] || '0');
  });
  renderEcharts({
    grid: {
      bottom: 0,
      containLabel: true,
      left: '1%',
      right: '1%',
      top: '2 %',
    },
    series: [
      {
        areaStyle: {},
        data: seriesData,
        itemStyle: {
          color: '#5ab1ef',
        },
        smooth: true,
        type: 'line',
      }
    ],
    tooltip: {
      axisPointer: {
        lineStyle: {
          color: '#019680',
          width: 1,
        },
      },
      trigger: 'axis',
    },
    // xAxis: {
    //   axisTick: {
    //     show: false,
    //   },
    //   boundaryGap: false,
    //   data: Array.from({ length: 18 }).map((_item, index) => `${index + 6}:00`),
    //   type: 'category',
    // },
    xAxis: {
      axisTick: {
        show: false,
      },
      boundaryGap: false,
      data: days,
      splitLine: {
        lineStyle: {
          type: 'solid',
          width: 1,
        },
        show: true,
      },
      type: 'category',
    },
    yAxis: [
      {
        axisTick: {
          show: false,
        },
        // max: 800,
        splitArea: {
          show: true,
        },
        splitNumber: 4,
        type: 'value',
      },
    ],
  });
};
onMounted(async () => {
getMeterRecordTrend();
});

</script>

<template>
  <div>
  <EchartsUI ref="chartRef" />
  </div>
</template>
