<template>
  <div class="app-container">
    <el-card class="box-card" style="margin-bottom: 10px">
      <el-row :gutter="20">
        <el-col :span="24" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="能源类型" prop="energyType">
              <el-select v-model="queryParams.energyType" style="width: 100px" placeholder="请选择能源类型">
                <el-option
                  v-for="item in energyTypeList"

                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="日期类型" prop="dateType">
              <el-select v-model="queryParams.dateType" style="width: 100px" placeholder="请选择日期类型">
                <el-option
                  v-for="dict in dateTypeList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="采集时间">
              <el-date-picker
                v-model="queryParams.startTime"
                style="width: 200px"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label-width="auto">-</el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="queryParams.endTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 200px"
                type="datetime"
                placeholder="选择日期时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
              >搜索
              </el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>

    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <el-card class="box-card" style="height: 350px; position: relative">
          <img
            class="centered-image"
            src="@/assets/images/electricityIcon.svg"
          />
          <div class="centered-text total-consumption-label">
            总耗量
          </div>
          <div class="centered-text total-consumption-value">
            {{ totalConsumption != null ? totalConsumption.toFixed(2) : '' }}{{ measurementUnit }}
          </div>
        </el-card>
      </el-col>
      <el-col :span="19" :xs="24">
        <el-card class="box-card" style="height: 350px; margin-bottom: 10px">
          <div id="card" class="card-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="box-card" style="margin-bottom: 30px">
      <el-row :gutter="20">
        <el-col :span="24" :xs="24">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getList"
            ></right-toolbar>
          </el-row>
          <el-table
            header-cell-class-name="columnClassName"
            id="bootstrap-table"
            v-loading="loading"
            :data="dataList"
            @selection-change="handleSelectionChange"
          >
            <template v-for="time in timeList">
              <el-table-column
                v-if="time.title && time.rowspan == 2"
                :key="time.title"
                :label="time.title"
                :prop="time.field"
                min-width="120"
              />
              <el-table-column
                v-if="time.title && time.colspan == 1"
                :key="time.title"
                :label="time.title"
              >
                <el-table-column
                  min-width="140"
                  :key="time.title + '_' + time.field"
                  :label="'耗量(' + measurementUnit + ')'"
                  :prop="time.field"
                />
              </el-table-column>
            </template>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import {
  energyPreviewReportList
} from '@/api/ems/report/reportPort.js'
import Treeselect from 'vue3-treeselect';
import 'vue3-treeselect/dist/vue3-treeselect.css';
import * as echarts from 'echarts'
import {
  getHoursBetween,
  getDatesBetween,
  getMonthsBetween,
  getYearsBetween
} from '@/utils/dateReportUtils.js'
import { handleExport } from '@/utils/export.js'
import { parseTime } from '@/utils/ruoyi'

