<template>
  <div id="app">
    <header class="app-header">
      <h1>文件管理客户端</h1>
      <div class="network-indicator" :class="isOnline ? 'online' : 'offline'">
        {{ isOnline ? '在线模式' : '离线模式' }}
      </div>
    </header>
    <main class="app-main">
      <FileUpload @file-uploaded="refreshFileList" />
      <FileList
          ref="fileListRef"
          @md5-check="handleMD5Check"
          @ocr-recognize="handleOcrRecognize"
      />
    </main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import FileUpload from '../components/FileUpload.vue'
import FileList from '../components/FileList.vue'
import apiManager from '../utils/apiManager'

interface FileRecord {
  id: number
  originalName: string
  fileName: string
  filePath: string
  fileSize: number
  mimeType: string
  md5: string
  createdAt: string
  updatedAt: string
}

const router = useRouter()
const fileListRef = ref<InstanceType<typeof FileList>>()
const isOnline = ref(false)

// 监听网络状态变化
const handleNetworkChange = (event: CustomEvent<{ baseUrl: string; isOnline: boolean }>) => {
  isOnline.value = event.detail.isOnline
  console.log('App: 网络状态变更', event.detail)
}

onMounted(() => {
  isOnline.value = apiManager.isOnlineMode()
  window.addEventListener('apiBaseUrlChanged', handleNetworkChange as EventListener)
})

onUnmounted(() => {
  window.removeEventListener('apiBaseUrlChanged', handleNetworkChange as EventListener)
})

const refreshFileList = (): void => {
  fileListRef.value?.refreshList()
}

const handleMD5Check = async (file: FileRecord, isChanged: boolean, newMD5: string): Promise<void> => {
  if (isChanged) {
    const confirmed = confirm('文件内容已发生变化，是否更新MD5信息？')
    if (confirmed) {
      try {
        await apiManager.request(`/api/files/${file.id}/update-md5`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ md5: newMD5 })
        })

        alert('MD5信息已更新')
        refreshFileList()
      } catch (error) {
        console.error('更新MD5失败:', error)
        alert('更新失败')
      }
    }
  } else {
    alert('文件未发生变化')
  }
}

const handleOcrRecognize = (file: FileRecord): void => {
  // 跳转到OCR识别页面
  router.push(`/ocr?fileId=${file.id}`).then((res) => {
    console.log('导航成功:', res)
  }).catch((error) => {
    console.error('导航错误:', error)
    // 如果路由跳转失败，尝试使用 hash 方式
    window.location.hash = `/ocr?fileId=${file.id}`
  })
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background: #f5f5f5;
  height: 100vh;
  overflow: hidden;
}

#app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.app-header {
  background: #2c3e50;
  color: white;
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  flex-shrink: 0; /* 防止头部被压缩 */
}

.network-indicator {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: bold;
}

.network-indicator.online {
  background: #27ae60;
}

.network-indicator.offline {
  background: #e74c3c;
}

.app-main {
  flex: 1;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  overflow: hidden; /* 改为 hidden，内部组件自己处理滚动 */
}
</style>