<template>
  <div class="energy-monitor-page">
    <div class="left-content">
      <FloorTree></FloorTree>
    </div>
    <div class="right-content">
      <div class="row">
        <div class="comparison-section-container">
          <div class="section-header">
            <div class="header-title">环比</div>
          </div>
          <div class="comparison-grid">
            <div class="comparison-item">
              <div class="item-value">{{ chainData.currentMonthEnergy }}</div>
              <div class="item-title">当月用水(t)</div>
            </div>
            <div class="comparison-item">
              <div class="item-value">{{ chainData.lastMonthSamePeriodEnergy }}</div>
              <div class="item-title">上月同期(t)</div>
            </div>
            <div class="comparison-item">
              <div class="item-top">
                <div class="item-percent">{{ chainData.monthTrendPercentage }}</div>
                <div>{{ chainData.monthTrendValue }}
                  <span class="item-title">t</span>
                </div>
              </div>
              <div class="item-title">趋势</div>
            </div>
            <div class="comparison-item">
              <div class="item-value">{{ chainData.currentYearEnergy }}</div>
              <div class="item-title">当年用水(t)</div>

            </div>
            <div class="comparison-item">
              <div class="item-value">{{ chainData.lastYearSamePeriodEnergy }}</div>
              <div class="item-title">去年同期(t)</div>
            </div>
            <div class="comparison-item">
              <div class="item-top">
                <div class="item-percent">{{ chainData.yearTrendPercentage }}</div>
                <div>{{ chainData.yearTrendValue }}
                  <span class="item-title">t</span>
                </div>
              </div>
              <div class="item-title">趋势</div>
            </div>
          </div>
        </div>
        <div class="energy-trend-container">
          <div class="energy-trend-top">
            <div class="section-header">
              <div class="header-title">能耗趋势</div>
            </div>
            <RadioGroup v-model:value="energyTrendTime"
                        button-style="solid"
                        size="small" @change="buildingEnergyTrendData(energyTrendTime)">
              <RadioButton value="2">当月</RadioButton>
              <RadioButton value="3">当年</RadioButton>
            </RadioGroup>
          </div>
          <div class="energy-chart" ref="energyTrendChart">
          </div>
        </div>
      </div>
      <div class="row">
        <div class="power-curve-container">
          <div class="section-header">
            <div class="header-title">当年数据曲线</div>
          </div>
          <div class="power-chart" ref="powerCurveChart">
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {RadioGroup, RadioButton} from 'ant-design-vue'
import {ref, onMounted, onBeforeUnmount, reactive} from 'vue'
import * as echarts from 'echarts'
import type {ECharts, EChartsOption} from 'echarts'
import FloorTree from "../../electricEnergy/elctricitySituation/floor-tree.vue";

const chainData = reactive({
  currentMonthEnergy: '9',
  lastMonthSamePeriodEnergy: '--',
  monthTrendPercentage: '--',
  monthTrendValue: '--',
  currentYearEnergy: '59',
  lastYearSamePeriodEnergy: '--',
  yearTrendPercentage: '--',
  yearTrendValue: '--',
})

const energyTrendTime = ref('2')

// 能耗趋势图表容器
const energyTrendChart = ref<HTMLElement | null>(null)
const energyTrendInstance = ref<ECharts | null>(null)

const energyTrendOption: EChartsOption = {
  tooltip: {
    trigger: 'item',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: [],
    name: '日期',
  },
  yAxis: {
    type: 'value',
    name: 't',
  },
  series: [
    {
      data: [],
      type: 'bar',
      markPoint: {
        data: [
          {type: 'max', name: 'Max'},
          {type: 'min', name: 'Min'}
        ]
      },
    }
  ],
}

const initEnergyTrendChart = () => {
  if (energyTrendChart.value) {
    // 销毁旧实例
    energyTrendInstance.value?.dispose()
    // 创建新实例
    energyTrendInstance.value = echarts.init(energyTrendChart.value)
    // 设置配置项
    energyTrendInstance.value.setOption(energyTrendOption)
    buildingEnergyTrendData('2')
    // 可选：添加窗口大小变化监听
    const resizeHandler = () => {
      energyTrendInstance.value?.resize()
    }
    window.addEventListener('resize', resizeHandler)

    // 在组件卸载前移除监听
    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeHandler)
    })
  }
}

