<template>
  <view class="page-container system-log-container">
    <!-- 页面头部 -->
    <!-- <view class="page-header">
      <view class="header-left">
        <text class="page-title">日志</text>
      </view>
      <view class="header-right">
        <view class="system-title">
          <view class="system-title-icon">
            <text class="icon">📋</text>
          </view>
          <text class="system-title-text">移动式检修车间系统</text>
        </view>
      </view>
    </view> -->
    
    <!-- 日期选择区域 -->
    <view class="date-picker-container">
      <picker 
        mode="date" 
        :value="selectedDate" 
        @change="onDateChange"
        class="date-picker"
      >
        <view class="picker-input">
          <text class="picker-text">{{ selectedDate || '请选择日期' }}</text>
          <text class="picker-icon">▼</text>
        </view>
      </picker>
    </view>
    
    <!-- 日志表格 -->
    <view class="page-content">
      <view class="log-content">
        <view class="log-table">
          <!-- 表格头部 -->
          <view class="table-header">
            <view class="table-cell header-cell event-column">事件</view>
            <view class="table-cell header-cell time-column">时间</view>
            <view class="table-cell header-cell status-column">状态</view>
          </view>
          
          <!-- 表格内容 -->
          <scroll-view 
            class="table-body" 
            scroll-y="true" 
            :scroll-with-animation="true"
            :scroll-top="scrollTop"
            @scrolltolower="onScrollToLower"
            @scroll="onScroll"
          >
            <!-- 加载状态 -->
            <view class="table-loading-container" v-if="isLoading">
              <view class="table-loading-spinner"></view>
              <text class="table-loading-text">正在加载日志数据...</text>
            </view>
            
            <!-- 表格数据 -->
            <template v-else>
              <view 
                v-for="(log, index) in logList" 
                :key="index" 
                class="table-row"
                :class="{ 'even-row': index % 2 === 0 }"
              >
                <view class="table-cell event-column">{{ log.event }}</view>
                <view class="table-cell time-column">{{ log.time }}</view>
                <view class="table-cell status-column" :class="getStatusClass(log.status)">
                  {{ log.status }}
                </view>
              </view>
            </template>
            
            <!-- 空数据提示 -->
            <view class="table-empty-container" v-if="!isLoading && logList.length === 0 && hasInitialized">
              <text class="table-empty-text">暂无日志数据</text>
            </view>
            
            <!-- 初始状态提示 -->
            <view class="table-empty-container" v-if="!isLoading && logList.length === 0 && !hasInitialized">
              <text class="table-empty-text">暂无数据</text>
            </view>
            
            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="isLoadingMore">
              <view class="load-more-spinner"></view>
              <text class="load-more-text">正在加载更多日志...</text>
            </view>
            
            <!-- 没有更多数据提示 -->
            <view class="no-more-container" v-if="!hasMoreData && logList.length > 0 && !isLoadingMore">
              <text class="no-more-text">已加载全部数据</text>
            </view>
            
            <!-- 底部间距，确保最后一条记录完全显示 -->
            <view class="table-bottom-spacing"></view>
          </scroll-view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
import { eventApi } from '@/utils/api.js';

// 接收父组件传递的查询日期
const props = defineProps({
  queryDate: {
    type: String,
    default: ''
  }
});

// 日志数据
const logList = ref([]);
const isLoading = ref(false);
const isConnected = ref(false);
const hasInitialized = ref(false);

// 分页相关
const currentPage = ref(0);
const pageSize = ref(20);
const hasMoreData = ref(true);
const isLoadingMore = ref(false);

// 滚动相关
const scrollTop = ref(0);
const isScrolling = ref(false);

// 日期选择相关
const selectedDate = ref('');
const startTime = ref('');
const endTime = ref('');

// 移除空行占位逻辑，没有数据时只显示"暂无数据"

// 状态映射函数
const mapStatusToDisplay = (status) => {
  const statusMap = {
    '已完成': '正常',
    '进行中': '进行中',
    '失败': '异常',
    '错误': '异常',
    '成功': '正常',
    '正常': '正常',
    '异常': '异常'
  };
  return statusMap[status] || status || '未知';
};

