<template>
  <v-card>
    <v-data-table
      :headers="headers"
      :items="filteredLogEntries"
      :items-per-page="itemsPerPage"
      item-key="timestamp"
      class="elevation-1"
      dense
      hide-default-footer
    >
      
      
      <template v-slot:[`item.timestamp`]="{ item }">
        {{ new Date(item.timestamp).toLocaleString() }}
      </template>
      
      <template v-slot:[`item.level`]="{ item }">
        <v-chip :color="getLevelColor(item.level)" small>
          {{ item.level }}
        </v-chip>
      </template>
    </v-data-table>
    <v-row class="pa-4" align="center">
      <v-col cols="3">
        <v-select
          v-model="selectedLevel"
          :items="levelFilters"
          label="筛选日志级别"
          clearable
          dense
          hide-details
        ></v-select>
      </v-col>
    </v-row>
    <v-row class="pa-4" justify="end">
      <v-btn 
        @click="PrintLog('info', '测试日志信息')"
        color="primary"
        class="ma-2"
      >
        添加测试日志
      </v-btn>
    </v-row>
    <v-pagination
      v-model="page"
      :length="pageCount"
      class="my-4"
      @update:modelValue="updatePagination"
    ></v-pagination>
  </v-card>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';


const page = ref(1);
const itemsPerPage = ref(10);

const headers = ref([
  { title: '时间', key: 'timestamp', width: '180px' },
  { title: '级别', key: 'level', width: '100px' },
  { title: '消息', key: 'message' },
]);

const selectedLevel = ref(null);
const levelFilters = ['INFO', 'WARNING', 'ERROR'];

const filteredLogEntries = computed(() => {
  if (!selectedLevel.value) return logEntries.value;
  return logEntries.value.filter(entry => entry.level === selectedLevel.value);
});

const logEntries = ref([
  {
    timestamp: 1622548800000,
    level: 'INFO',
    message: '系统初始化完成',
  },
  {
    timestamp: 1622548801000,
    level: 'WARNING',
    message: '检测到未校准参数',
  },
  // 更多模拟日志数据...
]);

const pageCount = computed(() => {
  return Math.ceil(filteredLogEntries.value.length / itemsPerPage.value);
});

function getLevelColor(level) {
  return {
    INFO: 'blue',
    WARNING: 'orange',
    ERROR: 'red',
  }[level] || 'grey';
}

function updatePagination(value) {
  page.value = value;
}

const PrintLog = (level, message) => {
  const newLog = {
    timestamp: Date.now(),
    level: level.toUpperCase(),
    message: message
  };
  logEntries.value.unshift(newLog);
};

defineExpose({
  PrintLog
});
</script>

<style scoped>
.v-card {
  margin: 12px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}
</style>