<template>
  <el-dialog
    :title="'工作流日志'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <!-- <el-form :model="dataForm" ref="dataForm" label-width="160px">
      <el-form-item class="boxformitem"> -->
    <div style="width:'10%',height:'100%'">
      <el-radio-group
        v-model="containertype"
        default-value="main"
        @change="workflowcontainerchange"
      >
        <el-radio label="main" value="main">main</el-radio>
        <el-radio label="init" value="init">init</el-radio>
        <el-radio label="wait" value="wait">wait</el-radio>
      </el-radio-group>
      <!-- <div class="log-box"> -->
      <div class="log-box" style="position: relative; overflow: scroll">
        <div
          v-if="
            this.workflowContentlogsplit && this.workflowContentlogsplit.length
          "
        >
          <p
            class="logList-item"
            v-for="(item, index) in this.workflowContentlogsplit"
            :key="index"
          >
            {{ item }}
          </p>
        </div>
        <p v-else>暂无数据</p>
      </div>
      <!-- </div> -->

      <!-- <a-descriptions
        title=""
        layout="vertical"
        bordered
        style="white-space: pre-wrap"
      >
        <a-descriptions-item>
          {{ this.workflowContentlog }}
        </a-descriptions-item>
      </a-descriptions> -->
      <!-- </a-layout-footer> -->
    </div>
    <!-- </el-form-item>
    </el-form> -->
    <!-- <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span> -->
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        modelName: "",
      },

      workflowName: "", //提交后的工作流名称
      workflowContent: { main: "暂无数据", wait: "暂无数据", init: "暂无数据" },
      workflowContentlog: "",
      workflowContentlogsplit: [],
      workflowStatus: "", //记录工作流状态

      containertype: "main",
      websocket: null,
      log: "", // 日志内容
      logCache: "",
      websocket: null,
      socketTimer: null,
    };
  },
  methods: {
    // init1(cell, celldata, workflowName) {
    //   this.visible = true;
    //   this.workflowName = workflowName;
    //   // this.wftemplateName = celldata.wftemplatename;
    //   //此时celldata.sourcealgocell == null
    // },
    init(workflowName) {
      this.visible = true;
      this.workflowName = workflowName;
      // this.createWebsocket();
      var intervalID = window.setInterval(() => {
        // this.getWorkflowStatus();
        this.$http({
          url: this.$http.adornUrl("/visi/visiworkflow/getworkflowlog2"),
          method: "get",
          params: this.$http.adornParams({
            workflowName: this.workflowName,
          }),
        })
          .then(({ data }) => {
            if (data && data.code === 0) {
              this.$nextTick(() => {
              this.workflowContent = data.workflowContent;
              if (this.containertype == "main") {
                this.workflowContentlog = this.workflowContent.main;
                this.workflowContentlogsplit =
                  this.workflowContent.main.split(/[(\r\n)\r\n]+/);
              }
              if (this.containertype == "init") {
                this.workflowContentlog = this.workflowContent.init;
                this.workflowContentlogsplit =
                  this.workflowContent.init.split(/[(\r\n)\r\n]+/);
              }
              if (this.containertype == "wait") {
                this.workflowContentlog = this.workflowContent.wait;
                this.workflowContentlogsplit =
                  this.workflowContent.wait.split(/[(\r\n)\r\n]+/);
              }
              this.workflowStatus = data.workflowStatus;
              // this.handleLog();
              // this.podlogs = data.podlogs;
              
              // console.log("workflowcontent");
              // console.log(this.workflowContent);
              // console.log(this.workflowContent.main);
              // console.log(this.workflowContent.init);
              // console.log(this.workflowContent.wait);
              // console.log(this.workflowStatus);

              // console.log("podlogs")
              // console.log(this.podlogs);
            });
            }
            
          })
          .then(() => {
            // this.visible = true
            // this.$nextTick(() => {
            //   this.$refs['dataForm'].resetFields()
            // })
            // 取消该定时设置
            if (
              this.workflowStatus == "Succeeded" ||
              this.workflowStatus == "Error" ||
              this.workflowStatus == "Failed"
            ) {
              // if (this.workflowStatus == "Succeeded") {
              //   this.workflowstatustag.name = "Succeeded";
              //   this.workflowstatustag.type = "success";
              // } else if (
              //   this.workflowStatus == "Error" ||
              //   this.workflowStatus == "Failed"
              // ) {
              //   this.workflowstatustag.name = "Failed";
              //   this.workflowstatustag.type = "danger";
              // }
              console.log("关闭定时器-workflowlog");
              window.clearInterval(intervalID);
            }
          });
      }, 5000);
    },
    init1() {
      this.visible = true;
      this.workflowContentlog = this.workflowContent.main;
      this.workflowContentlogsplit =
        this.workflowContent.main.split(/[(\r\n)\r\n]+/);
      //暂未生成workflowname
    },
    //单选控制 日志类型 main init wait
    workflowcontainerchange(e) {
      if (this.containertype == "main") {
        this.workflowContentlog = this.workflowContent.main;
        this.workflowContentlogsplit =
          this.workflowContent.main.split(/[(\r\n)\r\n]+/);
      }
      if (this.containertype == "init") {
        this.workflowContentlog = this.workflowContent.init;
        this.workflowContentlogsplit =
          this.workflowContent.init.split(/[(\r\n)\r\n]+/);
      }
      if (this.containertype == "wait") {
        this.workflowContentlog = this.workflowContent.wait;
        this.workflowContentlogsplit =
          this.workflowContent.wait.split(/[(\r\n)\r\n]+/);
      }
    },

    //获取webSocket消息
    handleLog() {
      var websocket = null;

      var host = "ws://127.0.0.1:8082/renren-fast/webSocket/log";
      // if (window.location.protocol == 'http:') {
      //   host = 'ws://' + window.location.host + '/websocket';
      // } else {
      //   host = 'wss://' + window.location.host + '/websocket';
      // }

      //判断当前浏览器是否支持WebSocket
      if ("WebSocket" in window) {
        this.websocket = new WebSocket(host);
      } else if ("MozWebSocket" in window) {
        this.websocket = new MozWebSocket(host);
      } else {
        alert("该浏览器不支持WebSocket！");
      }
      console.log(host);
      this.initWebSocket();

      // if ("WebSocket" in window) {
      //   let url = `ws://localhost/websocket`;
      //   console.log(url);
      //   this.websocket = new WebSocket(url);
      //   this.initWebSocket();
      // }
    },

    //初始化webSocket
    initWebSocket() {
      // 连接错误
      this.websocket.onerror = () => {
        console.log(
          "WebSocket连接发生错误   状态码：" + this.websocket.readyState
        );
      };
      // 连接成功
      this.websocket.onopen = () => {
        console.log(
          "WebSocket连接成功    状态码：" + this.websocket.readyState
        );
      };
      this.websocket.onclose = () => {
        console.log("WebSocket断开    状态码：" + this.websocket.readyState);
      };
      // 收到消息的回调
      this.websocket.onmessage = (event) => {
        // this.consumeCount = this.consumeCount + 1;
        // if (this.filter && event.data.indexOf(this.keyword) == -1) {
        //   return
        // }
        // var curIndex=id;
        if (event.data.match("日志获取结束")) {
          console.log(event.data);
          this.websocket.close();
        } else {
          this.workflowContent = JSON.parse(event.data);
          this.containertype = "main";
          this.workflowContentlog = this.workflowContent.main;
          this.workflowContentlogsplit =
            this.workflowContent.main.split(/[(\r\n)\r\n]+/);
          console.log("event.data" + event.data);
        }

        /* else{
          this.websocket.close();
        } */
      };
    },

    createWebsocket() {
      const url = "ws://127.0.0.1:8082/renren-fast/webSocket/workflowlog";
      this.websocket = new WebSocket(url);
      this.websocket.onopen = () => {
        console.log("websocket.onopen...");
        this.websocket.send(
          JSON.stringify({ workflowName: this.workflowName })
        );
        this.openSocketTimer();
      };
      this.websocket.onmessage = (res) => {
        console.log("websocket.onmessage...");
        const data = res.data;
        console.log(res.data);
        // let lineRes = "";
        // let arrN = [];
        // if (data.indexOf("\n") !== -1) {
        //   arrN = data.split("\n");
        // }

        // if (arrN.length > 0) {
        //   for (let i = 0; i < arrN.length - 1; i++) {
        //     let lineStr = arrN[i];
        //     if (lineStr.indexOf("\r") !== -1) {
        //       lineStr = lineStr[lineStr.length - 1];
        //     }

        //     lineRes += lineStr + "\n\n";
        //   }
        // } else {
        //   lineRes = data;
        // }

        // 放到缓存logCache中
        if (res.data) {
          if (!this.log || this.log.length == 0) {
            this.$nextTick(() => {
              // this.log = `${this.log}${lineRes}`;
              this.log = res.data;
              this.workflowContent = JSON.parse(res.data);
              this.containertype = "main";
              this.workflowContentlog = this.workflowContent.main;
              this.workflowContentlogsplit =
                this.workflowContent.main.split(/[(\r\n)\r\n]+/);
            });
          } else {
            // this.logCache = `${this.logCache}${lineRes}`;
            this.logCache = res.data;
          }
        }
      };
      this.websocket.onclose = function (e) {
        console.log("websocket.onclose...");
        console.log(`连接已断开...>>>${e.code}`);
      };
    },
    // 开启定时器，每隔3秒检验下是否需要刷新日志
    openSocketTimer() {
      this.clearSocketTimer();
      this.socketTimer = setInterval(this.checkRenderEnable, 3000);
    },
    // 关闭定时器
    clearSocketTimer() {
      if (this.socketTimer != null) {
        clearInterval(this.socketTimer);
        this.socketTimer = null;
      }
    },
    // 判断是否需要刷新页面，也就是log缓存是否为空
    checkRenderEnable() {
      if (this.logCache && this.logCache.length > 0) {
        this.renderPage();
      }
    },
    // 刷新页面
    renderPage() {
      this.$nextTick(() => {
        // this.log = `${this.log}${this.logCache}`;
        this.log = this.logCache;
        this.workflowContent = JSON.parse(this.log);
        this.containertype = "main";
        this.workflowContentlog = this.workflowContent.main;
        this.workflowContentlogsplit =
          this.workflowContent.main.split(/[(\r\n)\r\n]+/);
        this.logCache = ""; // 刷新完成之后，清空log缓存
      });
    },
  },
};
</script>
<style>
.el-form-item .el-select {
  width: 100%;
}
.el-form-item .el-input {
  width: 100%;
}
.logList-item {
  padding: 0px 0;
  line-height: 20px;
  margin: 0;
  font: normal 13px/1.2 "Courier", sans-serif;
}
.log-box {
  min-height: 500px;
  max-height: 800px;
  padding: 10px;
  margin: 10px;
  background-color: #fff;
}
</style>
