<template>
  <a-card >
    <div class="subtitle" > 消息跟踪可记录设备在运行过程中的各类操作信息，状态和结果。当数据上报、响应命令等业务场景中出现故障时，消息跟踪功能可帮助您快速进行故障定位和原因分析</div>

    <div class="subtitle" >为避免占用读写计算、存储资源，同时保证数据有效，平台限制最长可跟踪3天的数据，且单个用户下，仅支持同时启动10个设备的消息跟踪。</div>

    <AlertTsx style="margin-top: 20px;"  >
      <template #valueSlot>
        <div v-if="state.dataSource.length && state.trackStart" >
          结束时间： {{state.formatStartTime}}
        </div>
        <div v-else-if="state.trackStart" >
          开始追踪：当前暂无消息记录
        </div>
        <div v-else >
          尚未追踪
        </div>

      </template>
      <template #operaSlot>
        <a-space>
          <a-button type="link" @click="clearDataSource">清除数据</a-button>
        </a-space>
      </template>
    </AlertTsx>

    <a-row  style="margin: 20px 0px;" justify="space-between" >
      <a-col>
        <a-space>

        </a-space>
      </a-col>
      <a-col>
        <a-space>
          <a-button type="primary" @click="addEventTrace" >新增事件跟踪</a-button>
        </a-space>
      </a-col>
    </a-row>

    <a-table
      :columns="columns"
      :loading="state.loading"
      :dataSource="state.dataSource"
      :pagination="false"
      style="height: 400px;overflow: hidden;overflow-y: auto;"
    >
      <template #bodyCell="{column, record}">
        <template v-if="column.key === 'eventType'" >
          {{EventController.eventTypeMap.get(record.eventType)?.name}}
        </template>
        <template v-if="column.key === 'eventPayload'" >
          <a-tooltip placement="topLeft" >
            <template #title> {{record.eventPayload}}</template>
            {{record.eventPayload}}
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'eventTs'" >
          {{ dayjs(record.eventTs).format('YYYY-MM-DD hh:mm:ss') }}
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<script lang="ts" setup >
import { AlertTsx } from '@/components/MicroComponents/index'
import { EventController } from '@/controller'
import { onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { useScheduler } from '@/hooks'

const route = useRoute()
const deviceId = route.query.id as string

const columns = [
  {
    title: '业务名称',
    dataIndex: 'eventName',
    width: 100
  },
  {
    title: '业务类型',
    dataIndex: 'eventType',
    key: 'eventType',
    width: 100
  },
  {
    title: '业务详情',
    dataIndex: 'eventPayload',
    key: 'eventPayload',
    width: 100,
    ellipsis: true
  },
  {
    title: '记录时间',
    dataIndex: 'eventTs',
    key: 'eventTs',
    width: 100
  }
]

const eventTypeList = Array.from(EventController.eventTypeMap, ([key, value]) => ({ ...value, value: value.key }))

const state = reactive({
  loading: false,
  dataSource: [],
  total: 0,
  trackStart: false,
  // startTime: new Date().getTime() - 2000,
  startTime: 0,
  lastId: '',
  formatStartTime: ''
})

const clearDataSource = () => {
  state.dataSource = []
}

const addEventTrace = async () => {
  await EventController.addTrace({ deviceId: deviceId })
  state.trackStart = true
  stop()
  getEventTraceList()
}

const getEventList = async () => {
  const { data } = await EventController.list({ deviceId: deviceId, startTime: state.startTime, lastId: state.lastId })
  console.log('getEventList:', data)
  state.dataSource = state.dataSource.concat(data)
  state.total = 0
}

const { start, stop } = useScheduler(getEventList, 2000)

const getEventTraceList = async () => {
  const data = await EventController.listTrace({ deviceId: deviceId }) as unknown as Number
  state.formatStartTime = data ? dayjs(data).format('YYYY-MM-DD hh:mm:ss') : ''
  start()
}

onMounted(() => {
  getEventTraceList()
})

</script>

<style lang="less" scoped >

@import '~@/styles/theme.less';
.subtitle {
  color: @sublabel-color;
  font-size: 14px;
}
</style>
