<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">生产时间：</span>
        <el-date-picker v-model="dateTime" size="small" type="daterange" align="center" style="width: 240px;"
          value-format="yyyy-MM-dd" format="yyyy-MM-dd" range-separator="～" start-placeholder="开始日期"
          end-placeholder="结束日期" />
        <span style="margin-left: 10px">电表号：</span>
        <el-input v-model="meterCode" placeholder="输入电表号(可空)" clearable size="small"
          style="width: 200px; margin-left: 13px" />
        <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 5px"
          @click="pageCurrent = 1; searchData()">查询</el-button>
        <el-button type="info" size="small" icon="el-icon-download" @click="exportExcel()">Excel</el-button>
      </div>
      <el-row :gutter="10">
        <el-col :span="16">
          <el-table v-loading="loading" ref="multipleTable" :data="tableData"
            :header-cell-style="{ background: '#f5f7fa', color: '#333', fontSize: '14px', fontWeight: 'bold' }"
            element-loading-text="数据加载中" element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.2)" class="main" tooltip-effect="dark" height="750px" border
            size="medium" show-summary :summary-method="getSummaries">
            <el-table-column align="center" label="序号" type="index" width="80" />
            <el-table-column align="center" label="电表号" prop="电表号" />
            <el-table-column align="center" label="开始电能" prop="开始电能" />
            <el-table-column align="center" label="结束电能" prop="结束电能" />
            <el-table-column align="center" label="结算日期" prop="结算日期" />
            <el-table-column align="center" label="结算电能" prop="结算电能" />
          </el-table>
        </el-col>
        <el-col :span="8">
          <div class="chart-card">
            <div class="chart-title">按日期消耗趋势</div>
            <div ref="byDateChart" class="chart-box"></div>
          </div>
          <div class="chart-card" style="margin-top: 10px;">
            <div class="chart-title">按电表消耗分布</div>
            <div ref="byMeterChart" class="chart-box"></div>
          </div>
        </el-col>
      </el-row>
      <div class="block" style="margin-top: 10px;">
        <el-pagination v-if="!loading" :current-page="pageCurrent" :page-sizes="[15, 30, 50, 100, 500]"
          :page-size="pageSize" :total="total" background layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [], // 表格数据
      meterCode: '', // 电表号
      deviceList: [], // 兼容旧变量，不再使用
      dateTime: [], // 日期范围
      total: 0, // 总条数
      pageSize: 15, // 每页显示条数
      pageCurrent: 1, // 当前页码
      loading: false, // 加载状态
      chartByDate: null,
      chartByMeter: null
    }
  },
  created() {
    // 初始化日期为当前月的第一天到今天
    const end = new Date()
    const start = new Date()
    start.setDate(1) // 设置为当月第一天

    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    this.dateTime = [formatDate(start), formatDate(end)]

    // 获取设备列表
    this.getDeviceList()
  },
  methods: {
    // 直接初次查询
    getDeviceList() {
      this.searchData()
    },

    // 查询日汇总分页数据
    searchData() {
      if (!this.dateTime || this.dateTime.length !== 2) {
        this.$message.warning('请选择日期范围')
        return
      }

      this.loading = true
      this.tableData = []

      const param = [
        ['开始日期', this.dateTime[0]],
        ['结束日期', this.dateTime[1]],
        ['电表号', this.meterCode || ''],
        ['PageCurrent', this.pageCurrent],
        ['PageSize', this.pageSize],
        ['PageCount', '1111', 'int', '1'],
        ['ItemCount', '1111', 'int', '1']
      ]
      const Data = this.CreateData('11', '能耗_日汇总_视图_分页查询', param)
      this.ExecDatabase(Data).then(response => {
        let rows = []
        if (response && response.data) {
          if (Array.isArray(response.data)) {
            rows = response.data
          } else if (response.data.result && Array.isArray(response.data.result)) {
            rows = response.data.result
          }
        }
        this.tableData = rows || []
        let total = 0
        if (response && response.data && Array.isArray(response.data.output) && response.data.output.length > 0) {
          total = parseInt(response.data.output[0].ItemCount || 0)
        }
        this.total = total
        this.$nextTick(() => this.updateCharts())
      }).catch(() => {
        this.$message.error('查询失败，请稍后重试')
      }).finally(() => {
        this.loading = false
      })
    },

    // 导出Excel（可选：如需日报导出）
    exportExcel() {
      if (this.tableData.length === 0) {
        this.$message.warning('暂无数据可导出')
        return
      }

      const param = [
        ['开始日期', this.dateTime[0]],
        ['结束日期', this.dateTime[1]],
        ['电表号', this.meterCode || '']
      ]
      const Data = this.CreateData('2001', '能耗_日汇总_视图_分页查询', param)
      this.exportExcel_NPOI(Data)
    },

    // 分页处理 - 改变每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.pageCurrent = 1
      this.searchData()
    },

    // 分页处理 - 改变页码
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.searchData()
    }
    ,
    // 表格合计行：合计当前页“结算电能”
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (column.property === '结算电能') {
          const total = (data || []).reduce((s, r) => s + (Number(r['结算电能']) || 0), 0)
          sums[index] = total.toFixed(2)
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 初始化/释放图表
    initCharts() {
      if (!this.chartByDate && this.$refs.byDateChart) this.chartByDate = this.$echarts.init(this.$refs.byDateChart)
      if (!this.chartByMeter && this.$refs.byMeterChart) this.chartByMeter = this.$echarts.init(this.$refs.byMeterChart)
    },
    disposeCharts() {
      if (this.chartByDate) { this.chartByDate.dispose(); this.chartByDate = null }
      if (this.chartByMeter) { this.chartByMeter.dispose(); this.chartByMeter = null }
    },
    handleResize() {
      this.chartByDate && this.chartByDate.resize()
      this.chartByMeter && this.chartByMeter.resize()
    },
    // 构建图表
    updateCharts() {
      this.initCharts()
      const rows = this.tableData || []
      // 日期趋势：按结算日期合并
      const dateMap = {}
      rows.forEach(r => {
        const d = r['结算日期']
        const v = Number(r['结算电能']) || 0
        dateMap[d] = (dateMap[d] || 0) + v
      })
      const dateCats = Object.keys(dateMap).sort()
      const dateVals = dateCats.map(k => parseFloat(dateMap[k].toFixed(2)))
      this.chartByDate && this.chartByDate.setOption({
        grid: { left: 40, right: 60, top: 30, bottom: 40 },
        tooltip: { trigger: 'axis' },
        toolbox: { feature: { saveAsImage: {}, restore: {}, dataZoom: {} } },
        dataZoom: dateCats.length > 20 ? [{ type: 'inside' }, { type: 'slider', height: 12 }] : [],
        xAxis: { type: 'category', data: dateCats },
        yAxis: { type: 'value', name: 'kWh' },
        color: ['#67C23A'],
        series: [{
          type: 'line', smooth: true, data: dateVals, name: '结算电能',
          areaStyle: { color: 'rgba(103,194,58,0.12)' },
          markPoint: { data: [{ type: 'max', name: '峰值' }] },
          markLine: { data: [{ type: 'average', name: '平均' }] }
        }]
      })
      // 电表分布：按电表号合并
      const meterMap = {}
      rows.forEach(r => {
        const m = r['电表号'] || '未知'
        const v = Number(r['结算电能']) || 0
        meterMap[m] = (meterMap[m] || 0) + v
      })
      const meterArr = Object.keys(meterMap).map(k => ({ name: k, value: parseFloat(meterMap[k].toFixed(2)) }))
        .sort((a, b) => b.value - a.value)
      const meterCats = meterArr.map(i => i.name)
      const meterVals = meterArr.map(i => i.value)
      this.chartByMeter && this.chartByMeter.setOption({
        grid: { left: 60, right: 20, top: 30, bottom: 60 },
        tooltip: { trigger: 'axis' },
        toolbox: { feature: { saveAsImage: {}, restore: {} } },
        dataZoom: meterCats.length > 10 ? [{ type: 'inside' }, { type: 'slider', height: 12 }] : [],
        xAxis: { type: 'category', data: meterCats, axisLabel: { interval: 0, rotate: 35 } },
        yAxis: { type: 'value', name: 'kWh' },
        color: ['#409EFF'],
        series: [{
          type: 'bar', barMaxWidth: 30, data: meterVals, name: '结算电能',
          itemStyle: { color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: '#66b1ff' }, { offset: 1, color: '#3a8ee6' }]) },
          label: { show: true, position: 'top' }
        }]
      })
    }
  }
}
</script>

<style scoped>
.topCard {
  margin: 10px;
  padding: 5px;
}

.topDiv {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.el-select {
  width: 200px;
}

.el-input {
  width: 200px;
}

:deep(.el-col-8) .chart-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px 8px 0 8px;
}

.chart-title {
  font-size: 14px;
  color: #303133;
  padding: 4px 8px 8px 8px;
}

.chart-box {
  width: 100%;
  height: 350px;
}

::v-deep .el-table th.el-table__cell {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
}

::v-deep .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #f8f8f9;
}

::v-deep .el-table--border th.el-table__cell.is-leaf {
  border-right: 1px solid #e8e8e8;
}
</style>
