<template>
  <div class="chart-my-box scada-display-plugin">
    <div class="my-chart jqfa">
      <v-chart ref="chart" style="height:100%; width: 100%" :options="option" />
    </div>
    <div class="icon-div el-icon-setting" @click="dialogFormVisible = true"></div>
    <el-table
      :data="tableData"
      stripe
      :border="true"
      style="width: calc(100% - 50px)"
      height="calc(45% - 1px)"
    >
      <el-table-column width="40" type="index"></el-table-column>
      <el-table-column label="移除" :width="80" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope" :index="scope">
          <span style="cursor: pointer;" @click="deleteFun(scope)">——</span>
        </template>
      </el-table-column>
      <el-table-column label="选择" :width="80" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope" :index="scope">
          <span :style="{color:scope.row.color}">——</span>
        </template>
      </el-table-column>
      <el-table-column
        v-for="col in tableColmn.filter(item => {return value.find(zitem => zitem == item.tag)})"
        :key="col.tag"
        :prop="col.tag"
        :label="col.label"
        :width="col.width?col.width:''"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
    </el-table>
    <el-dialog title="表格调整" :visible.sync="dialogFormVisible" width="600px" top="15%">
      <div class="amazing-box">
        <el-transfer
          v-model="value"
          :props="{
            key: 'tag',
            label: 'label'
          }"
          :titles="['备用列表', '选用列表']"
          :button-texts="['备用属性', '选用属性']"
          :data="tableColmn"
        ></el-transfer>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" @click="settingFun">完成</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
