<template>
  <div style="padding: 0.5%">
    <el-row :gutter="10">
      <el-col :span="24">
          <el-form :inline="true" :model="ruleForm" class="demo-form-inline" style='margin-left: 15px'>
              <el-form-item label="统计指标:">
                  <el-select
                      v-model="formData.tagType"
                      placeholder="请选择"
                      @change="changeload"
                  >
                      <el-option
                          v-for="item in options"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                      >
                      </el-option>
                  </el-select>
              </el-form-item>

              <el-form-item label="负荷类型:">
                  <el-select
                      v-model="value2"
                      multiple
                      collapse-tags
                      :multiple-limit="limit1"
                      placeholder="请选择"
                  >
                      <el-option
                          v-for="item in options2"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                      >
                      </el-option>
                  </el-select>
              </el-form-item>

              <el-form-item label="值类型:">
                  <el-select
                      v-model="value1"
                      multiple
                      collapse-tags
                      :multiple-limit="limit2"
                      placeholder="请选择"
                  >
                      <el-option
                          v-for="item in options1"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                      >
                      </el-option>
                  </el-select>
              </el-form-item>
          </el-form>
      </el-col>
      <el-col :span="24">
        <timepicker
          v-if="falg"
          @querfromdata="querfromdata"
          :type="2"
          :interval="interval"
          :tablename="tablename"
          :thb="true"
        ></timepicker>
      </el-col>
      <el-col :span="24">
        <div
          id="load"
          v-if="activeName == 'tab1'"
          :style="'width:100%;height:' + (tableheight-50) + 'px' "
          ref="fhfx"
        ></div>
      </el-col>
    </el-row>
    <el-dialog
      :close-on-click-modal="false"
      title="负荷对比分析"
      :visible.sync="dialogVisibledd"
      width="70%"
      :before-close="handleClose"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <span style="font-size: 14px; font-weight: bold">统计时间:</span
          ><span style="color: green; font-weight: bold">{{ time }}</span>
          <span style="font-size: 14px; font-weight: bold; margin-left: 1%"
            >统计指标:</span
          ><span style="color: #0066cc; font-weight: bold">{{ title }}</span>
        </el-col>
        <el-col :span="24">
          <div
            id="fxdb"
            :style="
              'width:100%;height:' + (tableheight - 100) + 'px' 
            "
            ref="fxdb"
          ></div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibledd = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibledd = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import ElInputGroup from "@/components/ElInputGroup/el-input-group.vue";
