<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>
          <el-row :gutter="10">
            <el-col v-for="item in deviceModelStatus" :key="item.deviceCode" :span="12" :xs="24">
              <el-card shadow="hover">
                <el-descriptions :title="item.deviceName">
                  <el-descriptions-item label="位置信息">{{ item.location }}</el-descriptions-item>
                  <el-descriptions-item label="设备编码">{{ item.deviceCode }}</el-descriptions-item>
                  <el-descriptions-item v-for="attr in item.attrJson" :key="attr.attr_key" :label="attr.attr_name">{{attr.attr_value}} {{attr.attr_unit}}</el-descriptions-item>
                </el-descriptions>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
        <el-card style="margin-top: 10px;">
          <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="storeList" 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="chargeElecQuantity"/>
              <el-table-column label="放电电量(kW·h)" align="center" prop="dischargeElecQuantity"/>
            </el-table>
            <BaseChart v-else width="100%" height="400px" :option="elecOptions"/>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import {getStoreDayList} from '@/api/mgr/elecStoreH.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'
import {listDeviceModel} from "@/api/device/device";

export default {
  name: 'ElecStoreD',
  components: {
    Treeselect,
    BaseChart,
    SubTitle
  },
  data() {
    const lastWeek = getDayAgoDate(7)
    const nowDay = new Date()
    return {
      // 遮罩层
      loading: true,
      facsCategory: 'E',
      facsSubCategory: '',
      storeList: [],
      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: [],
      deviceModelStatus: [],
      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() {
      const xData = this.storeList.map(item => item.date)
      const chargeQuantity = this.storeList.map(item => item.chargeElecQuantity)
      const dischargeQuantity = this.storeList.map(item => item.dischargeElecQuantity)
      const option = {
        toolbox: {
          itemGap: 10,
          itemSize: 16,
          right: 10,
          top: 0,
          show: true,
          feature: {
            magicType: {
              show: true,
              type: ['bar', 'line']
            },
            saveAsImage: {
              show: true
            }
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            var relVal = params[0].name
            for (var i = 0, l = params.length; i < l; i++) {
              relVal =
                  relVal +
                  '<br/>' +
                  params[i].marker +
                  params[i].seriesName +
                  '&nbsp;&nbsp;&nbsp;' +
                  params[i].value +
                  'kW·h'
            }
            return relVal
          }
        },
        legend: {},
        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
    },

  },
  watch: {
    // 根据名称筛选区域树
    areaName(val) {
      this.$refs.tree.filter(val)
    }
  },
  async created() {
    await this.getAreaList()
    this.getList()
    this.getListDeviceModel()
  },
  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
      const [startRecTime, endRecTime] = this.dateRange
      getStoreDayList({
        areaCode,
        startRecTime,
        endRecTime
      }).then(({code, data}) => {
        this.loading = false
        if (code === 200) {
          this.storeList = 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()
      this.getListDeviceModel()
    },
    async getListDeviceModel() {
      const {data} = await listDeviceModel({
        areaCode: this.queryParams.areaCode,
        subsystemCode: 'SYS_CN',
        attrGroup: 'State'
      })
      this.deviceModelStatus = data
    }
  }
}
</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>
