<template>
  <div class="upload-records-page">
    <intelligence-left-tab-bar />

    <div class="records-main">
      <header class="page-header">
        <div class="page-header-inner">
          <img class="workspace-toolbar-icon" src="@/assets/icons/tool-item-icon2.png" alt="" />
          <span class="workspace-toolbar-heading">智能翻译</span>
        </div>
      </header>

      <div class="records-toolbar">
        <div class="records-toolbar-left">
          <button type="button" class="back-btn" aria-label="返回" @click="onBack">
            <img class="back-icon" :src="backIconUrl" alt="" />
          </button>
          <span class="records-toolbar-title">文档上传记录</span>
        </div>
        <div class="records-toolbar-right">
          <el-input
            v-model="searchKeyword"
            class="records-search-input"
            clearable
            placeholder="搜索文档"
          />
          <label class="records-upload-btn" for="records-upload-input">
            <span class="records-upload-btn-inner">
              <span class="records-upload-btn-main">
                <span class="records-upload-icon" v-html="lineUploadIconSvg" />
                <span class="records-upload-text">上传文档</span>
              </span>
            </span>
          </label>
          <input
            id="records-upload-input"
            ref="fileInputRef"
            class="records-upload-input"
            type="file"
            multiple
            accept=".pdf,application/pdf"
            @change="onFileChange"
          />
        </div>
      </div>

      <div class="records-table-section">
        <el-table :data="paginatedRows" class="records-table" style="width: 100%">
          <el-table-column prop="name" label="文档名称" min-width="220" show-overflow-tooltip />
          <el-table-column prop="uploadTime" label="上传时间" width="180" />
          <el-table-column label="文档大小" width="120">
            <template #default="{ row }">
              {{ formatFileSize(row.sizeBytes) }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="140">
            <template #default="{ row }">
              <span v-if="isCompletedStatus(row.status)" class="status-cell">
                <img class="status-cell-icon" :src="statusCompleteIconUrl" alt="" />
                <span class="status-cell-text">{{ row.status }}</span>
              </span>
              <span v-else class="status-cell status-cell--plain">{{ row.status }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <button type="button" class="cell-action cell-action--delete" @click="onDelete(row)">删除</button>
              <button type="button" class="cell-action" @click="onExport(row)">导出</button>
              <button type="button" class="cell-action" @click="onEdit(row)">编辑</button>
            </template>
          </el-table-column>
        </el-table>

        <div class="records-pagination-row">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :total="filteredRows.length"
            layout="prev, pager, next"
            background
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import IntelligenceLeftTabBar from '@/components/intelligenceLeftTabBar/index.vue'
import { uploadRecordListMock } from './mock'
import backIconUrl from './icons/back-layer.png'
import lineUploadIconSvg from './icons/Line_Upload.svg?raw'
import statusCompleteIconUrl from './icons/status-complete.png'

function isCompletedStatus(status) {
  return status === '已完成'
}

const router = useRouter()

const fileInputRef = ref(null)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)

const records = ref(
  uploadRecordListMock.map((item) => ({
    ...item
  }))
)

const filteredRows = computed(() => {
  const q = searchKeyword.value.trim().toLowerCase()
  if (!q) {
    return records.value
  }
  return records.value.filter((row) => row.name.toLowerCase().includes(q))
})

const paginatedRows = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  return filteredRows.value.slice(start, start + pageSize.value)
})

watch(searchKeyword, () => {
  currentPage.value = 1
})

watch(filteredRows, (rows) => {
  const maxPage = Math.max(1, Math.ceil(rows.length / pageSize.value) || 1)
  if (currentPage.value > maxPage) {
    currentPage.value = maxPage
  }
})

