<template>
  <div style="width: 100%;height: 100%;">
    <div style="height: 25px;color: #fff;display: flex;align-items: center;padding: 0 5px 0 0">
      <img :src="require('@/assets/image/log.png')" height="20px" style="margin: 0 3px 0 0;" />
      <span
        style="color: #13227a;font-size: 1rem;display: flex;align-items: center;justify-content: flex-start">操作日志</span>
      <span style="color: #A8B8CC;font-size: 0.8rem;padding: 0 7px 0 0;margin-left: auto;">Operation Log</span>
      <!-- 滚动按钮 -->
      <el-button type="primary" plain size="mini" icon="el-icon-arrow-up" style="padding: 3px 10px;margin-right: -3px;"
        @click="scrollUp" />
      <el-button type="primary" plain size="mini" icon="el-icon-arrow-down" style="padding: 3px 10px;"
        @click="scrollDown" />
      <!--      <el-tooltip content="导出日志文件">-->
      <!--        <el-button type="warning" plain size="small" icon="el-icon-download" style="padding: 0;font-size: 1rem;margin-left: auto;" @click="universalSave" />-->
      <!--      </el-tooltip>-->
      <!--            <el-button type="primary" size="small" icon="el-icon-s-unfold" style="padding: 0;font-size: 1.2rem;margin-left: 5px;" />-->
    </div>
    <div style="height: calc(100% - 25px);">
      <div style="height: 100%;padding: 0 3px 3px 1px">
        <el-table ref="logTable" :data="infoList" :header-cell-style="{ background: '#f9fbfe', padding: '3px 0' }"
          :show-header="false" style="height: 100%;width: 100%; border-radius: 5px;" stripe size="mini" height="100%"
          tooltip-effect="dark">
          <el-table-column align="center" label="时间" width="60px">
            <template #default="scope">
              {{ scope.row.操作时间 }}
            </template>
          </el-table-column>
          <el-table-column align="left" label="描述">
            <template #default="scope">
              <span v-if="scope.row.消息类型 === 'ERROR'" style="color: #ff0000;">{{ scope.row.内容 }}</span>
              <span v-else-if="scope.row.消息类型 === 'WARNING'" style="color: #ffa500;">{{ scope.row.内容 }}</span>
              <span v-else style="">{{ scope.row.内容 }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>

import { getNowTime3, stationIsWorking } from '@/utils/tool'

export default {
  name: 'index',
  components: {},
  data() {
    return {
      infoList: [],
      timer: null
    }
  },
  created() {
    const scope = this
    scope.getOperationLog()
    this.timer = setInterval(() => {
      scope.getOperationLog()
    }, 5000)
  },
  mounted() {
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  methods: {
    // 查询日志
    getOperationLog() {
      var param = []
      param[0] = ['工位号', this.$store.state.station.stationNumber]
      param[1] = ['查询来源', 1]
      param[2] = ['PageCurrent', 1]
      param[3] = ['PageSize', 100]
      param[4] = ['PageCount', '1111', 'int', '1']
      param[5] = ['ItemCount', '1111', 'int', '1']
      var Data = this.CreateData('11', '日志_工位操作_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result.length !== 0) {
          this.infoList = response.data.result
        }
      })
    },

    // 向上滚动
    scrollUp() {
      this.$nextTick(() => {
        const tableWrapper = this.$refs.logTable.$el.querySelector('.el-table__body-wrapper')
        if (tableWrapper) {
          const scrollDistance = 200 // 每次滚动的距离
          const currentScroll = tableWrapper.scrollTop
          tableWrapper.scrollTop = Math.max(0, currentScroll - scrollDistance)
        }
      })
    },

    // 向下滚动
    scrollDown() {
      this.$nextTick(() => {
        const tableWrapper = this.$refs.logTable.$el.querySelector('.el-table__body-wrapper')
        if (tableWrapper) {
          const scrollDistance = 200 // 每次滚动的距离
          const currentScroll = tableWrapper.scrollTop
          const maxScroll = tableWrapper.scrollHeight - tableWrapper.clientHeight
          tableWrapper.scrollTop = Math.min(maxScroll, currentScroll + scrollDistance)
        }
      })
    },

    async universalSave() {
      const currentTime = getNowTime3()
      const content = this.infoList.map(obj => JSON.stringify(obj)).join('\n')
      const options = {
        suggestedName: currentTime + 'log.txt',
        types: [
          {
            description: '文件',
            accept: {
              'text/plain': ['.txt']
            }
          }
        ],
        excludeAcceptAllOption: true
      }
      // 优先使用现代API
      if ('showSaveFilePicker' in window) {
        return await this.saveFileWithPicker(content, options)
      } else {
        this.saveFile(content, options.fileName)
        return { status: 'success' }
      }
    },

    async saveFileWithPicker(content, options) {
      try {
        const handle = await window.showSaveFilePicker(options) // 打开保存文件对话框
        const writable = await handle.createWritable() // 创建可写入的文件对象
        // 在这里写入文件内容
        await writable.write(content)
        await writable.close()
      } catch (error) {
        console.error('文件保存失败:', error)
      }
    },
    saveFile(content, fileName) {
      // 创建Blob对象
      const blob = new Blob([content], { type: 'text/plain' })

      // 创建下载链接
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = fileName || 'log.txt' // 默认文件名

      // 触发点击下载
      document.body.appendChild(link)
      link.click()

      // 清理
      setTimeout(() => {
        document.body.removeChild(link)
        URL.revokeObjectURL(link.href)
      }, 100)
    },
  }
}
</script>
<style scoped>
::v-deep.el-table .el-table__cell {
  padding: 2px 0;
}

::v-deep.el-table td.el-table__cell div {
  line-height: 20px;
  padding: 0 5px;
}
</style>
