<template>
  <div class="layout-no-cols right-detail-toolbar" style="margin:0;">
    <el-toolbar>
      <el-checkbox v-model="realTimeLog.scrollLock">滚动锁定</el-checkbox>
      <el-checkbox v-model="realTimeLog.isAuto" @change="autoChangeHandler">自动刷新</el-checkbox>
      <el-button @click.stop="refreshClickHandler" type="text" title="刷新" style="padding-bottom:13px;margin-left: 30px;">
        <i class="fa fa-refresh"></i>刷新</el-button>
      </el-toolbar>

    <div>
      <textarea v-model="realTimeLog.textLog" id="realTimeLogTextArea"></textarea>
    </div>
  </div>
</template>

<style scoped>

textarea {
  height: calc(100vh - 133px);
  width: 100%;
  padding: 8px;
  border-radius: 4px;
}
</style>

<script>
export default {
  data() {
    return {
      realTimeLog: {
        textLog: '',
        lastID: 0,
        isAuto: true,
        scrollLock: false,
        intervalId: null
      }
    }
  },
  methods: {
    async loadLog() {
      const res = await axios.get('/ui/logs/realtimelog', {
        params: {
          lastID: this.realTimeLog.lastID
        }
      })

      this.realTimeLog.lastID = res.data.lastID
      this.realTimeLog.textLog += res.data.log
      let text = document.getElementById('realTimeLogTextArea')
      if (!this.realTimeLog.scrollLock) {
        text.scrollTop = text.scrollHeight
      }
    },
    refreshClickHandler() {
      this.loadLog()
    },
    autoChangeHandler() {
      if (!this.realTimeLog.isAuto && this.realTimeLog.intervalId) {
        clearInterval(this.realTimeLog.intervalId)
        this.realTimeLog.intervalId = null
        return
      }

      this.getRealTimeLog()
    },
    getRealTimeLog() {
      if (this.realTimeLog.isAuto) {
        if (this.realTimeLog.lastID === 0) {
          this.loadLog()
        }
        this.realTimeLog.intervalId = setInterval(() => {
          this.loadLog()
        }, 2000)
      } else {
        this.realTimeLog.intervalId = null
        this.loadLog()
      }
    }
  },
  created() {
    this.getRealTimeLog()
  },
  destroyed() {
    if (this.realTimeLog.intervalId) {
      clearInterval(this.realTimeLog.intervalId)
    }
  }
}
</script>