function formatFileSize(bytes) {
  if (bytes == null || bytes === 0) {
    return '0 B'
  }
  const units = ['B', 'KB', 'MB', 'GB']
  let n = bytes
  let i = 0
  while (n >= 1024 && i < units.length - 1) {
    n /= 1024
    i += 1
  }
  return `${n < 10 && i > 0 ? n.toFixed(1) : Math.round(n)} ${units[i]}`
}

const onBack = () => {
  router.push({ name: 'intelligentTranslation' })
}

const onFileChange = (event) => {
  const { files } = event.target
  if (!files?.length) {
    return
  }
  const pdfOnly = Array.from(files).filter(
    (f) => /\.pdf$/i.test(f.name) || f.type === 'application/pdf'
  )
  const now = new Date()
  const pad = (x) => String(x).padStart(2, '0')
  const uploadTime = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())} ${pad(
    now.getHours()
  )}:${pad(now.getMinutes())}`
  pdfOnly.forEach((f) => {
    records.value.unshift({
      id: `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
      name: f.name,
      uploadTime,
      sizeBytes: f.size,
      status: '翻译中'
    })
  })
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
  ElMessage.success(pdfOnly.length ? `已添加 ${pdfOnly.length} 个文档` : '仅支持 PDF 格式')
}

const onDelete = (row) => {
  const idx = records.value.findIndex((r) => r.id === row.id)
  if (idx !== -1) {
    records.value.splice(idx, 1)
    ElMessage.success('已删除')
  }
}

const onExport = (row) => {
  ElMessage.info(`导出：${row.name}（占位）`)
}

const onEdit = (row) => {
  router.push({
    name: 'intelligentTranslationDocument',
    query: { fileName: row.name }
  })
}
</script>

<style scoped lang="scss">
.upload-records-page {
  display: flex;
  width: 100%;
  min-height: calc(100vh - 65px);
  box-sizing: border-box;
  background-color: var(--bg-white-100);
}

.upload-records-page :deep(.intelligence-left-tab-bar) {
  background-color: var(--bg-white-100);
  align-self: stretch;
}

.records-main {
  box-sizing: border-box;
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: var(--bg-white-100);
}

.page-header {
  box-sizing: border-box;
  flex-shrink: 0;
  width: calc(100% + 32px);
  height: 64px;
  margin: -16px -16px 0;
  padding: 0 24px;
  display: flex;
  align-items: center;
  background: var(--bg-white-100);
  box-shadow: 0 0 20px 0 rgba(25, 69, 130, 0.1);
}

.page-header-inner {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.workspace-toolbar-icon {
  width: 24px;
  height: 24px;
  flex-shrink: 0;
  display: block;
}

.workspace-toolbar-heading {
  font-family: 'YouSheBiaoTiHei', sans-serif;
  font-size: 30px;
  font-weight: 400;
  line-height: 32px;
  letter-spacing: 0;
  color: var(--text-primary-80-color);
}

.records-toolbar {
  box-sizing: border-box;
  flex-shrink: 0;
  margin-top: 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  flex-wrap: wrap;
}

.records-toolbar-left {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.back-btn {
  box-sizing: border-box;
  width: 32px;
  height: 32px;
  padding: 0;
  border: none;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.back-btn:hover {
  background: rgba(25, 69, 130, 0.06);
}

.back-btn .back-icon {
  width: 16px;
  height: 16px;
  display: block;
  object-fit: contain;
}

.records-toolbar-title {
  font-family: 'Source Han Sans CN', sans-serif;
  font-size: 18px;
  font-weight: 600;
  line-height: 26px;
  color: var(--text-primary-80-color, #344054);
}

.records-toolbar-right {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.records-search-input {
  width: 240px;
}

/* 覆盖 App.vue 全局 el-input box-shadow: none !important */
:deep(.records-search-input.el-input .el-input__wrapper) {
  min-height: 32px;
  height: auto;
  background-color: var(--bg-white-100) !important;
  box-shadow: 0 0 0 1px var(--bg-black-10) inset !important;
}

:deep(.records-search-input.el-input .el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px var(--bg-black-10) inset !important;
}

:deep(.records-search-input.el-input .el-input__wrapper:active) {
  box-shadow: 0 0 0 1px var(--bg-black-10) inset !important;
}

:deep(.records-search-input.el-input .el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--color-primary-100)) inset !important;
}

:deep(.records-search-input.el-input .el-input__wrapper.is-focus:hover) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--color-primary-100)) inset !important;
}