function buildingEnergyTrendData(val: string) {
  const now = new Date();
  let timeArr = [];
  let valArr = [];
  let name = '日期';
  if (val == '2') {
    const day = now.getDate()
    for (let i = 1; i < day; i++) {
      timeArr.push(i);
      valArr.push(parseFloat((Math.random() * 10).toFixed(2)));
    }
  } else {
    const month = now.getMonth() + 1;
    for (let i = 1; i < month; i++) {
      timeArr.push(i);
      valArr.push(parseFloat((Math.random() * 80).toFixed(2)));
    }
    name = '月份';
  }

  if (energyTrendInstance.value) {
    energyTrendInstance.value.setOption({
      xAxis: {data: timeArr, name},
      series: [{data: valArr}],
    });
  }
}

//日用电率
const powerCurveChart = ref<HTMLElement | null>(null)
const powerCurveInstance = ref<ECharts | null>(null)


const powerCurveOption: EChartsOption = {
  tooltip: {
    trigger: 'item',
    axisPointer: {
      type: 'cross',
      crossStyle: {
        color: '#999'
      }
    }
  },
  toolbox: {
    feature: {
      magicType: {show: true, type: ['line', 'bar']},
      restore: {show: true},
    }
  },
  legend: {
    data: ['今年']
  },
  xAxis: [
    {
      type: 'category',
      data: [],
      axisPointer: {
        type: 'shadow'
      },
      name: '月份'
    }
  ],
  yAxis: [
    {
      type: 'value',
      name: 't',
    },
  ],
  series: [
    {
      name: '今年',
      type: 'line',
      smooth: true,
      data: [],
      markPoint: {
        data: [
          {type: 'max',},
          {type: 'min',}
        ]
      },
    },
  ]
};

const initPowerCurveChart = () => {
  if (powerCurveChart.value) {
    // 销毁旧实例
    powerCurveInstance.value?.dispose()
    // 创建新实例
    powerCurveInstance.value = echarts.init(powerCurveChart.value)
    // 设置配置项
    powerCurveInstance.value.setOption(powerCurveOption)
    buildingPowerCurveData()
    // 可选：添加窗口大小变化监听
    const resizeHandler = () => {
      powerCurveInstance.value?.resize()
    }
    window.addEventListener('resize', resizeHandler)

    // 在组件卸载前移除监听
    onBeforeUnmount(() => {
      window.removeEventListener('resize', resizeHandler)
    })
  }
}

function buildingPowerCurveData() {
  const now = new Date();
  const month = now.getMonth()+1;
  let yearData = [];
  let timeDate = []
  for (let i = 1; i < month; i++) {
    timeDate.push(i+'月');
    yearData.push(parseFloat((Math.random() * 60).toFixed(2)));
  }
  if (powerCurveInstance.value) {
    powerCurveInstance.value.setOption({
      xAxis: {data: timeDate},
      series: [{data: yearData}],
    });
  }
}

// 组件挂载后初始化图表
onMounted(() => {
  initEnergyTrendChart()
  initPowerCurveChart()
})

// 组件卸载前销毁图表实例
onBeforeUnmount(() => {
  energyTrendInstance.value?.dispose();
  powerCurveInstance.value?.dispose();
})


</script>

<style scoped>
.energy-monitor-page {
  display: flex;
  gap: 1rem;
  padding: 1rem;
  background-color: #f4f4f4;
  min-height: 100vh;
}

.left-content {
  flex: 1;
}

.right-content {
  display: flex;
  flex: 4;
  flex-direction: column;
  gap: 1rem;
}

.row {
  display: flex;
  gap: 1rem;
  width: 100%;
}

.comparison-section-container {
  flex: 2;
}

.energy-trend-container {
  flex: 3;
}
.power-curve-container {
  flex: 5;
}
.energy-trend-top {
  display: flex;
  justify-content: space-between
}

.section-header {
  border-left: 4px solid #3671e8;
  margin-bottom: 15px;
  padding-left: 16px;
}

.header-title {
  font-size: 16px;
  color: #333;
}

.comparison-section-container,
.energy-trend-container,
.power-curve-container{
  background: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 1rem;
}

.comparison-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 5px;
}

.comparison-item {
  padding: 15px 10px;
  border: 1px solid #e0e0e0;
  text-align: center;
}

.item-value {
  font-size: 22px;
  color: #333;
  margin-bottom: 10px;
}

.item-title {
  font-size: 12px;
  color: #666;
}

.item-top {
  font-size: 16px;
  margin-bottom: 10px;
}

.item-percent {
  color: #7fb926;
  margin-bottom: 5px;
  border-bottom: 1px solid #666;
}

.power-chart{
  height: 380px;
}

.energy-chart{
  height: 240px;
}

</style>