// 时间格式化函数
const formatDateTime = (dateString) => {
  if (!dateString) return '未知时间';
  try {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('时间格式化失败:', error);
    return dateString;
  }
};

// MQTT日志服务接口（预留）
const mqttLogService = {
  // 连接MQTT服务器
  connect: async () => {
    try {
      // 模拟连接延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      isConnected.value = true;
      return Promise.resolve();
    } catch (error) {
      console.error('MQTT日志连接失败:', error);
      isConnected.value = false;
      return Promise.reject(error);
    }
  },
  
  // 订阅日志数据
  subscribeLogData: () => {
    // 这里后期会实现真实的MQTT日志订阅
    return Promise.resolve();
  },
  
  // 获取历史日志（分页）
  getHistoryLogs: async (page = 0, size = 20, isLoadMore = false, queryDate = '') => {
    try {
      if (!isLoadMore) {
        isLoading.value = true;
      } else {
        isLoadingMore.value = true;
      }
      hasInitialized.value = true;
      
      // 如果没有选择日期，使用默认日期（当天）
      let queryStartTime = startTime.value;
      let queryEndTime = endTime.value;
      
      if (!queryStartTime || !queryEndTime) {
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        const todayStr = `${year}-${month}-${day}`;
        
        queryStartTime = `${todayStr} 00:00:00`;
        queryEndTime = `${todayStr} 23:59:59`;
        
        // 更新选择的日期
        if (!selectedDate.value) {
          selectedDate.value = todayStr;
          startTime.value = queryStartTime;
          endTime.value = queryEndTime;
        }
      }
      
      // 构建查询参数
      const params = { 
        page: page, 
        size: size,
        startTime: queryStartTime,
        endTime: queryEndTime
      };
      
      // 调用事件API获取分页数据
      const response = await eventApi.getListByCreateTime(params);
      
      // 将API数据转换为日志格式
      const newLogs = response.data.map(item => ({
        event: item.eventType || '未知事件',
        time: formatDateTime(item.eventTime) || '未知时间',
        status: mapStatusToDisplay(item.status) || '未知'
      }));
      
      if (isLoadMore) {
        // 加载更多时追加数据
        logList.value = [...logList.value, ...newLogs];
      } else {
        // 首次加载时替换数据
        logList.value = newLogs;
      }
      
      // 更新分页状态
      currentPage.value = page;
      hasMoreData.value = newLogs.length === size; // 如果返回的数据少于请求的数量，说明没有更多数据
    } catch (error) {
      if (!isLoadMore) {
        // 首次加载失败时显示空数据
        logList.value = [];
      }
    } finally {
      isLoading.value = false;
      isLoadingMore.value = false;
    }
  },
  
  
  
  // 断开连接
  disconnect: () => {
    isConnected.value = false;
    // 这里后期会实现真实的MQTT断开
  }
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case '正常':
      return 'status-normal';
    case '异常':
      return 'status-error';
    case '警告':
      return 'status-warning';
    default:
      return '';
  }
};

// 滚动事件处理
let scrollTimer = null;

const onScroll = (e) => {
  isScrolling.value = true;
  
  // 防抖处理，避免频繁触发
  if (scrollTimer) {
    clearTimeout(scrollTimer);
  }
  
  scrollTimer = setTimeout(() => {
    isScrolling.value = false;
  }, 150);
  
  // 可以在这里添加滚动时的逻辑
};

const onScrollToLower = () => {
  if (isLoadingMore.value || !hasMoreData.value) {
    console.log('⏸️ 正在加载中或没有更多数据，跳过加载');
    return;
  }
  
  const nextPage = currentPage.value + 1;
  mqttLogService.getHistoryLogs(nextPage, pageSize.value, true, props.queryDate);
};

// 滚动到顶部
const scrollToTop = () => {
  scrollTop.value = scrollTop.value === 0 ? 1 : 0;
};