import { getappheight, getheight } from "../../../assets/commjs/common";
import api from "@/api/energy/sysconfig";
import timepicker from "../../components/TimePicker/index4";
import echarts from "echarts";
import FileSaver from "file-saver";
import XLSX from "xlsx";
import json2csv from "json2csv";
export default {
  components: {
    timepicker,
  },
  data() {
    return {
      falg: false,
      t: false,
      activeName: "tab1",
      title: "三相有功功率",
      //time:'2022-03-11 11:45',
      tabname: "tab1",
      limit1: 7,
      limit2: 1,
      //统计指标
      value: 0,
      options: [],
      value1: [0],
      options1: [
        { value: 0, label: "最大值" },
        { value: 1, label: "最小值" },
        { value: 2, label: "平均值" },
      ],
      value2: [],
      options2: [],
      dialogVisibledd: false,
      dialogVisible2: false,
      interval: 4,
      tableData: [],
      checkList: [],
      device: 1,
      tableheight: undefined,
      treedata: [
        {
          id: 0,
          label: "空调负荷",
          children: [
            {
              id: 1,
              label: "1层1号监测点",
            },
            {
              id: 2,
              label: "1层2号监测点",
            },
          ],
        },
        {
          label: "办公负荷",
          id: 11,
          children: [
            {
              id: 12,
              label: "1号楼电梯",
            },
            {
              id: 13,
              label: "1号楼照明",
            },
          ],
        },
        {
          label: "厨房负荷",
          id: 3,
          children: [
            {
              id: 31,
              label: "厨房",
            },
            {
              id: 32,
              label: "保安室",
            },
          ],
        },
      ],
      defaultProps: {
        children: "children",
        label: "label",
      },
      tablename: "tab2",
      form: {
        name: "",
        region: "",
      },
      name: "",
      text: "环比",
      subtext: "最大值",
      shuju: "",
      legend: [],
      xdata: [],
      ydata1: [],
      ydata2: [],
      formData: {
        startTime: "",
        endTime: "",
        startTimeBi: "",
        endTimeBi: "",
        tagType: "",
        loadType: [],
        valType: [0],
      },
      ping: "",
      time: "",
      periodBeginTime: "",
      periodEndTime: "",
      timehuanbiValue: [],
      dw: "kW",
    };
  },
  watch: {
    value2: function () {
      //debugger
      if (this.value2.length == 1) {
        this.limit1 = 1;
        this.limit2 = 3;
      } else {
        this.limit1 = 7;
        this.limit2 = 1;
      }
    },
    value1: function () {
      if (this.value1.length == 1) {
        this.limit1 = 7;
        this.limit2 = 1;
      } else {
        this.limit1 = 1;
        this.limit2 = 3;
      }
    },
  },
  created() {
    this.getTarget();
  },
  mounted() {
    // this.tableheight = getheight();
    // this.device = window.devicePixelRatio;
    // if (this.device == 1) {
    //   this.tableheight = this.tableheight * 2.25;
    // }
    // if (this.device == 1.25) {
    //   this.tableheight = this.tableheight * 1.8;
    // }
    // if (this.device == 1.5) {
    //   this.tableheight = this.tableheight * 1.93;
    // }
    this.tableheight =  window.sessionStorage.getItem('appheight') - 120
    this.$nextTick(() => {
      this.loadtypeEcharts();
      this.constloadtypeEcharts();
    });
  },
  methods: {
    changeload(val) {
      for (var i = 0; i < this.options.length; i++) {
        if (val == this.options[i].id && this.options[i].name == "有功功率") {
          this.dw = "kW";
          this.loadtypeEcharts();
        } else if (
          val == this.options[i].id &&
          this.options[i].name == "无功功率"
        ) {
          this.dw = "kVar";
          this.loadtypeEcharts();
        }
      }
    },
    //获取指标数据
    getTarget() {
      var p = {
        statisticalName: "负荷统计",
      };
      api.getEleStatisticalTree(p).then((res) => {
        if (res.code == "A0000") {
          this.options = res.data.binds;
          this.formData.tagType = this.options[0].id;
          this.getDetail();
        }
      });
    },
    //获取负荷类型
    getDetail() {
      api.getEleLoadSetDetail().then((res) => {
        if (res.code == "A0000") {
          var data = res.data;
          var arr = [];
          var arrId = [];
          for (var i = 0; i < data.length; i++) {
            var p = {
              name: data[i].loadName,
              id: data[i].loadId,
            };
            arrId.push(data[i].loadId);
            arr.push(p);
          }
          this.value2 = arrId;
          this.options2 = arr;
        }
        this.falg = true;
      });
    },
    //tab标签触发切换事件
    handleClick(tab, event) {
      if (tab.name == "tab1") {
        this.tabname = "tab1";
        this.$nextTick(() => {
          this.loadtypeEcharts();
        });
      } else {
        this.tabname = "tab2";
        this.$nextTick(() => {
          this.constloadtypeEcharts();
        });
      }
    },
    //指标策略触发事件
    Indexstrategy() {
      // this.dialogVisible = true
    },
    //树节点触发事件
    handleNodeClick(data) {
      //console.log(data);
    },
    //时间格式化
    dateFormat(dateData1, dateData2) {
      var timearr = [];
      var date = new Date(dateData1);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var f = date.getMinutes();
      f = f < 10 ? "0" + f : f;
      var s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      this.formData.searchBeginTime = y + "-" + m + "-" + d;
      timearr.push(this.formData.startTime);
      var date = new Date(dateData2);
      var y = date.getFullYear();
      var m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      var d = date.getDate();
      d = d < 10 ? "0" + d : d;
      var h = date.getHours();
      h = h < 10 ? "0" + h : h;
      var f = date.getMinutes();
      f = f < 10 ? "0" + f : f;
      var s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      this.formData.searchEndTime = y + "-" + m + "-" + d;
      timearr.push(this.formData.endTime);
      return timearr;
    },
    querfromdata(data, timehbValue, interval) {
      this.interval = interval;
      this.timeValue = data;
      console.log("日期" + this.timeValue);
      this.timehuanbiValue = timehbValue;
      console.log("环比" + this.timehuanbiValue);
      this.periodBeginTime = this.timehuanbiValue[0];
      this.periodEndTime = this.timehuanbiValue[1];
      console.log("开始" + this.periodBeginTime);
      console.log("结束" + this.periodEndTime);
      this.ping = this.periodBeginTime + "至" + this.periodEndTime;
      this.dateFormat(this.timeValue[0], this.timeValue[1]);
      this.time =
        this.formData.searchBeginTime + "至" + this.formData.searchEndTime;
      var arr = [];
      var startTime = this.timeValue[0];
      var year1 = parseInt(startTime.substring(0, 4));
      var month = parseInt(startTime.substring(5, 7));

      var startTimeb = this.periodBeginTime;
      var year2 = parseInt(startTimeb.substring(0, 4));
      var month = parseInt(startTimeb.substring(5, 7));

      arr.push(this.time);
      arr.push(this.ping);
      this.legend = arr;
      for (var i = 0; i < this.options.length; i++) {
        if (this.formData.tagType == this.options[i].id) {
          this.name = this.options[i].name;
        }
      }

      var data = {
        startTime: this.timeValue[0],
        endTime: this.timeValue[1],
        startTimeBi: this.periodBeginTime,
        endTimeBi: this.periodEndTime,
        tagType: this.formData.tagType,
        loadType: this.value2,
        valType: this.value1,
      };
      api.getLoadStatistics(data).then((res) => {
        if (res.code == "A0000") {
          var data = res.data;
          var xdata = [];
          var ydata1 = [];
          var ydata2 = [];
          for (var i = 0; i < data.length; i++) {
            if (
              data[i].afterNum == data[i].beforeNum &&
              data[i].afterNum !== 0 &&
              data[i].beforeNum !== 0
            ) {
              this.t = true;
              ydata1.push(data[i].beforeNum.toFixed(2));
              xdata.push(data[i].loadName);
            } else {
              this.t = false;
              xdata.push(data[i].loadName);
              if (data[i].afterNum == 3.14159) {
                data[i].afterNum = 0.5;
                //data[i].afterNum = data[i].beforeNum*0.01
                // this.shuju = data[i].afterNum
              }
              if (data[i].beforeNum == 3.14159) {
                data[i].beforeNum = 0.5;
                //data[i].beforeNum = data[i].afterNum*0.01
                //this.shuju = data[i].beforeNum
              }
              ydata2.push(data[i].afterNum.toFixed(2));
              ydata1.push(data[i].beforeNum.toFixed(2));
            }
          }

          this.xdata = xdata;
          this.ydata1 = ydata1;

          this.ydata2 = ydata2;
          if (this.text === "环比" && year1 > year2 && !this.t) {
            this.text = "同比";
            this.loadtypeEcharts();
          } else if (this.text === "同比" && year1 > year2 && !this.t) {
            this.text = "环比";
            this.loadtypeEcharts();
          } else {
            if (this.t) {
              this.text = "";
              this.loadtypeEcharts();
            } else {
              this.text = "环比";
              this.loadtypeEcharts();
            }
          }
        }
      });
      // if(d !==''){
      //  this.text='同比'
      //  this.subtext='空调负荷'
      //  this.xdata=['最大值','最小值','平均值']
      //  this.ydata1=[89,35,45],
      //  this.ydata2=[97.89,56.78,35,6]
      //  this.loadtypeEcharts()
      // }
    },
    //负荷策略触发事件
    loadtype() {
      this.dialogVisible2 = true;
    },
    //关闭事件
    handleClose() {
      this.dialogVisibledd = false;
      this.dialogVisible2 = false;
    },
    //负荷分析
    loadtypeEcharts() {
      let echarts = require("echarts");
      var myChart = echarts.init(document.getElementById("load"));
      var option = {
        title: {
          text: this.text,
          //  subtext:this.subtext ,
          left: "center",
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
          formatter: function (params) {
            var tips = "";
            tips +=
              '<span style="font-weight:bold;color:#0099CC">' +
              params[0].name +
              "</span></br/>";
            for (var i = 0; i < params.length; i++) {
              if (params[i].value == 0.5) {
                tips += params[i].seriesName + ":暂无数据<br/>";
              } else {
                tips +=
                  '<span style="">' +
                  params[i].seriesName +
                  '</span>:<span style="font-weight:bold;color:#996600">' +
                  params[i].value +
                  "</span><br/>";
              }
            }
            return tips;
          },
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "2%",
          top: "10%",
          containLabel: true,
        },
        toolbox: {
          feature: {
            // magicType: { show: true, type: ['line', 'bar'] },
            //restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        legend: {
          //	orient: 'vertical',
          data: [
            { name: this.legend[0], itemStyle: { color: "#CC9909" } },
            { name: this.legend[1], itemStyle: { color: "#006666" } },
          ],
          left: "left",
          // itemStyle: {
          //   color:['#00CC33','#0099CC']
          // }
        },
        xAxis: [
          {
            type: "category",
            data: this.xdata,
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "单位(" + this.dw + ")",
            //min: 0,
            // max: 100,
            //interval: 10,
            axisLabel: {
              formatter: "{value}",
            },
          },
        ],
        series: [
          {
            name: this.legend[1],
            barMaxWidth: 45,
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value + "kW";
              },
            },
            data: this.ydata2,
            // barMinHeight: 5,
            itemStyle: {
              normal: {
                color: function (params) {
                  if (params.value == 0.5) {
                    return new echarts.graphic.LinearGradient(
                      0,
                      1,
                      0,
                      0,
                      [
                        {
                          offset: 1,
                          color: "#999999",
                        },
                      ],
                      false
                    );
                  } else {
                    return new echarts.graphic.LinearGradient(
                      0,
                      1,
                      0,
                      0,
                      [
                        {
                          offset: 1,
                          color: "#006666",
                        },
                      ],
                      false
                    );
                  }
                },
              },
            },
            label: {
              show: true,
              position: "top",
              // distance: 10,
              // color: '#fff'
            },
          },
          {
            name: this.legend[0],
            barMaxWidth: 45,
            type: "bar",
            tooltip: {
              valueFormatter: function (value) {
                return value + "kW";
              },
            },
            data: this.ydata1,
            itemStyle: {
              normal: {
                color: function (params) {
                  if (params.value == 0.5) {
                    return new echarts.graphic.LinearGradient(
                      0,
                      1,
                      0,
                      0,
                      [
                        {
                          offset: 1,
                          color: "#999999",
                        },
                      ],
                      false
                    );
                  } else {
                    return new echarts.graphic.LinearGradient(
                      0,
                      1,
                      0,
                      0,
                      [
                        {
                          offset: 1,
                          color: "#CC9909",
                        },
                      ],
                      false
                    );
                  }
                },
              },
            },
            label: {
              show: true,
              position: "top",
              // distance: 10,
              // color: '#fff'
            },
          },
        ],
      };
      // var app = {
      //   currentIndex: -1,
      // };
      // setInterval(function () {
      //   var dataLen = option.series[0].data.length;

      //   // 取消之前高亮的图形
      //   myChart.dispatchAction({
      //     type: 'downplay',
      //     seriesIndex: 0,
      //     dataIndex: app.currentIndex
      //   });
      //   app.currentIndex = (app.currentIndex + 1) % dataLen;
      //   //console.log(app.currentIndex);
      //   // 高亮当前图形
      //   myChart.dispatchAction({
      //     type: 'highlight',
      //     seriesIndex: 0,
      //     dataIndex: app.currentIndex,
      //   });
      //   // 显示 tooltip
      //   myChart.dispatchAction({
      //     type: 'showTip',
      //     seriesIndex: 0,
      //     dataIndex: app.currentIndex
      //   });

      // }, 1000);
      myChart.clear();
      
      option && myChart.setOption(option, true)
window.echartsArr.push(myChart);
      const _this = this;
      //  myChart.on('click', function (params) {
      //           console.log(params)
      //          // alert(params.value)
      //           _this.dialogVisibledd = true
      //            _this.$nextTick(()=>{
      //              _this.loadProportion()
      //          })
      //   })
    },
    //总负荷分析
    constloadtypeEcharts() {
      let echarts = require("echarts");
      var myChart = echarts.init(document.getElementById("zload"));

      const colors = ["#91CC75", "#5470C6"];
      var option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        grid: {
          left: "2%",
          right: "4%",
          bottom: "6%",
          top: "10%",
          containLabel: true,
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            // dataView: { readOnly: false },
            magicType: { type: ["line", "bar"] },
            //restore: {},
            saveAsImage: {},
          },
        },
        legend: {
          data: ["功率因数", "总负荷"],
        },
        xAxis: [
          {
            type: "category",
            axisTick: {
              alignWithLabel: true,
            },
            // prettier-ignore
            data: ['2022-03-11 11:45', '12:45', '13:45', '14:45', '15:45', '16:45', '17:45'],
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "总负荷",
            position: "right",
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: colors[0],
              },
            },
            axisLabel: {
              formatter: "{value}kW",
            },
          },
          {
            type: "value",
            name: "",
            position: "center",
            alignTicks: true,
            offset: 80,
            axisLine: {
              show: false,
              lineStyle: {
                color: colors[1],
              },
            },
            axisLabel: {
              formatter: "{value}kW",
            },
          },
          {
            type: "value",
            name: "功率因数",
            position: "left",
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#EE6666",
              },
            },
            axisLabel: {
              formatter: "{value}",
            },
          },
        ],
        series: [
          {
            name: "总负荷",
            type: "line",
            data: [
              22.0, 40.9, 70.0, 23.2, 25.6, 76.7, 135.6, 62.2, 32.6, 80.0, 86.4,
              73.3,
            ],
          },
          {
            name: "功率因数",
            type: "line",
            yAxisIndex: 2,
            data: [
              0.5, 0.7, 0.78, 0.85, 0.78, 0.9, 0.7, 0.78, 0.64, 0.7, 0.7, 0.9,
            ],
          },
        ],
      };
      var app = {
        currentIndex: -1,
      };
      setInterval(function () {
        var dataLen = option.series[0].data.length;

        // 取消之前高亮的图形
        myChart.dispatchAction({
          type: "downplay",
          seriesIndex: 0,
          dataIndex: app.currentIndex,
        });
        app.currentIndex = (app.currentIndex + 1) % dataLen;
        //console.log(app.currentIndex);
        // 高亮当前图形
        myChart.dispatchAction({
          type: "highlight",
          seriesIndex: 0,
          dataIndex: app.currentIndex,
        });
        // 显示 tooltip
        myChart.dispatchAction({
          type: "showTip",
          seriesIndex: 0,
          dataIndex: app.currentIndex,
        });
      }, 1000);
      myChart.setOption(option)