:deep(.records-search-input.el-input .el-input__wrapper.is-focus:active) {
  box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--color-primary-100)) inset !important;
}

.records-upload-btn {
  box-sizing: border-box;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 114px;
  height: 32px;
  padding: 0;
  border-radius: 4px;
  border: none;
  background: var(--color-primary-100);
  color: #fff;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  text-align: center;
  cursor: pointer;
}

.records-upload-btn-inner {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.records-upload-btn-main {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.records-upload-text {
  flex-shrink: 0;
  white-space: nowrap;
}

.records-upload-icon {
  flex-shrink: 0;
  display: inline-flex;
  line-height: 0;
  color: inherit;
}

.records-upload-icon :deep(svg) {
  width: 16px;
  height: 16px;
  display: block;
}

.records-upload-input {
  display: none;
}

.records-table-section {
  margin-top: 18px;
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background-color: var(--bg-white-100);
}

.records-table {
  flex: 1;
  min-height: 200px;
}

.cell-action {
  margin-right: 8px;
  padding: 0;
  border: none;
  background: none;
  color: #2563eb;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  cursor: pointer;
}

.cell-action:hover {
  text-decoration: underline;
}

.cell-action--delete {
  color: var(--color-red-100);
}

.cell-action--delete:hover {
  color: var(--color-red-100);
}

.status-cell {
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.status-cell-icon {
  width: 16px;
  height: 16px;
  object-fit: contain;
  flex-shrink: 0;
  display: block;
}

.status-cell--plain {
  display: inline;
}

.records-pagination-row {
  display: flex;
  justify-content: center;
  width: 100%;
}

:deep(.records-table.el-table) {
  --records-table-line: #e8ecf2;
  --el-table-bg-color: var(--bg-white-100);
  --el-table-tr-bg-color: var(--bg-white-100);
  --el-table-row-hover-bg-color: var(--bg-white-100);
  --el-table-border-color: var(--records-table-line);
  background-color: var(--bg-white-100);
  border: none !important;
}

:deep(.records-table.el-table::before),
:deep(.records-table.el-table::after) {
  display: none;
}

:deep(.records-table .el-table__inner-wrapper) {
  border: none !important;
}

/* 无外围框线、无竖线；保留行间水平分割线 */
:deep(.records-table .el-table__header tr),
:deep(.records-table .el-table__body tr) {
  height: 48px;
}

:deep(.records-table .el-table__cell) {
  border-left: none !important;
  border-right: none !important;
  border-top: none !important;
  border-bottom: 1px solid var(--records-table-line) !important;
  box-sizing: border-box;
  padding: 0 12px;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: left;
  vertical-align: middle;
}

:deep(.records-table .el-table__cell .cell) {
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: left;
}

:deep(.records-table .el-table__body tr:last-child .el-table__cell) {
  border-bottom: none !important;
}

:deep(.records-table .el-table__border-left-patch),
:deep(.records-table .el-table__border-right-patch) {
  display: none;
}

:deep(.records-table .el-table__fixed-right::before),
:deep(.records-table .el-table__fixed::before) {
  box-shadow: none;
}

:deep(.records-table .el-table__header-wrapper .el-table__cell) {
  background-color: var(--bg-black-2) !important;
}

:deep(.records-table .el-table__header th) {
  background-color: var(--bg-black-2) !important;
  color: #344054;
  font-weight: 400;
}

:deep(.records-table .el-table__body tr) {
  background-color: var(--bg-white-100);
}
</style>