// 日期选择处理，选择后直接查询
const onDateChange = async (e) => {
  selectedDate.value = e.detail.value;
  // 自动构建开始和结束时间
  if (selectedDate.value) {
    startTime.value = `${selectedDate.value} 00:00:00`;
    endTime.value = `${selectedDate.value} 23:59:59`;
    try {
      // 重置分页状态
      currentPage.value = 0;
      hasMoreData.value = true;
      logList.value = [];
      
      // 使用选择的日期范围查询
      await mqttLogService.getHistoryLogs(0, pageSize.value, false, selectedDate.value);
    } catch (error) {
      console.error('❌ 查询失败:', error);
    }
  }
};



// 组件生命周期
onMounted(async () => {
  try {
    await mqttLogService.getHistoryLogs(0, pageSize.value, false, props.queryDate);
  } catch (error) {
    uni.showToast({
      title: '连接失败',
      icon: 'error'
    });
  }
});

// 刷新数据方法
const refreshData = async () => {
  try {
    // 重置分页状态
    currentPage.value = 0;
    hasMoreData.value = true;
    logList.value = [];
    
    // 重新获取第一页数据
    await mqttLogService.getHistoryLogs(0, pageSize.value, false, props.queryDate);
  } catch (error) {
    console.error('❌ 刷新数据失败:', error);
  }
};

// 按日期查询方法
const queryByDate = async (queryDate) => {
  try {
    // 重置分页状态
    currentPage.value = 0;
    hasMoreData.value = true;
    logList.value = [];
    
    // 按日期获取第一页数据
    await mqttLogService.getHistoryLogs(0, pageSize.value, false, queryDate);
  } catch (error) {
    console.error('❌ 按日期查询失败:', error);
  }
};

// 暴露方法给父组件
defineExpose({
  refreshData,
  queryByDate
});

onUnmounted(() => {
  mqttLogService.disconnect();
  
  // 清理滚动定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer);
    scrollTimer = null;
  }
});
</script>

<style lang="scss">
@import '@/styles/common.scss';

.system-log-container {
  // 继承通用页面容器样式
  display: flex;
  flex-direction: column;
  height: 100%;
}

// 日期选择器容器样式
.date-picker-container {
  display: flex;
  align-items: center;
  // justify-content: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%);
  border-bottom: 2rpx solid #e8eaed;
}

.date-picker {
  width: 100%;
  // max-width: 500rpx;
}

.picker-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 24rpx;
  background: #ffffff;
  border: 2rpx solid #dadce0;
  border-radius: 8rpx;
  transition: all 0.3s ease;
}

.picker-input:active {
  border-color: #1a73e8;
  background: #f1f5ff;
}

.picker-text {
  font-size: 26rpx;
  color: #3c4043;
  flex: 1;
}

.picker-icon {
  font-size: 20rpx;
  color: #5f6368;
  margin-left: 12rpx;
}

