<template>
  <div class="app-container">
    <!-- 条件筛选区 -->
    <el-row :gutter="24">
      <el-col :span="24" :xs="24">
        <el-form :model="filterForm" ref="queryForm" :inline="true" size="small" label-width="80px">
          <el-form-item label="能源类型" prop="energyType">
            <el-select v-model="filterForm.energyType" style="width: 100px" placeholder="请选择能源类型">
              <el-option
                v-for="item in energyTypeList"
                :key="item.energyTypeId"
                :label="item.energyName"
                :value="item.energyTypeId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="日期类型" prop="dateType">
            <el-select v-model="filterForm.dateType" placeholder="请选择日期类型" style="width: 80px;">
              <el-option
                v-for="item in dateTypeList"
                :key="item.dateTypeCode"
                :label="item.dateTypeName"
                :value="item.dateTypeCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="统计单元" prop="workUnitCode">
            <treeselect v-model="filterForm.workUnitCode" :options="workUnitOptions"
                        :normalizer="workUnitOptionsNormalizer"
                        placeholder="请选择统计单元" style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 340px;"
            >
            </el-date-picker>
          </el-form-item>
<!--          <el-form-item label="对比类型">-->
<!--            <el-select v-model="filterForm.compareType" placeholder="请选择对比类型" style="width: 120px;">-->
<!--              <el-option label="同比" value="yoy"></el-option>-->
<!--              <el-option label="环比" value="mom"></el-option>-->
<!--              <el-option label="自定义对比" value="custom"></el-option>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 数据可视化展示区 -->
    <el-row :gutter="20" class="visualization-section">
      <!-- 趋势对比图 -->
      <el-col :span="16">
        <el-card>
          <div slot="header">
            <span>趋势对比图</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="saveChart('trendChart')">
              保存图片
            </el-button>
          </div>
          <div ref="trendChart" style="height: 400px; width: 100%"></div>
        </el-card>
      </el-col>
      <!-- 能耗总量对比 -->
      <el-col :span="8">
        <el-card>
          <div slot="header">
            <span>能耗总量对比</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="saveChart('totalChart')">
              保存图片
            </el-button>
          </div>
          <div ref="totalChart" style="height: 400px; width: 100%"></div>
        </el-card>
      </el-col>
    </el-row>

<!--    <el-row :gutter="20" class="visualization-section" style="margin-top: 20px;">-->
<!--      &lt;!&ndash; 能耗占比对比 &ndash;&gt;-->
<!--      <el-col :span="12">-->
<!--        <el-card>-->
<!--          <div slot="header">-->
<!--            <span>能耗占比对比</span>-->
<!--            <el-button style="float: right; padding: 3px 0" type="text" @click="saveChart('proportionChart')">-->
<!--              保存图片-->
<!--            </el-button>-->
<!--          </div>-->
<!--          <div ref="proportionChart" style="height: 300px; width: 100%"></div>-->
<!--        </el-card>-->
<!--      </el-col>-->
<!--      &lt;!&ndash; 变化率趋势 &ndash;&gt;-->
<!--      <el-col :span="12">-->
<!--        <el-card>-->
<!--          <div slot="header">-->
<!--            <span>变化率趋势</span>-->
<!--            <el-button style="float: right; padding: 3px 0" type="text" @click="saveChart('rateChart')">-->
<!--              保存图片-->
<!--            </el-button>-->
<!--          </div>-->
<!--          <div ref="rateChart" style="height: 300px; width: 100%"></div>-->
<!--        </el-card>-->
<!--      </el-col>-->
<!--    </el-row>-->

  </div>
</template>
<script>
import * as echarts from 'echarts'
import { getBaseEnergyTypeList } from '@/api/ems/base/baseEnergyType'
import { parseTime } from '@/utils/ruoyi'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getWorkUnitTrees } from '@/api/ems/base/baseWorkUnit'
import { yoyAnalysisReport } from '@/api/ems/report/reportPort'

