<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">
        <div class="container-block">
          <el-card>
            <div style="display: flex;justify-content: space-between;">
            <SubTitle :title="`平均功率-15分钟【${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="datetimerange" @change="getPowerChart"
              :picker-options="pickerOptions" value-format="yyyy-MM-dd hh:mm:ss" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" align="right" :clearable="false">
            </el-date-picker>
          </div>
          <el-table v-if="activeBtn == 'table'" :data="powerChartData" max-height="400px">
            <el-table-column label="日期" align="center" prop="date" width="100" fixed="left">
            </el-table-column>
            <el-table-column label="时间" align="center" prop="time" width="100" fixed="left">
            </el-table-column>
            <el-table-column label="电流(A)" align="center" show-overflow-tooltip width="200">
              <template slot-scope="scope">
                <span>A相:{{ scope.row.la }}A;</span>
                <span>B相:{{ scope.row.lb }}A;</span>
                <span>C相:{{ scope.row.lc }}A</span>
              </template>
            </el-table-column>
            <el-table-column label="电压(V)" align="center" show-overflow-tooltip width="200">
              <template slot-scope="scope">
                <span>A相:{{ scope.row.ua }}V;</span>
                <span>B相:{{ scope.row.ub }}V;</span>
                <span>C相:{{ scope.row.uc }}V</span>
              </template>
            </el-table-column>
            <el-table-column label="有功功率(kW)" align="center" show-overflow-tooltip width="250" >
              <template slot-scope="scope">
                <span>A相:{{ scope.row.pa }}kW;</span>
                <span>B相:{{ scope.row.pb }}kW;</span>
                <span>C相:{{ scope.row.pc }}kW</span>
              </template>
            </el-table-column>
            <el-table-column label="无功功率(kW)" align="center" show-overflow-tooltip width="250" >
              <template slot-scope="scope">
                <span>A相:{{ scope.row.qa }}kW;</span>
                <span>B相:{{ scope.row.qb }}kW;</span>
                <span>C相:{{ scope.row.qc }}kW</span>
              </template>
            </el-table-column>
            <el-table-column label="功率因素" align="center" prop="pf" width="100" />
          </el-table>
          <BaseChart v-else width="100%" height="400px" :option="powerLineOptions" />
          </el-card>
          <el-card style="margin-top: 10px;">
            <div style="display: flex;justify-content: space-between;">
            <SubTitle :title="`峰值功率-日【${selectedLabel}】`" />
            <el-date-picker v-model="maxPowerDate" type="daterange" @change="getDayMaxLoad"
              :picker-options="pickerOptions" value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" align="right" :clearable="false">
            </el-date-picker>
          </div>
          <BaseChart width="100%" height="400px" :option="maxLoadLineOptions" />
          </el-card>

        </div>
      </el-col>
    </el-row>
  </div>
</template>


