<template>
  <el-row>
    <el-col :span="6">
      <div class="box">
        <el-scrollbar>
          <basic-container>
            <avue-tree ref="lazyTree" :option="treeOption" :data="treeData" @node-click="nodeClick" />
          </basic-container>
        </el-scrollbar>
      </div>
    </el-col>
    <el-col :span="18">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>逆变器</span>
            <!-- <el-button class="button" text>Operation button</el-button> -->

            <el-date-picker :clearable="false" v-model="time"
                                        type="date" size="mini" class="fl mr10" style="width: 140px;"
                                        value-format="YYYY-MM-DD" @change="() => { this.initGraph() }"
                                        placeholder="选择日期">
                                    </el-date-picker>
          </div>
        </template>

        <el-row :gutter="10">
          <el-col :span="12">
            <div id="powerChar" style="width: 100%; height: 220px"></div>
          </el-col>
          <el-col :span="12">
            <div id="electriChar" style="width: 100%; height: 220px"></div>
          </el-col>
        </el-row>
      </el-card>

      <el-card style="margin-top: 10px;">
        <el-table :data="deviceList" height="350">
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag  v-if="scope.row.status == 1" type="success">在线</el-tag>
              <el-tag  v-if="scope.row.status == 2" type="info">离线</el-tag>
              <el-tag  v-if="scope.row.status == 3" type="danger">报警</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="sn" label="逆变器SN" />
          <el-table-column prop="status" label="额定功率" >
            <template #default="scope">{{ scope.row.inverterData.realPower }}KW</template>
          </el-table-column>
          <el-table-column prop="status" label="实时功率">
            <template #default="scope">{{ scope.row.inverterData.pac }}KW</template>
          </el-table-column>
          <el-table-column prop="status" label="当日电量">
            <template #default="scope">{{ scope.row.inverterData.etd }}KWh</template>
          </el-table-column>
          <el-table-column prop="inverterData" label="累计电量">
            <template #default="scope">{{ scope.row.inverterData.eto }}KWh</template>
          </el-table-column>
          <el-table-column prop="station" label="所属电站">
            <template #default="scope">{{ scope.row.station.stationName }}</template>
          </el-table-column>
          <el-table-column prop="warrantyExpires" label="质保到期时间" />
          <el-table-column prop="updateTime" label="更新时间" />
          <el-table-column prop="station.startGenDate" label="投运时间" />
          <el-table-column label="操作" >
            <template #default="scope">
              <el-button round @click="showDeviceDetail(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-col>
  </el-row>

  <el-dialog
        v-model="dialogVisible"
        title="设备详情"
        width="60%"
        :before-close="handleClose"
    >
        <DeviceDetail :deviceId="detailId"></DeviceDetail>
    </el-dialog>
</template>

<script>
import 'nprogress/nprogress.css';
import func from '@/utils/func';

import { getLazyTree,getTotalTree } from "@/api/nh/powerStation";
import { getList,getInverterGraph } from "@/api/nh/device";

import DeviceDetail from '@/views/nh/components/deviceDetail.vue'
import * as echarts from 'echarts';
import { formatDate } from '@/utils/date';