.log-content {
  // 继承通用内容样式
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.log-table {
  // 继承通用表格样式
  @extend .common-table;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.table-header {
  display: flex;
  background: #f8f9fa;
  color: #3c4043;
  border-bottom: 1rpx solid #e8eaed;
}

.header-cell {
  font-weight: 500;
  font-size: 26rpx;
  padding: 20rpx 16rpx;
  text-align: center;
  letter-spacing: 0.2rpx;
}

.table-body {
  flex: 1;
  height: 0; /* 重要：配合flex: 1使用，确保正确计算高度 */
  overflow-y: auto;
  overflow-x: hidden;
  /* 滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #dadce0 #f1f3f4;
  /* 平滑滚动 */
  scroll-behavior: smooth;
}

/* Webkit浏览器滚动条样式 */
.table-body::-webkit-scrollbar {
  width: 8rpx;
}

.table-body::-webkit-scrollbar-track {
  background: rgba(241, 243, 244, 0.5);
  border-radius: 4rpx;
  margin: 4rpx 0;
}

.table-body::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #dadce0 0%, #bdc1c6 100%);
  border-radius: 4rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.table-body::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #bdc1c6 0%, #9aa0a6 100%);
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.table-body::-webkit-scrollbar-thumb:active {
  background: linear-gradient(180deg, #9aa0a6 0%, #5f6368 100%);
}

.table-row {
  display: flex;
  border-bottom: 1rpx solid #e8eaed;
  transition: all 0.2s ease;
  min-height: 80rpx;
}

.table-row.even-row {
  background-color: rgba(248, 249, 250, 0.5);
}

.table-row:hover {
  background-color: rgba(241, 243, 244, 0.8);
  transform: translateX(2rpx);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.table-row:last-child {
  border-bottom: none;
}

.table-cell {
  padding: 16rpx 16rpx;
  font-size: 24rpx;
  color: #3c4043;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  min-height: 80rpx;
  line-height: 1.4;
  word-wrap: break-word;
  word-break: break-all;
  transition: color 0.2s ease;
}

.event-column {
  flex: 2;
  justify-content: flex-start;
  text-align: left;
  padding-left: 30rpx;
}

.time-column {
  flex: 2;
}

.status-column {
  flex: 1;
  font-weight: bold;
}

.status-normal {
  color: #34a853;
  font-weight: 600;
  position: relative;
}

.status-normal::before {
  content: '●';
  color: #34a853;
  margin-right: 8rpx;
  font-size: 20rpx;
}

.status-error {
  color: #ea4335;
  font-weight: 600;
  position: relative;
}

.status-error::before {
  content: '●';
  color: #ea4335;
  margin-right: 8rpx;
  font-size: 20rpx;
}

.status-warning {
  color: #fbbc04;
  font-weight: 600;
  position: relative;
}

.status-warning::before {
  content: '●';
  color: #fbbc04;
  margin-right: 8rpx;
  font-size: 20rpx;
}

/* 移除空行样式，不再需要 */

.table-bottom-spacing {
  height: 40rpx;
  background-color: transparent;
}

.table-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60rpx 20rpx;
  gap: 20rpx;
  background-color: #ffffff;
}

.table-loading-spinner {
  width: 48rpx;
  height: 48rpx;
  border: 3rpx solid #e8eaed;
  border-top: 3rpx solid #5f6368;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.table-loading-text {
  font-size: 24rpx;
  color: #5f6368;
  font-weight: 400;
}

.table-empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 80rpx;
  gap: 16rpx;
}

.table-empty-text {
  font-size: 26rpx;
  color: #9aa0a6;
  font-weight: 400;
}


// 响应式设计 - 平板设备适配
@media (min-width: 768px) and (max-width: 1024px) {
  .header-cell {
    font-size: 28rpx;
    padding: 24rpx 20rpx;
  }
  
  .table-cell {
    font-size: 26rpx;
    padding: 20rpx 16rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
  }
  
  .date-picker-container {
    padding: 24rpx 32rpx;
  }
  
  .date-picker {
    max-width: 600rpx;
  }
  
  .picker-text {
    font-size: 28rpx;
  }
}

// 响应式设计 - 手机设备适配
@media (max-width: 750rpx) {
  .header-cell {
    font-size: 22rpx;
    padding: 16rpx 12rpx;
  }
  
  .table-cell {
    font-size: 20rpx;
    padding: 12rpx 8rpx;
  }
  
  .empty-text {
    font-size: 24rpx;
  }
  
  .date-picker-container {
    padding: 16rpx 20rpx;
  }
  
  .date-picker {
    max-width: 100%;
  }
  
  .picker-text {
    font-size: 24rpx;
  }
}

// 响应式设计 - 大屏设备适配
@media (min-width: 1200px) {
  .header-cell {
    font-size: 30rpx;
    padding: 28rpx 24rpx;
  }
  
  .table-cell {
    font-size: 28rpx;
    padding: 24rpx 20rpx;
  }
  
  .empty-text {
    font-size: 30rpx;
  }
}

// 加载更多样式
.load-more-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 20rpx;
  gap: 15rpx;
  background-color: #ffffff;
}

.load-more-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #e8eaed;
  border-top: 3rpx solid #5f6368;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.load-more-text {
  font-size: 24rpx;
  color: #5f6368;
  font-weight: 400;
}

.no-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 30rpx 20rpx;
  background-color: #ffffff;
}

.no-more-text {
  font-size: 24rpx;
  color: #9aa0a6;
  font-weight: 400;
}
</style>