<template>
  <div>
    <div id="log-box" v-html="content"></div>
  </div>
</template>
<script>
import request from '@/utils/request2';

var _this;
var socket;
var sit;
export default {
  name: "log",
  data() {
    return {
      modelId: '',
      type: '',
      content: ''
    }
  },
  mounted() {
    _this = this;
  },
  methods: {
    close() {
      if (sit) {
        clearInterval(sit);
      }
      _this.content = "";
      if (socket) {
        socket.close();
      }
    },
    init({modelId, type}) {
      _this.content = "";
      _this.modelId = modelId;
      _this.type = type;
      console.log(`当前modelId为${modelId},type为${type}`);
      socket = new WebSocket(`ws://47.103.128.32:10050/socket/file-tail?modelId=${modelId}&type=${type}`);
      //连接打开事件
      socket.onopen = function () {
        console.log("Socket 已打开");
      };
      //收到消息事件
      socket.onmessage = function (msg) {
        if (msg.data.indexOf('连接成功，sessionId=') != -1) {
          var sessionId = msg.data.slice(15);
          console.log(sessionId)
        } else {
          // console.log(msg);
          _this.content += '<p>' + msg.data + "</p>";
          _this.$nextTick(() => {
            document.getElementById("log-box").scrollTop = 100000;
          });
        }
      };
      //连接关闭事件
      socket.onclose = function () {
        console.log("Socket已关闭");
      };
      //发生了错误事件
      socket.onerror = function () {
        alert("Socket发生了错误");
      }


      //创建心跳，防止掉线
      sit = setInterval(() => {
        let op = {
          data: "heart",
        };
        sendJson(op);
      }, 5000);

    }
  }
}


function sendJson(data) {
  // 0        CONNECTING        连接尚未建立
  // 1        OPEN            WebSocket的链接已经建立
  // 2        CLOSING            连接正在关闭
  // 3        CLOSED            连接已经关闭或不可用
  if (socket.readyState == 2 || socket.readyState == 3) {
    clearInterval(sit);
    sit = null;
  } else {
    socket.send(JSON.stringify(data));
  }
}

</script>

<style lang="scss">
#log-box {
  height: 800px;
  overflow-y: auto;
  background-color: #c2c2c2;
  border-radius: 5px;
  padding: 0 25px;
}

#log-box p {
  line-height: 30px;
  font-size: 16px;
  text-indent: 2em;
  color: #313131;
}
</style>