window.echartsArr.push(myChart);
    },
    //负荷占比分析
    loadProportion() {
      let echarts = require("echarts");
      var myChart = echarts.init(document.getElementById("fxdb"));
      var option = {
        //backgroundColor:"#000a3f",
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          backgroundColor: "rgba(9, 24, 48, 0.5)",
          borderColor: "rgba(75, 253, 238, 0.4)",
          textStyle: {
            color: "#CFE3FC",
          },
          borderWidth: 1,
        },
        grid: {
          top: "15%",
          right: "5%",
          left: "5%",
          bottom: "6%",
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: "none",
            },
            dataView: { readOnly: false },
            magicType: { type: ["line", "bar"] },
            //restore: {},
            saveAsImage: {},
          },
        },
        xAxis: [
          {
            name: "",
            type: "category",
            data: ["总负荷", "光伏发电", "进线"],
            axisLine: {
              lineStyle: {
                show: true,
                color: "#000",
              },
            },
            axisLabel: {
              margin: 10,
              color: "#000",
              textStyle: {
                show: true,
                fontSize: 12,
              },
            },
            axisTick: {
              show: false,
            },
          },
        ],
        yAxis: [
          {
            name: "负荷占比",
            axisLabel: {
              show: true,
              formatter: "{value}%",
              color: "blue",
            },
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: "blue",
              },
            },
            splitLine: {
              lineStyle: {
                color: "#ccc",
              },
            },
          },
        ],
        series: [
          {
            type: "bar",
            data: [200, 152, 185],
            barWidth: "30%",
            itemStyle: {
              normal: {
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: "#009999", // 0% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#009999", // 100% 处的颜色
                    },
                  ],
                  false
                ),
                shadowColor: "#009999",
                shadowBlur: 0,
              },
            },
            label: {
              normal: {
                show: true,
                lineHeight: 10,
                formatter: "{c}",
                position: "top",
                textStyle: {
                  color: "#000",
                  fontSize: 12,
                },
              },
            },
          },
        ],
      };
      myChart.setOption(option)
window.echartsArr.push(myChart);
    },
  },
};
</script>
<style lang='scss' scoped>
.spantext {
  font-size: 14px;
  font-weight: bold;
}
.border {
  border: 1px solid rgb(15, 15, 15);
  height: 20vh;
  width: 100%;
  margin: 0 auto;
}
.check {
  margin-top: 2%;
  margin-left: 25%;
}
.border2 {
  border: 1px solid rgb(15, 15, 15);
}
::v-deep .el-tree {
  color: rgb(1, 15, 27);
  font-weight: bold;
  // background: rgba(46, 64, 70, 0.26);
}
</style>