export default {
  components: { DeviceDetail },
  data() {
    return {
      dialogVisible: false,
      detailId:"",
      time:"2024-05-27",
      currentDevice:null,
      monitorId:null,
      powerChar: {}, //交流功率图表
      electriChar: {}, //当日发电
      currentNode:{},
      deviceType: 1,
      deviceList: [],
      treeDeptId: '',
      treeData: [],
      treeOption: {
        nodeKey: 'id',
        lazy: localStorage.getItem('power_station_monitor_id')==null,
        treeLoad: function (node, resolve) {
          let parentId = node.level === 0 ? 0 : node.data.id;

          let name = parentId;
          if (node.level === 3) {
            console.log(node.data)
            parentId = node.data.parentId;
            name = node.data.title;
          }
          if (node.level === 4) {
            parentId = node.data.key;
            console.log(node.data)
            name = node.data.title;
          }

          getLazyTree(parentId, name, node.level).then(res => {
            resolve(
              res.data.data.map(item => {
                return {
                  ...item,
                  leaf: !item.hasChildren,
                };
              })
            );
          })
        },
        addBtn: false,
        menu: false,
        filter: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children',
        },
      },
    };
  },
  watch: {

  },
  computed: {


  },
  mounted() {

    this.time = formatDate(new Date(), "day");

    this.powerChar = echarts.init(document.getElementById('powerChar'));
    this.electriChar = echarts.init(document.getElementById('electriChar'));

    //自动缩放图表
    window.addEventListener('resize', ()=> {
      if (this.resizeTimer) clearTimeout(this.resizeTimer);
      this.resizeTimer = setTimeout( ()=>{
        this.powerChar.resize();
        this.electriChar.resize();
      }, 10)
    })

    // this.initToalTreeData();

    this.initMonitorData();
  },
  methods: {
    initMonitorData(){
      this.monitorId = localStorage.getItem('power_station_monitor_id');
      localStorage.removeItem('power_station_monitor_id');
      if(this.monitorId){
        this.initDeviceData(this.monitorId);
      }
    },
    initToalTreeData(){
      getTotalTree().then(res=>{
        console.log(res.data)
        this.treeData = res.data.data.children;
        console.log(this.treeData)
      })
    },
    showDeviceDetail(item){
      this.detailId = item.id;
      this.dialogVisible = true;
    },
    nodeClick(data) {
      console.log(data)
      if (!data.hasChildren) {
        // this.currentNode = data;
        if(!this.monitorId){
          this.initDeviceData(data.id);
        }
      }
    },
    initGraph(){
      getInverterGraph(this.currentDevice.sn,this.time).then(res=>{
        this.setPowerOptions(res.data.data);
        this.setElectriOptions(res.data.data);
      })
    },
    initDeviceData(stationId) {
      let that = this;
      let values = {
        "stationId": stationId,
        "type": 1
      };

      getList(1, 100, values).then(res => {
        const data = res.data.data;
        this.deviceList = data.records;
        if(this.deviceList.length>0){

          // this.currentDevice = this.deviceList[0];

          this.deviceList.forEach(d=>{
            if(d.type==1){
              this.currentDevice = d;
            }
          })
          this.openTreeNodeByStation(this.currentDevice.station)
          that.initGraph();
        }
      });
    },
    openTreeNodeByStation(station){
      console.log(station)
      let that = this;

      let filterKey = station.ownerName+"-"+station.actualCapacity+"KW-"+station.stationCode;

      if(that.monitorId){
        setTimeout(() => {
          that.treeData = [
            {
                "id": "1",
                "parentId": "0",
                "title": station.capitalName,
                children:[
                    {
                      "id": "2",
                      "parentId": "1",
                      "title": station.projectCompanyName,
                      children:[{
                        "id": "3",
                        "parentId": "2",
                        "title": station.city,
                        children:[{
                          "id": "4",
                          "parentId": "3",
                          "title": station.agentName,
                          children:[{
                              "id": that.monitorId,
                              "parentId": "4",
                              "title": filterKey
                          }]
                      }]
                    }]
                  }
                ]
            }
        ];

        setTimeout(() => {
          that.$refs.lazyTree.filter(filterKey);
        }, 100);
        
          // that.$refs.lazyTree.setCurrentKey("319747887726");
          // let node =that.$refs.lazyTree.getCurrentNode();
          // console.log(node)
          // // 重新展开节点就会间接重新触发load达到刷新效果
          // that.$refs.lazyTree.updateKeyChildren(node.key,[{
          //     "id": "测试2",
          //     "parentId": node.id,
          //     "title": "测试2",
          //     "key": "测试2",
          //     "value": "测试2",
          //     "hasChildren": true,
          //     "parentName": ""
          // }])
        }, 100);
      }
      

     
      // setTimeout(() => {
      //   that.$refs.lazyTree.filter(station.capitalName);
      //   setTimeout(() => {
      //     that.$refs.lazyTree.filter(station.projectCompanyName);
      //   }, 500);
      // }, 500);
    },
     //交流功率图表
     setPowerOptions(e) {
      this.powerChar.setOption({
        xAxis: {
          data: e.pacTimeList,
          // data: ['1:00','2:00','3:00','4:00','5:00','6:00','7:00','8:00','9:00','10:00','11:00','12:00','13:00','14:00','15:00','16:00','17:00','18:00','19:00','20:00','21:00','22:00','23:00','24:00'],
          boundaryGap: false,
          axisTick: {
            show: false
          },
          splitLine:{ show: false},
          axisLabel: { show: true, textStyle: { color: '#333333' } },
        },
        yAxis: {
          name: '交流功率(kW)',
          type: 'value',
          axisLine: {
            show: true,
          },
          axisTick:{
            show: false
          },
          axisLabel: { show: true, textStyle: { color: '#333333' } },
          splitLine:{ show: true},
        },
        grid: {
          left: 30,
          right: 30,
          bottom: 10,
          top: 40,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          padding: [5, 20],
        },
        series: [
          {
            name: '功率',
            smooth: true,
            type: 'line',
            itemStyle: {
              normal: {
                color: '#117fbc', //圆点色
                lineStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    {
                      offset: 0,
                      color: "rgba(150,217,255,0.5)"//'#96d9ff'
                    },
                    {
                      offset: 1,
                      color: "rgba(17,127,188,0.5)"//'#117fbc'
                    }
                  ]),//线色
                  width: 2
                },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    {
                      offset: 0,
                      color: "rgba(150,217,255,0.5)"//'#96d9ff'
                    },
                    {
                      offset: 1,
                      color: "rgba(17,127,188,0.5)"//'#117fbc'
                    }
                  ]) //背景色
                }
              }
            },
            data: e.pac,
            // data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24],
            animationDuration: 1000,
            animationEasing: 'quadraticOut'
          },
        ]
      })
    },
    //当日发电图表
    setElectriOptions(e) {
      this.electriChar.setOption({
        xAxis: {
          data: e.etdTimeList,
          boundaryGap: false,
          axisTick: {
            show: false
          },
          splitLine:{ show: false},
          axisLabel: { show: true, textStyle: { color: '#333333' } },
        },
        yAxis: {
          name: '当日发电(kWh)',
          type: 'value',
          axisLine: {
            show: true,
          },
          axisTick:{
            show: false
          },
          axisLabel: { show: true, textStyle: { color: '#333333' } },
          splitLine:{ show: true},
        },
        grid: {
          left: 30,
          right: 30,
          bottom: 10,
          top: 40,
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          padding: [5, 20],
        },
        series: [
          {
            name: '发电量',
            smooth: true,
            type: 'line',
            itemStyle: {
              normal: {
                color: '#117fbc', //圆点色
                lineStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    {
                      offset: 0,
                      color: "rgba(150,217,255,0.5)"//'#96d9ff'
                    },
                    {
                      offset: 1,
                      color: "rgba(17,127,188,0.5)"//'#117fbc'
                    }
                  ]),//线色
                  width: 2
                },
                areaStyle: {
                  color: new echarts.graphic.LinearGradient(0, 0, 1, 1, [
                    {
                      offset: 0,
                      color: "rgba(150,217,255,0.5)"//'#96d9ff'
                    },
                    {
                      offset: 1,
                      color: "rgba(17,127,188,0.5)"//'#117fbc'
                    }
                  ]) //背景色
                }
              }
            },
            data: e.etd,
            animationDuration: 1000,
            animationEasing: 'quadraticOut'
          },
        ]
      })
    },
  },
};
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 20px;
}
</style>
