<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="tabClick">
      <el-tab-pane label="总览" name="summary">
        <div class="chartGroup">
          <Block title="当日充电量【单位：kW·h】">
            <div class="block-area" slot="main">
              <div class="center-label">
                <div>总充电量</div>
                <div>{{ daySum.chargeElecQuantity }}kW·h</div>
              </div>
              <BaseChart width="100%" height="500px" :option="chargePieOptions" />
            </div>
          </Block>
          <Block title="当日放电量【单位：kW·h】">
            <div class="block-area" slot="main">
              <div class="center-label">
                <div>总放电量</div>
                <div>{{ daySum.dischargeElecQuantity }}kW·h</div>
              </div>
              <BaseChart width="100%" height="500px" :option="disChargePieOptions" />
            </div>
          </Block>
        </div>
      </el-tab-pane>
      <el-tab-pane label="区块储能" name="area">
        <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">
            <SubTitle :title="`时段储能数据【${selectedLabel}】`" />
            <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" :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="elecStoreHList" max-height="400px">
              <el-table-column label="日期" align="center" prop="date" width="180">
              </el-table-column>
              <el-table-column label="时间" align="center" prop="time">
              </el-table-column>
              <el-table-column label="充电电量(kW·h)" align="center" prop="chargeElecQuantity" />
              <el-table-column label="放电电量(kW·h)" align="center" prop="dischargeElecQuantity" />
            </el-table>
          </div>
        </el-col>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {listElecStoreH, dayStatistics} from '@/api/mgr/elecStoreH'
import {areaWithFacsCategoryAsTree} from '@/api/basecfg/area'
import {dateFormat} from '@/utils/index.js'
import dayjs from 'dayjs'
import {DateTool} from '@/utils/DateTool'
import BaseChart from '@/components/BaseChart'
import SubTitle from '@/components/SubTitle'
import Block from '@/components/Block/block.vue'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: 'ElecStoreH',
  components: {
    Treeselect,
    BaseChart,
    Block,
    SubTitle
  },
  data () {
    return {
      activeName: 'summary',
      // 遮罩层
      loading: true,
      facsCategory: '',
      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: [],
      hourSum: [],
      daySum: {},
      todayList: [],
      dateRange: [dayjs().format(DateTool.DateFormat.YYYY_MM_DD_00_00_00), dayjs().format(DateTool.DateFormat.YYYY_MM_DD_23_59_59)]
    }
  },
  computed: {
    elecOptions () {
      const xData = this.todayList.map(item => item.time)
      const chargeQuantity = this.todayList.map(item => item.chargeElecQuantity)
      const dischargeQuantity = this.todayList.map(item => item.dischargeElecQuantity)
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['充电电量', '放电电量']
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisPointer: {
            type: 'shadow'
          }
        },
        yAxis: [
          {
            name: 'kW·h（千瓦时）',
            type: 'value'
          }
        ],
        series: [
          {
            name: '充电电量',
            type: 'bar',
            data: chargeQuantity,
            barWidth: 20,
            itemStyle: {
              normal: {
                color: '#6395FA'
              }
            }
          },
          {
            name: '放电电量',
            type: 'bar',
            data: dischargeQuantity,
            barWidth: 20,
            itemStyle: {
              normal: {
                color: '#8CDF6C'
              }
            }
          }
        ]
      }
      return option
    },
    chargePieOptions () {
      return {
        tooltip: {
          trigger: 'item'
        },
        series: [

          {
            name: '充电量',
            type: 'pie',
            radius: [50, 150],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            data:
              this.hourSum.map(item => ({
                name: item.time,
                value: item.chargeElecQuantity
              }))
          }
        ]
      }
    },
    disChargePieOptions () {
      return {
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '放电量',
            type: 'pie',
            radius: [50, 150],
            center: ['50%', '50%'],
            roseType: 'area',
            itemStyle: {
              borderRadius: 8
            },
            data: this.hourSum.map(item => ({
              name: item.time,
              value: item.dischargeElecQuantity
            }))
          }
        ]
      }
    }

  },
  watch: {
    // 根据名称筛选区域树
    areaName (val) {
      this.$refs.tree.filter(val)
    }
  },
  async created () {
    this.facsCategory = 'C'
    await this.getAreaList()
    this.tabClick()
  },
  methods: {
    // 查询区域列表
    async getAreaList () {
      await areaWithFacsCategoryAsTree(this.facsCategory, this.facsSubCategory).then(response => {
        this.areaOptions = [{
          id: '-1',
          label: '全部',
          children: response.data
        }]
      })
    },
    /** 查询储能计量-小时列表 */
    getList () {
      this.loading = true
      const {areaCode} = this.queryParams
      let startRecTime = ''
      let endRecTime = ''
      if (this.dateRange && this.dateRange.length) {
        const [start, end] = this.dateRange
        startRecTime = start
        endRecTime = end
      }
      listElecStoreH({
        areaCode,
        pageNum: 1,
        pageSize: 999,
        startRecTime,
        endRecTime
      }).then(response => {
        this.elecStoreHList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getTodayChart () {
      const {areaCode} = this.queryParams
      const nowDay = dateFormat(new Date(), 'yyyy-MM-dd')
      listElecStoreH({
        areaCode,
        pageNum: 1,
        pageSize: 999,
        startRecTime: `${nowDay} 00:00:00`,
        endRecTime: `${nowDay} 23:59:59`
      }).then(response => {
        this.todayList = response.rows
      })
    },
    getSummary () {
      dayStatistics({date: dateFormat(new Date(), 'yyyy-MM-dd')}).then(({code, data}) => {
        if (code === 200) {
          this.hourSum = data.hourSum || []
          this.daySum = data.daySum || {}
        }
      })
    },
    // 筛选节点
    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()
      this.getTodayChart();
    },
    /** 搜索按钮操作 */
    tabClick () {
      if (this.activeName === 'summary') {
        this.getSummary()
      } else {
        this.selectedLabel = '全部'
        this.queryParams.areaCode = '-1'
        this.getAreaList()
        this.getTodayChart()
        this.getList()
      }
    }
  }
}
</script>

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

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

.chartGroup {
  display: flex;

  >div {
    flex: 1;

  }

  .block-area {
    position: relative;
    width: 100%;
  }

  .center-label {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
  }
}
</style>
