<template>
  <div class="app-container">
    <el-row :gutter="10">
      <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">
       <el-card>
        <div class="container-block">
          <div style="display: flex;justify-content: space-between;">
            <SubTitle :title="`发电量-日【${selectedLabel}】`" />
            <el-button-group>
              <el-button v-for="item in btnGroup" :key="item.name" size="mini"
                :type="item.name === activeBtn ? 'primary' : ''" :icon="item.icon" @click="btnChange(item)" />
            </el-button-group>
          </div>
          <div class="ctl-container">
            <el-date-picker v-model="dateRange" type="daterange" @change="getList" :picker-options="pickerOptions"
              value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
              align="right" :clearable="false">
            </el-date-picker>
          </div>
          <el-table v-if="activeBtn == 'table'" v-loading="loading" :data="elecStoreHList" max-height="400px">
            <el-table-column label="日期" align="center" prop="date" width="180">
            </el-table-column>
            <el-table-column label="发电量(kW·h)" align="center" prop="genElecQuantity" />
            <el-table-column label="上网电量(kW·h)" align="center" prop="upElecQuantity" />
            <el-table-column label="自用电量(kW·h)" align="center" prop="useElecQuantity" />
            <el-table-column label="上网收益(元)" align="center" prop="upElecEarn" />
          </el-table>
          <BaseChart v-else width="100%" height="400px" :option="elecOptions" />
        </div>
       </el-card>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import {listPvSupplyD} from '@/api/mgr/pgSupplyH.js'
import { areaTreeByFacsCategory } from '@/api/basecfg/area'
import BaseChart from '@/components/BaseChart'
import SubTitle from '@/components/SubTitle'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {dateFormat, getDayAgoDate} from '@/utils'
export default {
  name: 'ElecStoreD',
  components: {
    Treeselect,
    BaseChart,
    SubTitle
  },
  data () {
    const lastWeek = getDayAgoDate(7)
    const nowDay = new Date()
    return {
      // 遮罩层
      loading: true,
      facsCategory: 'E',
      facsSubCategory: '',
      elecStoreHList: [],
      areaName: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      selectedLabel: '',
      // 查询参数
      queryParams: {
        areaCode: ''
      },
      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])
            }
          }
        ]
      },
      // 表单参数
      areaOptions: [],
      dateRange: [dateFormat(lastWeek, 'yyyy-MM-dd'), dateFormat(nowDay, 'yyyy-MM-dd')],
      activeBtn: 'chart', //--chart图表 --table表格
      btnGroup: [
        {
          name: 'chart',
          icon: 'el-icon-s-data'
        },
        {
          name: 'table',
          icon: 'el-icon-menu'
        }]
    }
  },
  computed: {
    elecOptions () {
      return {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            let relVal = params[0].name
            for (let i = 0, l = params.length; i < l; i++) {
              const unit = params[i].seriesName==='上网收益'?'元':'kW·h'
              relVal =
                relVal +
                '<br/>' +
                params[i].marker +
                params[i].seriesName +
                '&nbsp;&nbsp;&nbsp;' +
                params[i].value + unit
            }
            return relVal
          }
        },
        legend: {
        },
        xAxis: {
          type: 'category',
          data: this.elecStoreHList.map(item => item.date),
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: [
          {
            name: 'kW·h（千瓦时）',
            type: 'value'
          },
          {
            name: '￥（元）',
            type: 'value'
          }
        ],
        dataZoom: [
          {
            type: "slider",
            start: 0,
            end: 40,
            height: 10,
            bottom: '5%',
            showDetail: false,
            showDataShadow: false,
            borderColor: "transparent"
          },
          {
            type: "inside",
            start: 0,
            end: 40,
          },
        ],
        series: [
          {
            name: '自用电量',
            type: 'bar',
            stack: '总数',
            barWidth: 30,
            label: {
              show: false,
              position: 'insideRight'
            },
            data: this.elecStoreHList.map(item => item.useElecQuantity),
            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.elecStoreHList.map(item => item.upElecQuantity),
            itemStyle: {
              normal: {
                color: '#8CDF6C',
                label: {
                  show: true, // 开启显示
                  position: 'top', // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: '#000',
                    fontSize: 14,
                    fontWeight: 600
                  }
                }
              }
            }
          },
          {
            name: '上网收益',
            type: 'line',
            yAxisIndex: 1,
            data: this.elecStoreHList.map(item => item.upElecEarn),
            smooth: false
          }
        ]
      }
    },

  },
  watch: {
    // 根据名称筛选区域树
    areaName (val) {
      this.$refs.tree.filter(val)
    }
  },
  async created () {
    await this.getAreaList()
    this.getList()
  },
  methods: {
    btnChange (item) {
      this.activeBtn = item.name
    },
    // 查询区域列表
    async getAreaList () {
      await areaTreeByFacsCategory(this.facsCategory, this.facsSubCategory, false).then(response => {
        this.areaOptions = [{
          id: '-1',
          label: '全部',
          children: []
        }].concat(response.data)
        this.selectedLabel = '全部'
        this.queryParams.areaCode = '-1'
      })
    },
    /** 查询储能计量-小时列表 */
    getList () {
      this.loading = true
      const {areaCode} = this.queryParams
      let startTime = ''
      let endTime = ''
      if (this.dateRange && this.dateRange.length) {
        const [start, end] = this.dateRange
        startTime = start
        endTime = end
      }
      listPvSupplyD({
        areaCode,
        startTime,
        endTime
      }).then(({code, data}) => {
        this.loading = false
        if (code === 200) {
          this.elecStoreHList = data
        }

      })
    },
    // 筛选节点
    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.getList()
    },
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';

.app-container {
  ::v-deep .el-tabs__content {
    overflow: initial;
  }
}

.ctl-container {
  display: flex;
  justify-content: flex-end;
  margin: 10px 0;
}
</style>