export default {
  name: 'YoyAnalysisReport',
  components: { Treeselect },
  data() {
    return {
      // 筛选表单
      filterForm: {
        energyType: 2,
        dateType: 10,
        workUnitCode: null
      },
      timeRange: [],
      // 图表实例
      charts: {},
      dateTypeList: [
        { dateTypeCode: 10, dateTypeName: '日' },
        { dateTypeCode: 7, dateTypeName: '月' },
        { dateTypeCode: 4, dateTypeName: '年' }
      ],
      // 能源类型选项
      energyTypeList: [],
      workUnitOptions: [],
      dataList: {
        // time: ['00:00', '04:00', '08:00', '12:00', '16:00', '20:00', '24:00'],
        // thisData: [120, 132, 101, 134, 90, 230, 210],
        // contrastData: [110, 125, 95, 128, 85, 220, 200],
        // rate: [9.1, 5.6, 6.3, 4.7, 5.9, 4.5, 5.0],
        // thisSum: 1320,
        // contrastSum: 1620
      }
    }
  },
  created() {
    this.getWorkUnitTreesMethod()
    getBaseEnergyTypeList({}).then(response => {
      this.energyTypeList = response.data
    })
  },
  mounted() {
    this.initFilterForm()
    this.initAnalysisCharts()
  },
  methods: {
    // 初始化筛选表单
    initFilterForm() {
      const nowDate = parseTime(new Date(), '{y}-{m}-{d}')
      this.timeRange = [
        nowDate + ' 00:00:00',
        nowDate + ' 23:59:59'
      ]
    },
    // 查询数据
    handleSearch() {
      this.updateCharts()
    },
    // 重置筛选条件
    handleReset() {
      this.resetForm('queryForm')
      this.handleSearch()
    },
    /** 转换统计单元信息数据结构 */
    workUnitOptionsNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id2: node.workUnitCode,
        label2: node.workUnitName,
        children2: node.children
      }
    },
    /** 查询统计单元下拉树结构 */
    getWorkUnitTreesMethod() {
      getWorkUnitTrees().then(response => {
        this.workUnitOptions = []
        this.workUnitOptions = JSON.parse(JSON.stringify(response.data).replaceAll('id', 'id2').replaceAll('code', 'id'))
      })
    },
    // 保存图表
    saveChart(chartName) {
      if (this.charts[chartName]) {
        const url = this.charts[chartName].getDataURL()
        const link = document.createElement('a')
        link.download = `${chartName}_${new Date().getTime()}.png`
        link.href = url
        link.click()
      }
    },
    // 初始化分析图表
    initAnalysisCharts() {
      this.$nextTick(() => {
        this.initTrendChart()
        this.initTotalChart()
      })
    },
    // 趋势对比图
    initTrendChart() {
      const chart = echarts.init(this.$refs.trendChart)
      this.charts.trendChart = chart

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['本期能耗', '对比期能耗', '变化率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: this.dataList.time
        },
        yAxis: [
          {
            type: 'value',
            name: '能耗(kWh)',
            position: 'left'
          },
          {
            type: 'value',
            name: '变化率(%)',
            position: 'right',
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        series: [
          {
            name: '本期能耗',
            type: 'bar',
            data: this.dataList.thisData
          },
          {
            name: '对比期能耗',
            type: 'bar',
            data: this.dataList.contrastData
          },
          {
            name: '变化率',
            type: 'line',
            yAxisIndex: 1,
            data: this.dataList.rate
          }
        ]
      }
      chart.setOption(option)
    },
    // 能耗总量对比
    initTotalChart() {
      const chart = echarts.init(this.$refs.totalChart)
      this.charts.totalChart = chart

      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            name: '能耗对比',
            type: 'pie',
            radius: '50%',
            data: [
              { value: this.dataList.thisSum, name: '本期能耗' },
              { value: this.dataList.contrastSum, name: '对比期能耗' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      chart.setOption(option)
    },
    // 能耗占比对比
    initProportionChart() {
      const chart = echarts.init(this.$refs.proportionChart)
      this.charts.proportionChart = chart

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['本期占比', '对比期占比']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['照明', '动力', '空调', '其他']
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '本期占比',
            type: 'bar',
            data: [25, 35, 30, 10]
          },
          {
            name: '对比期占比',
            type: 'bar',
            data: [20, 40, 25, 15]
          }
        ]
      }
      chart.setOption(option)
    },

    // 更新图表
    updateCharts() {
      this.loading = true
      this.filterForm.beginCollectTime = null
      this.filterForm.endCollectTime = null
      if (this.timeRange != null && this.timeRange !== '') {
        this.filterForm.beginCollectTime = this.timeRange[0]
        this.filterForm.endCollectTime = this.timeRange[1]
      }
      yoyAnalysisReport(this.filterForm).then(response => {
        this.dataList = response.data
        console.log(this.dataList)
        this.initTrendChart()
        this.initTotalChart()
        this.loading = false
        this.$message.success('图表数据已更新')
      })
    }
  }
}
</script>
<style scoped>
.energy-dashboard {
  padding: 20px;
}

.filter-section {
  background: #f5f7fa;
}

.visualization-section .el-card {
  min-height: 350px;
}

.analysis-section .el-card {
  min-height: 200px;
}

.table-section .el-card {
  min-height: 400px;
}

.dashboard-overview .el-card {
  min-height: 300px;
}
</style>
