<template>
  <div>
    <div class="svg-contain">
      <svg
        class="focal"
        id="svg_container"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        xmlns:xlink="http://www.w3.org/1999/xlink"
        style="background-color: #000"
        viewBox="0 0 1920 1080"
        width="100%"
        height="100%"
      >
        <defs />
        <g
          v-for="item in svgLists"
          :key="item.id"
          :id="item.id"
          :title="item.title"
          @click="click(item)"
          style="cursor: pointer"
          :transform="
            'translate(' +
            item.svgPositionX +
            ',' +
            item.svgPositionY +
            ')' +
            'rotate(' +
            item.angle +
            ')' +
            'scale(' +
            item.size +
            ')'
          "
        >
          <SvgComponents
            :component_prop="item"
            :component_type="item.type"
            :component_template="
              svgInfoData.filter((f) => f.type == item.type)[0].template
            "
            :svgInfoData="svgInfoData"
          ></SvgComponents>
        </g>
      </svg>
    </div>
    <div class="btns-content">
      <!-- <el-button type="primary" @click="testF">模拟硬件</el-button>
      <el-button type="primary" @click="testG">取消模拟硬件</el-button> -->
      <el-button
        type="primary"
        icon="el-icon-refresh-left"
        @click="$emit('refresh')"
        >返回</el-button
      >
      <!-- <el-button type="primary" icon="el-icon-refresh-left" @click="send"
        >发送消息</el-button
      > -->
    </div>
  </div>
