<template>
  <div>
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form layout="inline" @submit.prevent="handleSearch">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="请求IP">
                <a-input v-model:value="queryParam.requestIp" placeholder="请输入请求IP" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="用户ID">
                <a-input v-model:value="queryParam.uid" placeholder="请输入用户ID" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="API">
                <a-input v-model:value="queryParam.api" placeholder="请输入API路径" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="消息">
                <a-input v-model:value="queryParam.message" placeholder="请输入日志信息" />
              </a-form-item>
            </a-col>
            <a-col :md="24" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <a-table
        :columns="columns"
        :row-key="record => record.Id"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 'max-content' }"
        bordered
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'action'">
            <a-button type="link" @click="goToInfo(record.Id)">详情</a-button>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 日志详情模态框 -->
    <log-detail-modal ref="detailModalRef" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getLogList } from '~/api/log/log.js';
import LogDetailModal from './components/log-detail-modal.vue';

const router = useRouter();
const loading = ref(false);
const dataSource = ref([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total) => `共 ${total} 条`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
  showQuickJumper: true,
});

const queryParam = ref({
  requestIp: '',
  uid: '',
  api: '',
  message: '',
  extraData: ''
});

const columns = [
  { title: 'ID', dataIndex: 'Id', fixed: 'left', width: 80 },
  { title: 'Trace ID', dataIndex: 'TraceId', width: 160 },
  { title: '用户ID', dataIndex: 'Uid', width: 100 },
  { title: '请求IP', dataIndex: 'RequestIp', width: 140 },
  { title: 'API', dataIndex: 'Api', width: 180, ellipsis: true },
  { title: '状态码', dataIndex: 'StatusCode', width: 100 },
  { title: 'User Agent', dataIndex: 'UserAgent', width: 250, ellipsis: true },
  { title: '消息', dataIndex: 'Message', width: 250, ellipsis: true },
  { title: '附加数据', dataIndex: 'ExtraData', width: 200, ellipsis: true },
  { title: '创建时间', dataIndex: 'CreatedAt', width: 180 },
  { title: '更新时间', dataIndex: 'UpdatedAt', width: 180 },
  { title: '操作', dataIndex: 'action', fixed: 'right', width: 100 },
];

const fetchData = () => {
  loading.value = true;
  
  // 构造请求参数，并处理特殊类型
  const params = {
    requestIp: queryParam.value.requestIp || '',
    uid: queryParam.value.uid ? parseInt(queryParam.value.uid) : '',  // 允许为空，不默认为0
    api: queryParam.value.api || '',
    message: queryParam.value.message || '',
    extraData: queryParam.value.extraData || '',
    current: pagination.value.current,
    pageSize: pagination.value.pageSize,
    column: 'id',
    order: 'desc'
  };
  
  console.log('发送查询参数:', params);
  
  getLogList(params).then(response => {

    
    // 根据实际返回格式处理数据
    // 格式: {code: 0, message: "ok", data: {records: [...], page: 1, pageSize: 10, total: 1963, totalPages: 197}}
    if (response && response.code === 0 && response.data) {
      const apiData = response.data;
      if (apiData.records && Array.isArray(apiData.records)) {
        dataSource.value = apiData.records;
        pagination.value.total = apiData.total || 0;
        pagination.value.current = apiData.page || 1;
        pagination.value.pageSize = apiData.pageSize || 10;

      } else {
        dataSource.value = [];
        pagination.value.total = 0;
        console.warn('响应中无数据记录');
      }
    } else {
      // 未识别的格式或错误响应
      dataSource.value = [];
      pagination.value.total = 0;
      console.error('无效的响应格式或响应错误', response);
    }
    loading.value = false;
  }).catch((error) => {
    console.error('请求失败:', error);
    dataSource.value = [];
    loading.value = false;
  });
};

const handleTableChange = (pager) => {
  pagination.value.current = pager.current;
  pagination.value.pageSize = pager.pageSize;
  fetchData();
};

const handleSearch = () => {
  pagination.value.current = 1;
  fetchData();
};

const resetSearch = () => {
  queryParam.value.requestIp = '';
  queryParam.value.uid = '';
  queryParam.value.api = '';
  queryParam.value.message = '';
  queryParam.value.extraData = '';
  handleSearch();
};

const detailModalRef = ref(null);

const goToInfo = (id) => {
  // 打开模态框而不是跳转页面
  detailModalRef.value?.open(id);
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.table-page-search-wrapper .ant-form-inline .ant-form-item {
  margin-bottom: 24px;
}

/* 表格样式优化 */
:deep(.ant-table-body) {
  overflow-x: auto !important;
}

:deep(.ant-table-fixed-header .ant-table-scroll .ant-table-header) {
  margin-bottom: 0 !important;
  padding-bottom: 0 !important;
  overflow: hidden !important;
}

:deep(.ant-table-body::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.ant-table-body::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.ant-table-body::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}
</style>