/* eslint-disable */
import ECharts from "vue-echarts/components/ECharts.vue";
import "echarts/lib/chart/bar";
import Api from "./common/apiUtils";
import moment from "moment";
import WebSocketUtils from "../assets/js/WebSocketUtils";
import XLSX from 'xlsx'
export default {
  name: "chart",
  components: {
    "v-chart": ECharts
  },
  props: {
    httpProp: {
      default: ""
    },
  },
  data: function() {
    return {
      dialogFormVisible: false,
      value: [
        "name",
        "timeRange",
        "type",
        "unit",
        "max",
        "min",
        "avg",
        "current"
      ],
      colors: [],
      option: {
        grid: {
          top: "15%",
          left: 80,
          right: 80,
          bottom: 80
        },
        tooltip: {
          show: true,
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "cross" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        axisPointer: {
          link: { xAxisIndex: "all" },
          label: {
            backgroundColor: "#777"
          }
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: "none"
            },
            restore: {},
            dataView: {
              lang:['数据视图','关闭','下载'],
              contentToOption: function(data){
                // let table = document.getElementById('table');
                // let worksheet = XLSX.utils.table_to_sheet(table);
                // let workbook = XLSX.utils.book_new();
                // XLSX.utils.book_append_sheet(workbook, worksheet, 'sheet');
                // 以上四行也可以直接一行搞定，如果不需要对表格数据进行修改的话
                let workbook = XLSX.utils.table_to_book(data.getElementsByTagName("table")[0])
                try {
                  XLSX.writeFile(workbook, 'text.xlsx');
                } catch(e) {
                  console.log(e, workbook);
                }
              },
              backgroundColor:"var(--colorTwo)",
              textColor:"white",
              optionToContent: function(opt) {
                // var axisData = opt.xAxis[0].data;
                var series = opt.series;
                let xIndexArr = [];
                let hashArr = []
                for(let i = 0; i< series.length; i++){
                  series[i].data.forEach(item => {
                    item[0] = moment(item[0]).format("YYYY-MM-DD HH:mm:ss")
                    xIndexArr.push(item[0])
                  })
                  hashArr.push(new Map(series[i].data))
                }
                xIndexArr = Array.from(new Set(xIndexArr));
                xIndexArr.sort((a,b) => {
                  return ((moment(a).toDate().getTime() - moment(b).toDate().getTime()>0)?1:-1)
                })
                var table =
                  '<table style="width:100%;text-align:center"><tbody><tr>' +
                  "<td>时间</td>";
                for(let i in series){
                  table += "<td>" +
                  series[i].name +
                  "</td>"
                }
                table += "</tr>";
                for(let i = 0; i < xIndexArr.length;i++){
                  table += "<tr>" +
                    "<td>" +
                    xIndexArr[i] +
                    "</td>";
                  for(let z = 0; z < hashArr.length;z++){
                    table += "<td>" +
                     (hashArr[z].get(xIndexArr[i])?hashArr[z].get(xIndexArr[i]):"0") +
                    "</td>"
                  }
                  table += "</tr>";
                }
                table += "</tbody></table>";
                return table;
              }
            },
            saveAsImage: {}
          },
          top: "3%",
          right: 80
        },
        legend: {
          type: "scroll",
          show: true,
          left: "center",
          padding: [0, 80],
          top: "9%",
          textStyle: {
            color: "white"
          }
        },
        dataZoom: [
          {
            type: "slider",
            show: true,
            start: 0,
            end: 100
          }
        ],
        markPoint: {
          data: [
            { type: "max", name: "最大值" },
            { type: "min", name: "最小值" }
          ]
        },
        xAxis: {
          type: "time",
          axisLine: {
            lineStyle: {
              color: "#E6E6E6"
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#808080",
              opacity: 0.2
            }
          },
          axisLabel: {
            lineStyle: {
              color: "#E6E6E6"
            }
          }
        },
        yAxis: {
          axisLine: {
            lineStyle: {
              color: "#E6E6E6"
            }
          },
          splitLine: {
            show: true,
            lineStyle: {
              color: "#808080",
              opacity: 0.2
            }
          },
          axisLabel: {
            lineStyle: {
              color: "#E6E6E6"
            }
          }
        },
        series: []
      },
      tableColmn: [
        {
          tag: "name",
          label: "监测点名称"
        },
        {
          tag: "timeRange",
          label: "时间范围"
        },
        {
          tag: "type",
          label: "类型",
          width: 80
        },
        {
          tag: "unit",
          label: "单位",
          width: 80
        },
        {
          tag: "max",
          label: "最大值",
          width: 100
        },
        {
          tag: "min",
          label: "最小值",
          width: 100
        },
        {
          tag: "avg",
          label: "平均值",
          width: 100
        },
        {
          tag: "current",
          label: "当前值",
          width: 100
        }
      ],
      tableData: [],
      legend: []
    };
  },
  created() {
    this.apiUtil = new Api(this.httpProp);
  },
  async mounted() {
    // this.initSocket('C13_B1_TagAI001');
  },
  destroyed() {
    // this.closeWebsocket();
  },
  methods: {
    settingFun() {
      this.dialogFormVisible = false;
      console.log(this.value);
    },
    getRgb() {
      var r = Math.floor(Math.random() * 256);
      var g = Math.floor(Math.random() * 256);
      var b = Math.floor(Math.random() * 256);
      var rgb = "rgb" + "(" + r + "," + g + "," + b + ")";
      return rgb;
    },
    async updateCurve(scadaDatas) {
      // this.$set(this.option,'series',[]);
      this.colors = [];
      this.optionChange = false;
      this.$refs.chart.mergeOptions({ series: [] });
      this.tableData = [];
      var curveDatas = [];
      var tableDatas = [];
      if (!Array.isArray(scadaDatas)) {
        scadaDatas = [];
      }
      if(scadaDatas.length>0){
        for (var i=0; i<scadaDatas.length; i++) {
          let scadaData = scadaDatas[i];
          let color = this.getRgb();
          this.colors.push(color);
          let curveData = {
            name: scadaData["label"],
            type: "line",
            symbol: "none",
            data: scadaData["data"]?scadaData["data"].map(item => {
              return [moment(item.time).toDate(), item.value];
            }):[]
          };
          let datetimeArr = this.$parent.datetime;
          let scadaInfo = this.getScadaInfo(scadaData["id"]);
          let tableData = {
            name: scadaData["label"],
            timeRange: datetimeArr[0].slice(5) + " - " + datetimeArr[1].slice(5),
            type: scadaInfo?scadaInfo.type:scadaData["type"],
            unit: scadaInfo?scadaInfo.unit:scadaData["unit"],
            max: scadaData["max"],
            min: scadaData["min"],
            avg: Number(scadaData["avg"]).toFixed(2), // 保留两位小数
            current: scadaData["current"],
            color: color
          };

          curveDatas.push(curveData);
          tableDatas.push(tableData);
        }
      }
      this.$set(this.option, "series", curveDatas);
      this.option.color = this.colors;
      this.$refs.chart.chart.setOption(this.option, true);
      this.optionChange = true;
      this.tableData = tableDatas;
    },
    getScadaInfo(tag) {
      let checkedNodes = this.$parent.checkedNodes;
      for (var i in checkedNodes) {
        let currentNode = checkedNodes[i];
        if (currentNode["TAG"] == tag) {
          let res = {
            type: currentNode["ZBMARK"],
            unit: currentNode["ZBUNIT"]
          };
          return res;
        }
      }
    },
    deleteFun(val) {
      let index = val.row;
      this.$emit("deleteFun", index);
    }, // 此处以下方法做个websocket 测试
    initSocket(send) {
      this.loading = true;
      this.webSocket = new WebSocketUtils({
        myUrl: "pushreal",
        sendMessage: send,
        webSocketBack: this.messageBack
      });
    },
    messageBack(res, listData) {
      // console.log(res)
      let data = JSON.parse(res.data);
      console.log(data);
    },
    closeWebsocket() {
      if (this.webSocket) {
        this.webSocket.close();
        this.webSocket = null;
      }
    }
  }
};
</script>
<style scoped>
.my-chart {
  width: 100%;
  height: 55%;
  border-bottom: 1px solid gray;
}
.chart-my-box {
  background: var(--colorTwo);
  color: var(--maincolor) !important;
  height: 100%;
}
.icon-div {
  position: absolute;
  top: calc(55% + 1px);
  right: 0px;
  text-align: center;
  height: 35px;
  width: 50px;
  line-height: 35px;
  background: #404040;
  cursor: pointer;
}
.amazing-box {
  display: flex;
  width: 100%;
  justify-content: center;
}
</style>