<script>
import {getPowerData, getPowerMaxLoad, getPowerDayMaxLoad} from '@/api/mgr/elecUseH'
import {areaWithFacsCategoryAsTree} 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: 'Comsume',
  components: {
    Treeselect,
    BaseChart,
    SubTitle
  },
  data () {
    const lastWeek = dateFormat(getDayAgoDate(7), 'yyyy-MM-dd')
    const nowDay = dateFormat(new Date(), 'yyyy-MM-dd')
    return {
      // 遮罩层
      facsCategory: 'Z',
      facsSubCategory: '',
      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: [`${lastWeek} 00:00:00`, `${nowDay} 23:59:59`],
      activeBtn: 'chart', //--chart图表 --table表格
      btnGroup: [
        {
          name: 'chart',
          icon: 'el-icon-s-data'
        },
        {
          name: 'table',
          icon: 'el-icon-menu'
        }],
      powerChartData: [],
      powerMaxLoad: '',
      maxPowerDate: [`${lastWeek} 00:00:00`, `${nowDay} 23:59:59`],
      maxLoadData: []
    }
  },
  computed: {
    powerLineOptions () {
      const xAxisData = this.powerChartData.map(item => `${item.date.substr(5)} ${item.time.substr(0, 5)} `);
      const yData1 = this.powerChartData.map(item => parseFloat(item.s).toFixed(2));
      const yData2 = this.powerChartData.map(item => item.p);
      const yData3 = this.powerChartData.map(item => item.q);
      return {
        toolbox: {
          itemGap: 10,
          itemSize: 16,
          right: 10,
          top: 0,
          show: true,
          feature: {
            magicType: {
              show: true,
              type: ['bar', 'line']
            },
            saveAsImage: {
              show: true
            }
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            var relVal = params[0].name
            for (var i = 0, l = params.length; i < l; i++) {
              const unit = 'kW'
              relVal =`${relVal}<br/>${params[i].marker}${params[i].seriesName}&nbsp;&nbsp;&nbsp;${params[i].value}${unit}`
            }
            return relVal
          }
        },
        legend: {
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          name: 'kW（千瓦）',
          type: 'value',
        },
        dataZoom: [
          {
            type: "slider",
            start: 0,
            end: 100,
            height: 10,
            bottom: '5%',
            showDetail: false,
            showDataShadow: false,
            borderColor: "transparent"
          },
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
        series: [{
          name: '视在功率',
          type: 'line',
          data: yData1,
          markLine: {
            symbol: 'none',
            silent: true,
            lineStyle: {normal: {type: 'dashed'}},
            label: {position: 'end'},
            data: [
              {
                yAxis: this.powerMaxLoad,
                lineStyle: {width: 1.656, color: '#ff6367'},
                label: {
                  show: true,
                  textStyle: {
                    color: '#ff6367'
                  }
                }
              },
            ]
          },
          markPoint: {
            silent: true,
            data: [
              {
                yAxis: this.powerMaxLoad,
                x: '100%',
                symbolSize: 0.1,
                symbolOffset: [0, 0],
                label: {
                  textStyle: {color: '#ff6367'},
                  fontSize: 12,
                  position: 'left',
                  formatter: '最高负荷'
                }
              },
            ]
          },
        },
        {
          name: '有功功率',
          type: 'line',
          data: yData2,
        },
        {
          name: '无功功率',
          type: 'line',
          data: yData3,
        },]
      };
    },
    maxLoadLineOptions () {
      const xAxisData = this.maxLoadData.map(item => item.date);
      const yData1 = this.maxLoadData.map(item => parseFloat(item.s).toFixed(2));
      const yData2 = this.maxLoadData.map(item => item.p);
      const yData3 = this.maxLoadData.map(item => item.q);
      return {
        toolbox: {
          itemGap: 10,
          itemSize: 16,
          right: 10,
          top: 0,
          show: true,
          feature: {
            magicType: {
              show: true,
              type: ['bar', 'line']
            },
            saveAsImage: {
              show: true
            }
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: (params) => {
            var relVal = params[0].name
            for (var i = 0, l = params.length; i < l; i++) {
              const unit = 'kW'
              relVal =`${relVal}<br/>${params[i].marker}${params[i].seriesName}&nbsp;&nbsp;&nbsp;${params[i].value}${unit}`
            }
            return relVal
          }
        },
        legend: {
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          name: 'kW（千瓦）',
          type: 'value',
        },
        dataZoom: [
          {
            type: "slider",
            start: 0,
            end: 100,
            height: 10,
            bottom: '5%',
            showDetail: false,
            showDataShadow: false,
            borderColor: "transparent"
          },
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
        series: [{
          name: '视在功率',
          type: 'line',
          data: yData1,
        },
        {
          name: '有功功率',
          type: 'line',
          data: yData2,
        },
        {
          name: '无功功率',
          type: 'line',
          data: yData3,
        },]
      };
    },

  },
  watch: {
    // 根据名称筛选区域树
    areaName (val) {
      this.$refs.tree.filter(val)
    }
  },
  async created () {
    await this.getAreaList()
    this.getPowerChart()
    this.getDayMaxLoad()
  },
  methods: {
    btnChange (item) {
      this.activeBtn = item.name
    },
    getPowerChart () {
      this.powerMaxLoad = ''
      this.powerChartData = []
      const [startTime, endTime] = this.dateRange
      const params = {
        startTime,
        endTime,
        areaCode: this.queryParams.areaCode,
        objType: '1',
      }
      getPowerData({
        ...params,
        pageNum: 1,
        pageSize: 999
      }).then(({code, rows}) => {
        if (code === 200) {
          this.powerChartData = rows
        }
      })
      getPowerMaxLoad(params).then(({code, data}) => {
        if (code === 200) {
          this.powerMaxLoad = parseFloat(data.s).toFixed(2)
        }
      })
    },
    getDayMaxLoad () {
      const [startTime, endTime] = this.maxPowerDate
      getPowerDayMaxLoad({
        startTime,
        endTime,
        areaCode: this.queryParams.areaCode,
        objType: '1',
      }).then(({code, rows}) => {
        if (code === 200) {
          this.maxLoadData = rows || []
        }
      })
    },
    // 查询区域列表
    async getAreaList () {
      await areaWithFacsCategoryAsTree(this.facsCategory, this.facsSubCategory).then(response => {
        this.areaOptions = [{
          id: '-1',
          label: '全部',
          children: []
        }].concat(response.data)
        this.selectedLabel = '全部'
        this.queryParams.areaCode = '-1'
      })
    },
    // 筛选节点
    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.getPowerChart()
      this.getDayMaxLoad()
    },
  }
}
</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>