</template>
<script>
import SvgComponents from "@/components/SvgComponents.vue";
import jquery from "jquery";
import mqtt from "mqtt";
// import MqttWs from "@/components/Mqtt/mqttWs";
import "jquery.panzoom";
export default {
  components: { SvgComponents },
  props: {
    svgId: {
      type: [String],
      default: "",
    },
  },
  data() {
    return {
      svgLists: [],
      svgInfoData: [],
      analogDataTimer: "", //模拟数据定时器
      userInfo: "",
      editable: false,

      mqttWs: null,
      time: null,
    };
  },
  methods: {
    /**
     * @description: 此方法仅为演示使用 真正修改组件数据请判断data_type属性
     * @param {*}
     * @return {*}
     */
    testF() {
      //找出所有断路器
      let anyCircuitBreakerList = this.svgLists.filter(
        (f) => f.type == "CircuitBreakerSvg"
      );
      //找出所有的电线开关
      let anyWireBreakList = this.svgLists.filter(
        (f) => f.type == "WireBreakOnSvg" || f.type == "WireBreakOffSvg"
      );
      //找到所有饼图
      let anyEchartsPieList = this.svgLists.filter(
        (f) => f.type == "EchartsPieSvg"
      );
      //找到所有柱状图
      let anyEchartsBasicBarSvgList = this.svgLists.filter(
        (f) => f.type == "EchartsBasicBarSvg"
      );
      //找到所有文字
      let anyTextList = this.svgLists.filter((f) => f.type == "TextbandinSvg");
      let _this = this;
      this.analogDataTimer = setInterval(function () {
        anyTextList.forEach((anyText) => {
          let strData = anyText.title.substring(anyText.title.length - 3);
          let strData1 = anyText.title.slice(0, -3);
          // console.log(strData1, strData);
          //生成一个随机数
          // let random = Math.round(Math.random() * 10 + 10);
          // let random1 = Math.random(Math.random() * 10 + 10).toFixed(2);
          // strData = Number(random) + Number(random1);
          // console.log(strData);
          // function re() {
          strData = Math.floor(Math.random() * 1000);
          if (strData < 10) {
            strData = "00" + strData;
          } else if (strData < 100) {
            strData = "0" + strData;
          }
          anyText.title = strData1 + strData;
          // console.log(result);
          // }
          // if (strData == "IA:" && anyText.svgColor == "#FF0000") {
          //   anyText.title = strData + (Number(random) + Number(random1));
          // } else if (strData == "IB:" && anyText.svgColor == "#11ff00") {
          //   anyText.title = strData + (Number(random) + Number(random1));
          // } else if (strData == "IC:" && anyText.svgColor == "#ffdd00") {
          //   anyText.title = strData + (Number(random) + Number(random1));
          // } else if (strData == "ID:" && anyText.svgColor == "#FF0000") {
          //   anyText.title = strData + (Number(random) + Number(random1));
          // } else if (strData == "IE:" && anyText.svgColor == "#11ff00") {
          //   anyText.title = strData + (Number(random) + Number(random1));
          // } else if (strData == "IF:" && anyText.svgColor == "#ffdd00") {
          //   anyText.title = strData + (Number(random) + Number(random1));
          // }
        });
        anyCircuitBreakerList.forEach((anyCircuitBreaker) => {
          //生成一个随机数
          let random = Math.round(Math.random() * 10);
          if (random < 5) {
            anyCircuitBreaker.svgColor = "#00FF00";
          } else {
            anyCircuitBreaker.svgColor = "#FF0000";
          }
        });

        anyWireBreakList.forEach((anyWireBreak) => {
          //生成一个随机数
          let random = Math.round(Math.random() * 10);
          // console.log(random,'======================');
          // console.log(_this.svgLists,'======================');
          if (random < 5) {
            anyWireBreak.type = "WireBreakOnSvg";
            _this.svgLists.splice(
              _this.svgLists.findIndex((item) => item.id === anyWireBreak.id),
              1
            );
            anyWireBreak.svgColor = "#00FF00";
            anyWireBreak.typeName = "电线开关-连接";
            anyWireBreak.title = "电线开关-连接";
            setTimeout(() => {
              _this.svgLists.push(anyWireBreak);
            }, 0);
          } else {
            anyWireBreak.type = "WireBreakOffSvg";
            _this.svgLists.splice(
              _this.svgLists.findIndex((item) => item.id === anyWireBreak.id),
              1
            );
            anyWireBreak.svgColor = "#FF0000";
            anyWireBreak.typeName = "电线开关-断开";
            anyWireBreak.title = "电线开关-断开";
            setTimeout(() => {
              _this.svgLists.push(anyWireBreak);
            }, 0);
          }
        });
        anyEchartsPieList.forEach((anyEchartsPie) => {
          anyEchartsPie.echartsOption.series[0].data.forEach((f) => {
            //生成一个随机数
            let random = Math.round(Math.random() * 100);
            f.value = random;
          });
        });
        anyEchartsBasicBarSvgList.forEach((anyEchartsBasicBar) => {
          let data_arr = [
            Math.round(Math.random() * 300),
            Math.round(Math.random() * 300),
            Math.round(Math.random() * 300),
            Math.round(Math.random() * 300),
            Math.round(Math.random() * 300),
            Math.round(Math.random() * 300),
            Math.round(Math.random() * 300),
          ];
          anyEchartsBasicBar.echartsOption.series[0].data = data_arr;
        });
      }, 2000);
    },
    send() {
      this.mqttWs.publish("/zl/askRtData/" + this.svgId);
    },
    testG() {
      clearInterval(this.analogDataTimer);
    },
    click(e) {
      // e.title = 12312;
      // console.log('title', e);
    },
    // 链接WebSocket
    WebSocketTest() {
      this.mqttWs = {};
      let _this = this;

      const options = {
        protocolId: "MQTT",

        clean: true,
        connectTimeout: 30 * 1000,
        clientId: "mqttjs" + Math.random(),
        username: "t_user",
        password: "njcnpqs",
      };
      const url = "ws://192.168.1.13:8083/mqtt";
      _this.mqttWs = mqtt.connect(url, options);
      _this.mqttWs.on("error", (err) => {
        // console.log("mqtt连接失败...", error);
        _this.mqttWs.end();
      });

      _this.mqttWs.on("connect", (e) => {
        // console.log("mqtt客户端已连接....");
        // 订阅消息
        _this.mqttWs.subscribe("/zl/rtData/#");
        _this.mqttWs.publish("/zl/askRtData/" + this.svgId);
        clearInterval(_this.time);
        _this.time = setInterval(() => {
          _this.mqttWs.publish("/zl/askRtData/" + this.svgId);
        }, 3 * 60 * 1000);
      });
      // 接受消息
      _this.mqttWs.on("message", (topic, message, packet) => {
        let messageList = JSON.parse(message);

        setTimeout(() => {
          messageList.forEach((val) => {
            this.svgLists.forEach((item) => {
              if (item.id == val.id) {
                let title = item.title
                  .replace(/无相别-/, "")
                  .replace(/-平均值/, "")
                  .replace(/-CP95/, "")
                  .replace(/-最大值/, "")
                  .replace(/-最小值/, "")
                  .replace(
                    /###/,
                    val.value == 3.1415926 ? "暂无数据" : val.value
                  );
                item.title = title;
                return;
              }
            });
          });
          // this.send()
        }, 200);
      });
      _this.mqttWs.on("close", () => {
        // console.log("mqtt客户端已断开连接.....");
      });
    },
  },
  created() {
    let _this = this;

    //请求接口获取组件
    this.$axios
      .get("/webtopo-svgeditor/InterfaceReturn.json")
      .then(function (response) {
        _this.svgInfoData = response.data;
        // console.log(response.data);
        //渲染组件
        _this.svgLists = JSON.parse(localStorage.getItem("svginfo"));
        // console.log("+++++++++++++++++++++++++++", _this.svgLists);
      })
      .catch(function (error) {});
  },
  destroyed() {
    clearInterval(this.time);
    if (this.mqttWs.connected) {
      try {
        this.mqttWs.end();
        this.mqttWs = {
          connected: false,
        };
        // console.log("Successfully disconnected!");
      } catch (error) {
        // console.log("Disconnect failed", error.toString());
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.WebSocketTest();

      let zoom = jquery("#svg_container").panzoom({
        minScale: 0, //最小和最大放大比例
        maxScale: 10,
        linearZoom: true,
        increment: 10, //要放大的增量，大于0
        duration: 200, //动画时间（ms）
        easing: "ease-in-out", //CSS简化用于缩放过渡
      });

      let $panzoom = jquery(".focal").panzoom();
      $panzoom.parent().on("mousewheel.focal", function (e) {
        e.preventDefault();
        let delta = e.delta || e.originalEvent.wheelDelta;
        let zoomOut = delta ? delta < 0 : e.originalEvent.deltaY > 0;
        $panzoom.panzoom("zoom", zoomOut, {
          increment: 0.1,
          animate: false,
          focal: e,
        });
      });
    });
  },
};
</script>
<style scoped lang="less">
// .svg-contain {

// }
.btns-content {
  position: absolute;
  top: 20px;
  right: 10px;
  z-index: 9999;
  button {
    margin-right: 10px;
  }
}
</style>