let data = {}
let optionData = {}
export default {
  name: 'EnergyPreview',
  dicts: ['statistical_unit'],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      dataList: null,
      // 时间List
      timeList: null,
      energyList: null,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        energyType: '2',
        dateType: '10',
        startTime: '',
        endTime: ''
      },
      //总耗量
      totalConsumption: 0,
      //计量单位
      measurementUnit: 'kW·h',
      //采集方式
      dateTypeList: [
        { label: '时', value: '13' },
        { label: '日', value: '10' },
        { label: '月', value: '7' },
        { label: '年', value: '4' }
      ],
      // 能源类型选项
      energyTypeList: [
        { value: '2', label: '电' },
        { value: '3', label: '水' },
        { value: '4', label: '蒸汽' }
      ],
      option: {
        grid: {
          containLabel: true,
          left: '2%',
          right: '2%',
          bottom: '5%',
          top: 20
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return params.data + 'kW·h'
          },
          textStyle: {
            align: 'left'
          }
        },
        xAxis: [
          {
            axisLabel: {
              color: '#333',
              fontSize: 14
              // interval: 0,
            },
            axisTick: {
              lineStyle: {
                color: '#384267'
              },
              show: true
            },
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: 'rgba(255,255,255,0.1)',
                width: 1
              },
              show: true
            },
            data: data.x,
            type: 'category'
          }
        ],
        yAxis: {
          axisLabel: {
            color: '#333',
            fontSize: 14
          },
          axisTick: {
            lineStyle: {
              color: '#384267',
              width: 1
            },
            show: true
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: 'rgba(255,255,255,0.1)'
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(255,255,255,0.1)',
              width: 1
            },
            show: true
          },
          name: ''
        },
        dataZoom: [],
        series: [
          {
            data: data.y,
            type: 'bar',
            barMaxWidth: 20,
            barWidth: '75%',
            itemStyle: {
              color: {
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                type: 'linear',
                global: false,
                colorStops: [
                  {
                    offset: 0,
                    color: optionData?.bgColor ? optionData.bgColor : '#0a8ff6'
                  },
                  {
                    offset: 1,
                    color: '#06f8f7'
                  }
                ]
              }
            }
          },
          {
            type: 'line',
            stack: '总量',
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                borderWidth: 2,
                borderColor: '#3aa1ff',
                color: '#3aa1ff',
                lineStyle: {
                  color: '#3aa1ff',
                  width: 1
                }
              }
            },
            tooltip: {
              show: false
            },
            data: data.y
          }
        ]
      }
    }
  },
  created() {
    const nowDate = parseTime(new Date(), '{y}-{m}-{d}')
    this.queryParams.startTime = nowDate + ' 00:00:00'
    this.queryParams.endTime = nowDate + ' 23:59:59'
  },
  mounted() {
    this.handleQuery()
  },
  methods: {
    getDateList(startTime, endTime) {
      if (this.queryParams.dateType === '13') {
        return getHoursBetween(startTime, endTime)
      } else if (this.queryParams.dateType === '10') {
        return getDatesBetween(startTime, endTime)
      } else if (this.queryParams.dateType === '7') {
        return getMonthsBetween(startTime, endTime)
      } else if (this.queryParams.dateType === '4') {
        return getYearsBetween(startTime, endTime)
      }
    },
    barChart() {
      var chartDom = document.getElementById('card')
      var myChart = echarts.init(chartDom)
      let data = []
      const createLinearGradient = (startColor, endColor) => ({
        x: 0,
        y: 0,
        x2: 0,
        y2: 1,
        type: 'linear',
        global: false,
        colorStops: [
          { offset: 0, color: startColor },
          { offset: 1, color: endColor }
        ]
      })

      const axisStyle = {
        axisLabel: { color: '#333', fontSize: 14 },
        axisTick: { lineStyle: { color: '#384267', width: 1 }, show: true },
        axisLine: { lineStyle: { color: 'rgba(255,255,255,0.1)', width: 1 }, show: true }
      }

      const option = {
        grid: {
          containLabel: true,
          left: '2%',
          right: '2%',
          bottom: '5%',
          top: 20
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => `${params[0].name}<br>${params[0].marker} ${params[0].data}kW·h`
        },
        xAxis: [
          {
            ...axisStyle,
            data: [],
            type: 'category',
            splitLine: { show: false }
          }
        ],
        yAxis: {
          ...axisStyle,
          splitLine: { show: true, lineStyle: { color: 'rgba(255,255,255,0.1)' } },
          name: ''
        },
        dataZoom: [],
        series: [
          {
            data: data,
            type: 'bar',
            barMaxWidth: 20,
            barWidth: '75%',
            itemStyle: {
              color: createLinearGradient(optionData?.bgColor || '#0a8ff6', '#06f8f7')
            }
          },
          {
            data: data,
            type: 'line',
            stack: '总量',
            symbol: 'circle',
            symbolSize: 8,
            itemStyle: {
              normal: {
                borderWidth: 2,
                borderColor: '#3aa1ff',
                color: '#3aa1ff',
                lineStyle: { color: '#3aa1ff', width: 1 }
              }
            },
            tooltip: { show: false }
          }
        ]
      }

      myChart.setOption(option)
      energyPreviewReportList(this.queryParams).then((response) => {
        this.dataList = response.data
        this.loading = false

        const data = response.data || []
        if (data.length === 0) return
        this.totalConsumption = data.reduce((sum, item) => {
          return sum + parseFloat(item.expendSum || 0);
        }, 0);


        const keys = Object.keys(data[0])
        const filteredKeys = keys.filter(key => key && !['unitName', 'state', 'expendSum', 'type'].includes(key))

        const yData = filteredKeys.map(key => {
          return data.reduce((sum, item) => sum + parseFloat(item[key] || 0), 0).toFixed(2)
        })

        const timeData = filteredKeys.map(key => key.split('expend')[1] + ':00:00')
        const sortedData = timeData.map((time, index) => ({
          name: time,
          value: parseFloat(yData[index]),
          time: new Date(time).getTime()
        })).sort((a, b) => a.time - b.time)

        const xAxisData = sortedData.map(item => item.name.split(':')[0])
        const seriesData = sortedData.map(item => item.value)

        myChart.setOption({
          dataZoom: [{
            show: true,
            type: 'slider',
            bottom: '3%',
            xAxisIndex: 0,
            height: 12,
            start: 0,
            brushSelect: false,
            end: (1 / (seriesData.length / 20)) * 100,
            textStyle: {
              fontSize: 0,
              color: 'rgba(0,0,0,0)'
            }
          }],
          xAxis: [{
            data: xAxisData
          }],
          series: [{
            data: seriesData
          }, {
            data: seriesData
          }]
        })
      })

    },
    /** 查询用户列表 */
    getList(dateList) {
      this.loading = true
      this.initTable(dateList)
      this.barChart()
    },
    initTable(columns) {
      this.timeList = []
      this.energyList = []
      this.timeList.push(
        {
          title: '用电类型名称',
          field: 'unitName',
          align: 'center',
          rowspan: 2
        },
        {
          field: 'expendSum',
          title: '耗量合计(' + this.measurementUnit + ')',
          align: 'center',
          rowspan: 2
        }
      )
      for (let i in columns) {
        this.timeList.push({
          title: columns[i],
          align: 'center',
          colspan: 1,
          field: 'expend' + columns[i].substring(0, 13)
        })
        this.energyList.push({
          field: 'expend' + columns[i].substring(0, 13),
          title: '耗量(' + this.measurementUnit + ')',
          align: 'center',
          rowspan: 1
        })
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let dateList = this.getDateList(
        this.queryParams.startTime,
        this.queryParams.endTime
      )
      this.getList(dateList)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.dateType = '10'
      this.queryParams.startTime = ''
      this.queryParams.endTime = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      handleExport('bootstrap-table', `能源预览_${new Date().getTime()}`, true)
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  ::v-deep.columnClassName {
    font-size: 10px;
    font-weight: normal;
  }

  .tree {
    width: 220px;

    ::v-deep .el-tree-node {
      white-space: normal; //关键代码!!!!!!!!!

      .el-tree-node__content {
        height: 100%;
        align-items: start;
      }
    }
  }
}

.app-container {
  padding: 20px;
}

.centered-image {
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%, -100%);
}

.centered-text {
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0%);
  font-weight: 600;
  text-align: center;
}

.total-consumption-label {
  top: 45%;
  font-size: 1.9vw;
}

.total-consumption-value {
  top: 55%;
  width: 100%;
  padding: 3px 10px;
  font-size: 1.7vw;
}

.card-container {
  width: 100%;
  height: 350px;
  margin-left: 50px;
  user-select: none;
  margin-top: -30px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
