<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, ref } from 'vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { Page } from '@vben/common-ui';
import { DatePicker } from 'ant-design-vue';
import FloorTree from '../components/floor-tree.vue';
import { meterRecordTrend } from '#/api/property/energyManagement/meterRecord';

const currentDay = ref<Dayjs>(dayjs());
const currentMonth = ref<Dayjs>(dayjs());
const currentYear = ref<Dayjs>(dayjs());
const disabledDay = (current: Dayjs) => {
  return current && current > dayjs().endOf('day');
};
const disabledMonth = (current: Dayjs) => {
  return current && current > dayjs().endOf('month');
};
const disabledYear = (current: Dayjs) => {
  return current && current > dayjs().endOf('year');
};

const chartInstances = ref({
  day: null as echarts.ECharts | null,
  month: null as echarts.ECharts | null,
  year: null as echarts.ECharts | null,
});

onMounted(() => {
  //day
  const chartDay = document.getElementById('day');
  chartInstances.value.day = echarts.init(chartDay);
  const optionDay = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['当日', '昨日'],
    },
    toolbox: {
      show: true,
      feature: {
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: true },
      },
    },
    calculable: true,
    xAxis: [
      {
        type: 'category',
        name: '时',
        data: [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: 'KW.h',
      },
    ],
    series: [
      {
        name: '当日',
        type: 'bar',
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' },
          ],
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: 0,
        zoomOnMouseWheel: true,
        filterMode: 'filter',
      },
    ],
  };
  optionDay && chartInstances.value.day.setOption(optionDay);

  //month
  const chartMonth = document.getElementById('month');
  chartInstances.value.month = echarts.init(chartMonth);
  const optionMonth = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['当月', '上月'],
    },
    toolbox: {
      show: true,
      feature: {
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: true },
      },
    },
    calculable: true,
    xAxis: [
      {
        type: 'category',
        name: '日',
        data: [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: 'KW.h',
      },
    ],
    series: [
      {
        name: '当月',
        type: 'bar',
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' },
          ],
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: 0,
        zoomOnMouseWheel: true,
        filterMode: 'filter',
      },
    ],
  };
  optionMonth && chartInstances.value.month.setOption(optionMonth);

  //year
  const chartYear = document.getElementById('year');
  chartInstances.value.year = echarts.init(chartYear);
  const optionYear = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['当年', '去年'],
    },
    toolbox: {
      show: true,
      feature: {
        magicType: { show: true, type: ['line', 'bar'] },
        restore: { show: true },
      },
    },
    calculable: true,
    xAxis: [
      {
        type: 'category',
        name: '月',
        data: [],
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: 'KW.h',
      },
    ],
    series: [
      {
        name: '当年',
        type: 'bar',
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' },
          ],
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        xAxisIndex: 0,
        zoomOnMouseWheel: true,
        filterMode: 'filter',
      },
    ],
  };
  optionYear && chartInstances.value.year.setOption(optionYear);

  // 鼠标悬停时激活缩放
  chartInstances.value.day.on('mouseover', { seriesIndex: 0 }, () => {
    chartInstances.value.day.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: true,
    });
  });

  // 鼠标离开时取消缩放
  chartInstances.value.day.on('mouseout', { seriesIndex: 0 }, () => {
    chartInstances.value.day.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: false,
    });
  });

  // 鼠标悬停时激活缩放
  chartInstances.value.year.on('mouseover', { seriesIndex: 0 }, () => {
    chartInstances.value.year.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: true,
    });
  });

  // 鼠标离开时取消缩放
  chartInstances.value.year.on('mouseout', { seriesIndex: 0 }, () => {
    chartInstances.value.year.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: false,
    });
  });

  // 鼠标悬停时激活缩放
  chartInstances.value.month.on('mouseover', { seriesIndex: 0 }, () => {
    chartInstances.value.month.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: true,
    });
  });

  // 鼠标离开时取消缩放
  chartInstances.value.month.on('mouseout', { seriesIndex: 0 }, () => {
    chartInstances.value.month.dispatchAction({
      type: 'takeGlobalCursor',
      key: 'dataZoomSelect',
      dataZoomSelectActive: false,
    });
  });
});

const trendData = ref<any>({});
async function handleSelectFloor(selectedKeys, info) {
  let data = {
    day: currentDay.value.format('YYYY-MM-DD'),
    month: currentMonth.value.format('YYYY-MM'),
    year: currentYear.value.format('YYYY'),
    meterType: 1,
    meterId: null,
    floorId: null,
  };

  if (info.node.level == 3) {
    data.floorId = selectedKeys[0];
  } else {
    data.meterId = selectedKeys[0];
  }

  const trend = await meterRecordTrend(data);

  // 更新日数据图表
  if (chartInstances.value.day && trend.hour) {
    chartInstances.value.day.setOption({
      xAxis: {
        data: trend.hour.categories || [],
      },
      series: [
        {
          name: '当月',
          data: trend.hour.data || [],
        },
      ],
    });
  }

  // 更新月数据图表
  if (chartInstances.value.month && trend.day) {
    chartInstances.value.month.setOption({
      xAxis: {
        data: trend.day.categories || [],
      },
      series: [
        {
          name: '当月',
          data: trend.day.data || [],
        },
      ],
    });
  }

  // 更新年数据图表
  if (chartInstances.value.year && trend.month) {
    chartInstances.value.year.setOption({
      xAxis: {
        data: trend.month.categories || [],
      },
      series: [
        {
          name: '当年',
          data: trend.month.data || [],
        },
      ],
    });
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <div class="flex h-full gap-[8px]">
      <FloorTree class="w-[260px]" @select="handleSelectFloor"></FloorTree>
      <div class="flex-1 overflow-hidden">
        <div
          style="
            background: #fff;
            border-radius: 8px;
            padding: 10px;
            height: 33%;
          "
        >
          <div>
            <div style="display: flex; justify-content: space-between">
              <DatePicker
                v-model:value="currentDay"
                :disabled-date="disabledDay"
              />当日能耗总值：125.04KW.h
            </div>
          </div>
          <div id="day" style="height: 100%; width: 100%"></div>
        </div>
        <div
          style="
            background: #fff;
            border-radius: 8px;
            padding: 10px;
            margin-top: 16px;
            height: 33%;
          "
        >
          <div>
            <div style="display: flex; justify-content: space-between">
              <DatePicker
                v-model:value="currentMonth"
                :disabled-date="disabledMonth"
                picker="month"
              />当月能耗总值：125.04KW.h
            </div>
          </div>
          <div id="month" style="height: 100%; width: 100%"></div>
        </div>
        <div
          style="
            background: #fff;
            border-radius: 8px;
            padding: 10px;
            margin-top: 16px;
            height: 33%;
          "
        >
          <div>
            <div style="display: flex; justify-content: space-between">
              <DatePicker
                v-model:value="currentYear"
                :disabled-date="disabledYear"
                picker="year"
              />当年能耗总值：125.04KW.h
            </div>
          </div>
          <div id="year" style="height: 100%; width: 100%"></div>
        </div>
      </div>
    </div>
  </Page>
</template>
