<template>
  <m-card :title="`${title} [ ${code} ]`" style="height: 100%;" class="d-flex flex-column">
    <template #title>
      <div class="d-flex align-center flex-shrink-0">
        <v-checkbox
          class="mt-0 mr-3"
          v-model="autoSwitch"
          dense
          hide-details
        >
          <template v-slot:label>
            <tool-tip text="加载新内容时自动滚动至底部">
              <span class="grey--text subtitle-2">加载吸底</span>
            </tool-tip>
          </template>
        </v-checkbox>
        <template v-if="code">
          <v-btn class="half-button" rounded color="primary" :loading="downloading" @click="handleDownload">下载</v-btn>
        </template>
        <v-btn v-if="isUpdate" color="error" class="ml-3 buttons" rounded @click="handleCancelState">解锁运行状态</v-btn>
      </div>
    </template>
    <div class="box px-3 my-3" ref="box">
      <div v-for="item in logItems" :key="item.id" class="d-flex mb-2">
        <div class="box-title">{{ item.createDate }}</div>
        <div class="box-content">{{ item.content }}</div>
      </div>
      <div class="d-flex justify-center py-3" v-if="loading">
        <v-progress-circular
          indeterminate
          color="primary"
        ></v-progress-circular>
      </div>
    </div>
  </m-card>
</template>

<script>
import ToolTip from '@/components/Tooltip'
import { downloadFile } from '@/utils/index.js'
import { currentTime } from '@/utils/date.js'
import MCard from '@/components/MCard'
import { versionLogDetails, versionLogDownloadHasParam, cancelRunState } from '@/api/system'
export default {
  name: 'log-details',
  components: { MCard, ToolTip },
  props: {
    title: {
      type: String,
      default: '日志'
    },
    code: {
      type: String,
      default: ''
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      parentId: 0,
      timer: null,
      logItems: [],
      loading: false,
      downloading: false,
      autoSwitch: true
    }
  },
  watch: {
    code: {
      handler (val) {
        this.parentId = 0
        this.handleClearTimeout()
        this.logItems = []
        if (val) this.loadingLog()
      },
      immediate: true
    }
  },
  methods: {
    async handleCancelState () {
      try {
        await cancelRunState()
        this.$snackbar.success('解锁成功')
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async loadingLog () {
      this.loading = true
      try {
        const { data } = await versionLogDetails({ logCode: this.code, parentId: this.parentId })
        this.logItems.push(...data.records)
        if (this.autoSwitch) {
          this.$nextTick(() => {
            // const element = this.$refs.box.scrollTo
            // 距离底部50像素自动滑动到底部
            // if (element.scrollTop + element.clientHeight - element.scrollHeight > 50) {
            this.$refs.box.scrollTo({
              top: this.$refs.box.scrollHeight,
              behavior: 'smooth'
            })
            // }
          })
        }

        // 判断结束
        if (data.records.length && data.records[data.records.length - 1]?.content === '日志结束') {
          this.handleClearTimeout()
          this.loading = false
          return
        }
        // 1000毫秒加载下一段
        this.timer = setTimeout(() => {
          if (data.records.length) this.parentId = data.records[data.records.length - 1].id
          this.loadingLog()
        }, 1000)
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async handleDownload () {
      this.downloading = true
      const timestamp = new Date().getTime()
      const filename = `更新日志导出_${currentTime(timestamp)}.txt`
      try {
        const { data } = await versionLogDownloadHasParam({ logCode: this.code })
        downloadFile(data, filename)
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.downloading = false
      }
    },
    handleClearTimeout () {
      if (!this.timer) return
      clearTimeout(this.timer)
      this.timer = null
    }
  },
  beforeDestroy () {
    this.handleClearTimeout()
    // console.log('beforeDestroy2', this.timer)
  }
}
</script>

<style lang="scss" scoped>
.box {
  height: 100%;
  overflow: auto;
  &::-webkit-scrollbar {
    width: 20px !important;
    height: 40px !important;
  }
  &-title {
    width: 180px;
  }
  &-content {
    width: 0;
    flex: 1;
  }
}
</style>
