<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="tabClick">
      <el-tab-pane label="总览" name="summery">
        <el-row type="flex" :gutter="20" style="margin-top: 20px">
          <el-col :span="12">
            <PieChartBlock title="当日供电量（单位：kW·h）" :opt-cfg="elecQuantity"/>
          </el-col>
          <el-col :span="12">
            <PieChartBlock title="当日电费（单位：元）" :opt-cfg="elecCost"></PieChartBlock>
          </el-col>
        </el-row>
        <el-row type="flex" :gutter="20" style="margin-top: 20px">
          <el-col :span="24">
            <BarChartBlock title="当日供电量柱状图" :opt-cfg="pvSupplyIndex"/>
          </el-col>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="市电" name="first">
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="areaName" placeholder="请输入区域名称" clearable size="small"
                      prefix-icon="el-icon-search"
                      style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container" style="height: 100vh; overflow: hidden; position: relative;">
            <el-tree :data="areaOptions" :props="defaultProps" :expand-on-click-node="false"
                     :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                     @node-click="handleNodeClick" style="height: calc(100vh - 50px); overflow-y: auto;"
            />
          </div>
        </el-col>
        <el-col :span="20" :xs="24">
          <div class="container-block">
            <el-form size="small" :inline="true" label-width="68px">
              <el-form-item label="地块">
                <template slot-scope="scope">
                  <span>{{ selectedLabel }}</span>
                </template>
              </el-form-item>
            </el-form>
            <BaseChart width="100%" height="300px" :option="elecOptions"/>
          </div>
          <div class="container-block">
            <div class="ctl-container">
              <el-date-picker v-model="dateRange" type="datetimerange" @change="getList"
                              value-format="yyyy-MM-dd hh:mm:ss" :picker-options="pickerOptions" range-separator="至"
                              start-placeholder="开始日期" end-placeholder="结束日期" align="right"
              >
              </el-date-picker>
            </div>
            <el-table v-loading="loading" :data="pgSupplyHList">
              <el-table-column label="日期" align="center" prop="date" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="时间" align="center" prop="time">
                <template slot-scope="scope">
                  <span>{{ scope.row.time }}</span>
                </template>
              </el-table-column>
              <el-table-column label="计量类型" align="center" prop="meterType">
                <template slot-scope="scope">
                  <span>{{ getMeterTypeName(scope.row.meterType) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="单位电价(￥)" align="center" prop="meterUnitPrice"/>
              <el-table-column label="供电量(kW·h)" align="center" prop="useElecQuantity"/>
              <el-table-column label="供电电费(￥)" align="center" prop="useElecCost"/>
            </el-table>
            <pagination :total="total" :page-size.sync="queryParams.pageSize" :page-sizes="[10, 20, 50]"
                        :page.sync="queryParams.pageNum" @pagination="getList"
            />
          </div>
        </el-col>
      </el-tab-pane>
      <el-tab-pane label="光伏" name="second">
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input v-model="areaName" placeholder="请输入区域名称" clearable size="small"
                      prefix-icon="el-icon-search"
                      style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container" style="height: 100vh; overflow: hidden; position: relative;">
            <el-tree :data="areaOptions" :props="defaultProps" :expand-on-click-node="false"
                     :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current
                     @node-click="handleNodeClick" style="height: calc(100vh - 50px); overflow-y: auto;"
            />
          </div>
        </el-col>
        <el-col :span="20" :xs="24">
          <div class="container-block">
            <el-form size="small" :inline="true" label-width="68px">
              <el-form-item label="地块">
                <template slot-scope="scope">
                  <span>{{ selectedLabel }}</span>
                </template>
              </el-form-item>
            </el-form>
            <BaseChart width="100%" height="300px" :option="pvOptions"/>
          </div>
          <div class="container-block">
            <div class="ctl-container">
              <el-date-picker v-model="dateRange" type="datetimerange" @change="getList" :picker-options="pickerOptions"
                              value-format="yyyy-MM-dd hh:mm:ss" range-separator="至" start-placeholder="开始日期"
                              end-placeholder="结束日期"
                              align="right"
              >
              </el-date-picker>
            </div>
            <el-table v-loading="loading" :data="pvSupplyHList">
              <el-table-column label="日期" align="center" prop="date" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="时间" align="center" prop="time">
                <template slot-scope="scope">
                  <span>{{ scope.row.time }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总发电量(kW·h)" align="center" prop="genElecQuantity"/>
              <el-table-column label="自用电量(kW·h)" align="center" prop="useElecQuantity"/>
              <el-table-column label="上网电量(kW·h)" align="center" prop="upElecQuantity"/>
              <el-table-column label="上网收益(￥)" align="center" prop="upElecEarn"/>
            </el-table>
            <pagination :total="total" :page-size.sync="queryParams.pageSize" :page-sizes="[10, 20, 50]"
                        :page.sync="queryParams.pageNum" @pagination="getList"
            />
          </div>
        </el-col>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { ApiCode } from '@/api/apiEmums'
import { areaWithFacsCategoryAsTree } from '@/api/basecfg/area'
import { get } from '@/api/commonApi'
import { listPgSupplyH, listPvSupplyH } from '@/api/mgr/pgSupplyH'
import BaseChart from '@/components/BaseChart'
import BarChartBlock from '@/components/Block/charts/BarChartBlock.vue'
import PieChartBlock from '@/components/Block/charts/PieChartBlock.vue'
import { DateTool } from '@/utils/DateTool'
import dayjs from 'dayjs'

export default {
  name: 'PgSupplyH',
  dicts: ['meter_type'],
  components: {
    BarChartBlock,
    PieChartBlock,
    BaseChart
  },
  data() {
    return {
      activeName: 'summery',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      facsCategory: '',
      facsSubCategory: '',
      areaName: undefined,
      selectedLabel: '全部',
      pgSupplyHList: [],
      pgSupplyTodayList: [],
      pvSupplyHList: [],
      pvSupplyTodayList: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 查询参数
      queryParams: {
        areaCode: 'all',
        startRecTime: dayjs().subtract(1, 'month').format(DateTool.DateFormat.YYYY_MM_DD_HH_mm),
        endRecTime: dayjs().format(DateTool.DateFormat.YYYY_MM_DD_HH_mm)
      },
      areaOptions: [],
      elecData: [],
      dateRange: [dayjs().format(DateTool.DateFormat.YYYY_MM_DD_00_00_00), dayjs().format(DateTool.DateFormat.YYYY_MM_DD_23_59_59)],
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      elecQuantity: {
        series: [
          {
            type: 'pie',
            data: []
          }
        ]
      },
      elecCost: {
        series: [
          {
            type: 'pie',
            data: []
          }
        ]
      },
      pvSupplyIndex: {
        unit: '  ',
        xAxis: {
          type: 'category',
          data: []
        },
        series: []
      }
    }
  },
  computed: {
    elecOptions() {
      const xData = this.pgSupplyTodayList.map(item => item.time)
      const quantity = this.pgSupplyTodayList.map(item => item.useElecQuantity)
      const cost = this.pgSupplyTodayList.map(item => item.useElecCost)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['供电量', '供电电费']
        },
        xAxis: {
          type: 'category',
          data: xData.reverse(),
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: [
          {
            name: 'kW·h（千瓦时）',
            type: 'value'
          },
          {
            name: '￥（元）',
            type: 'value'
          }
        ],
        series: [
          {
            name: '用电量',
            type: 'bar',
            data: quantity.reverse(),
            barWidth: 30,
            itemStyle: {
              normal: {
                color: '#6395FA'
              }
            }
          },
          {
            name: '用电电费',
            type: 'line',
            yAxisIndex: 1,
            data: cost.reverse(),
            showSymbol: true,
            itemStyle: {
              normal: {
                color: '#5BD9A5'
              }
            }
          }
        ]
      }
      return option
    },
    pvOptions() {
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['自用电量', '上网电量', '上网收益']
        },
        xAxis: {
          type: 'category',
          data: this.pvSupplyTodayList.map(item => item.time).reverse(),
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: [
          {
            name: 'kW·h（千瓦时）',
            type: 'value'
          },
          {
            name: '￥（元）',
            type: 'value'
          }
        ],
        series: [
          {
            name: '自用电量',
            type: 'bar',
            stack: '总数',
            barWidth: 30,
            label: {
              show: false,
              position: 'insideRight'
            },
            data: this.pvSupplyTodayList.map(item => item.useElecQuantity).reverse(),
            itemStyle: {
              normal: {
                color: '#6395FA',
                label: {
                  show: true, // 开启显示
                  position: 'top', // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: '#000',
                    fontSize: 14,
                    fontWeight: 600
                  }
                }
              }
            }
          },
          {
            name: '上网电量',
            type: 'bar',
            stack: '总数',
            barWidth: 30,
            label: {
              show: false,
              position: 'insideRight'
            },
            data: this.pvSupplyTodayList.map(item => item.upElecQuantity).reverse(),
            itemStyle: {
              normal: {
                color: '#8CDF6C',
                label: {
                  show: true, // 开启显示
                  position: 'top', // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: '#000',
                    fontSize: 14,
                    fontWeight: 600
                  }
                }
              }
            }
          },
          {
            name: '上网收益',
            type: 'line',
            yAxisIndex: 1,
            data: this.pvSupplyTodayList.map(item => item.upElecEarn).reverse(),
            smooth: false
          }
        ]
      }
      return option
    }
  },
  watch: {
    // 根据名称筛选区域树
    areaName(val) {
      this.$refs.tree.filter(val)
    }
  },
  async created() {
    await this.getSummery()
  },
  methods: {
    tabClick() {
      if (this.activeName !== 'summery') {
        this.dateRange = [dayjs().format(DateTool.DateFormat.YYYY_MM_DD_00_00_00), dayjs().format(DateTool.DateFormat.YYYY_MM_DD_23_59_59)]
        this.queryParams.areaCode = 'all'
        this.queryParams.pageNum = 1
        this.selectedLabel = '全部'
        this.getTodayList()
        this.getList()
      } else {
        this.getSummery()
      }
    },
    async getSummery() {
      await this.getHSummery()
      await this.getThisDaySummery()
    },
    async getThisDaySummery() {
      const {
        data,
        code
      } = await get('pg/supply/hour/summery/this/day')
      if (ApiCode.SUCCESS !== code || !data) {
        this.elecQuantity.series[0].data = []
        this.elecCost.series[0].data = []
        return
      }
      const {
        pv,
        supply
      } = data
      this.elecQuantity.series[0].data = [
        {
          value: supply?.quantity,
          name: '市电',
          itemStyle: {
            color: '#6395FA'
          }

        },
        {
          value: pv?.useQuantity,
          name: '光伏',
          itemStyle: {
            color: '#8CDF6C'
          }
        }
      ]
      this.elecCost.series[0].data = [
        {
          value: supply?.cost,
          name: '实际电费',
          itemStyle: {
            color: '#6395FA'
          }
        },
        {
          value: pv?.upEarn,
          name: '节省电费',
          itemStyle: {
            color: '#8CDF6C'
          }
        }
      ]

    },
    async getHSummery() {
      const {
        data,
        code
      } = await get('pg/supply/hour/summery/h')
      if (ApiCode.SUCCESS !== code || !data || data.length < 1) {
        return
      }
      const xaxis = DateTool.getTime(60)
      const {
        supply,
        pv
      } = data
      const series = [
        {
          name: '市电',
          type: 'bar',
          barWidth: '30%', // 调整柱状图宽度
          data: [],
          itemStyle: {
            color: '#6395FA'
          }
        },
        {
          name: '光伏',
          type: 'bar',
          barWidth: '30%', // 调整柱状图宽度
          data: [],
          itemStyle: {
            color: '#8CDF6C'
          }
        }

      ]
      xaxis.forEach((item, index) => {
        let timeIndex = index + 1
        if (!pv || !pv[timeIndex]) {
          series[1].data.push(0)
        } else {
          series[1].data.push(pv[timeIndex].useQuantity)
        }
        if (!supply || !supply[timeIndex]) {
          series[0].data.push(0)
        } else {
          series[0].data.push(supply[timeIndex].quantity)
        }
      })
      this.pvSupplyIndex.series = series
      this.pvSupplyIndex.xAxis.data = xaxis
    },
    getTodayList() {
      if (this.activeName === 'first') {
        areaWithFacsCategoryAsTree('W', this.facsSubCategory).then(response => {
          this.areaOptions = [{
            id: 'all',
            label: '全部',
            children: response.data
          }]
        })
        listPgSupplyH({
          startRecTime: dayjs().format(DateTool.DateFormat.YYYY_MM_DD_00_00_00),
          endRecTime: dayjs().format(DateTool.DateFormat.YYYY_MM_DD_23_59_59),
          areaCode: this.queryParams.areaCode,
          pageNum: 1,
          pageSize: 999
        }).then(response => {
          this.pgSupplyTodayList = response.rows
        })
      } else {
        areaWithFacsCategoryAsTree('E', this.facsSubCategory).then(response => {
          this.areaOptions = [{
            id: 'all',
            label: '全部',
            children: response.data
          }]
        })
        listPvSupplyH({
          startRecTime: dayjs().format(DateTool.DateFormat.YYYY_MM_DD_00_00_00),
          endRecTime: dayjs().format(DateTool.DateFormat.YYYY_MM_DD_23_59_59),
          areaCode: this.queryParams.areaCode,
          pageNum: 1,
          pageSize: 999
        }).then(response => {
          this.pvSupplyTodayList = response.rows
        })
      }
    },
    getList() {
      this.loading = true
      this.queryParams.startRecTime = ''
      this.queryParams.endRecTime = ''
      if (this.dateRange && this.dateRange.length) {
        const [startRecTime, endRecTime] = this.dateRange
        this.queryParams.startRecTime = startRecTime
        this.queryParams.endRecTime = endRecTime
      }
      if (this.activeName === 'first') {
        listPgSupplyH(this.queryParams).then(response => {
          this.pgSupplyHList = response.rows
          this.total = response.total
          this.loading = false
        })
      } else {
        listPvSupplyH(this.queryParams).then(response => {
          this.pvSupplyHList = response.rows
          this.total = response.total
          this.loading = false
        })
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.areaCode = data.id
      this.selectedLabel = data.label
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getTodayList()
      this.getList()
    },
    getMeterTypeName(meterType) {
      const meterTypeMap = {
        '-1': '低谷电',
        '0': '平峰电',
        '1': '高峰点',
        '2': '尖峰电'
      }
      return meterTypeMap[meterType] || '平峰电'
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  ::v-deep .el-tabs__content {
    overflow: initial;
  }
}
</style>
<style lang="scss" src="./index.scss"></style>
