<template>
  <div class="intelligent-translation-page">
    <intelligence-left-tab-bar />

    <div class="translation-main">
      <div class="translation-workspace">
        <div class="workspace-left workspace-panel" :class="{ 'workspace-left--full': !isTextMode }">
          <div class="workspace-toolbar">
            <div class="workspace-toolbar-title">
              <img class="workspace-toolbar-icon" src="@/assets/icons/tool-item-icon2.png" alt="" />
              <span class="workspace-toolbar-heading">智能翻译</span>
            </div>
            <button class="translate-btn" type="button" :disabled="submitLoading" @click="onTranslate">
              {{ submitLoading ? '提交中...' : 'AI翻译' }}
            </button>
          </div>

          <div class="workspace-source-block">
            <div v-if="isTextMode" class="source-input-panel">
              <textarea v-model="sourceText" class="source-textarea" placeholder="请输入您要翻译的内容" />
            </div>

            <div v-else class="upload-file-panel">
              <ul class="upload-file-list">
                <li v-for="(file, index) in selectedFiles" :key="`${file.name}-${file.lastModified}-${file.size}`" class="upload-file-item">
                  <img class="upload-file-type-icon" :src="fileTypeIconUrl" alt="" />
                  <span class="upload-file-name">{{ file.name }}</span>
                  <button type="button" class="upload-file-item-delete" aria-label="删除该文件" @click="removeFileAt(index)">
                    <span class="upload-file-delete-icon" v-html="trashIconSvg" />
                  </button>
                </li>
              </ul>
            </div>

            <div class="upload-action-row">
              <label class="upload-btn" for="translation-upload-input">
                <span class="upload-btn-inner">
                  <span class="upload-btn-main">
                    <span class="upload-btn-icon" v-html="lineUploadIconSvg" />
                    <span class="upload-btn-text">上传文档</span>
                  </span>
                  <span class="upload-format-hint">上传的文件只支持 pdf 格式</span>
                </span>
              </label>
              <input id="translation-upload-input" ref="fileInputRef" class="upload-input" type="file" multiple
                accept=".pdf,application/pdf" @change="onFileChange" />
            </div>
          </div>
        </div>

        <div v-if="isTextMode" class="workspace-right workspace-panel">
          <div class="workspace-result-toolbar">
            <div class="workspace-result-toolbar-title">
              <span class="workspace-result-toolbar-icon" v-html="vector1967Svg" />
              <span class="workspace-result-toolbar-heading">智能体·AI翻译</span>
            </div>
            <div class="workspace-result-toolbar-actions">
              <button type="button" class="workspace-result-tool-btn" aria-label="功能" @click="onResultToolbarAgent">
                <span class="workspace-result-tool-btn-icon" v-html="vector1967Svg" />
              </button>
              <button type="button" class="workspace-result-tool-btn" aria-label="刷新" @click="onResultToolbarRefresh">
                <span class="workspace-result-tool-btn-icon" v-html="refresh2Svg" />
              </button>
            </div>
          </div>
          <div class="workspace-result-body">
            <div class="result-content">{{ translatedText }}</div>
          </div>
        </div>
      </div>

      <div class="upload-record-list">
        <div class="record-header">
          <span class="record-title">文档翻译上传记录</span>
          <button type="button" class="record-view-all" @click="onViewAllUploadRecords">
            查看全部 &gt;
          </button>
        </div>
        <div class="record-cards">
          <div v-for="record in uploadRecords" :key="`${record.name}-${record.time}`" class="record-card">
            <img class="record-card-icon" :src="fileTypeIconUrl" alt="" />
            <span class="record-card-name">{{ record.name }}</span>
            <span class="record-card-time">{{ formatRecordDateOnly(record.time) }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import IntelligenceLeftTabBar from '@/components/intelligenceLeftTabBar/index.vue'
import { submitTranslationTask } from '@/api/intelligentTranslation/index'
import { uploadRecordMock } from './mock'
import fileTypeIconUrl from './icons/file-type-icon.png'
import lineUploadIconSvg from './icons/Line_Upload.svg?raw'
import refresh2Svg from './icons/refresh-2.svg?raw'
import trashIconSvg from './icons/trash.svg?raw'
import vector1967Svg from './icons/vector-1967.svg?raw'

const router = useRouter()

const fileInputRef = ref(null)
const sourceText = ref('')
const translatedText = ref('点击“翻译”后展示占位结果')
const selectedFiles = ref([])
const uploadRecords = ref(uploadRecordMock)
const submitLoading = ref(false)

const isTextMode = computed(() => selectedFiles.value.length === 0)

const onTranslate = async () => {
  if (isTextMode.value) {
    ElMessage.warning('请先上传 PDF 文件后再发起翻译')
    return
  }

  const targetFile = selectedFiles.value[0]
  if (!targetFile) {
    ElMessage.warning('请先上传 PDF 文件')
    return
  }
  if (submitLoading.value) {
    return
  }

  submitLoading.value = true
  try {
    const response = await submitTranslationTask(targetFile)
    const taskId = response?.data?.task_id || response?.data?.task_ids?.[0]
    if (!taskId) {
      throw new Error('未获取到任务ID')
    }

    router.push({
      name: 'intelligentTranslationDocument',
      query: {
        taskId,
        fileName: targetFile.name || ''
      }
    })
  } catch (error) {
    ElMessage.error(error?.message || '翻译任务提交失败，请稍后重试')
  } finally {
    submitLoading.value = false
  }
}

const onFileChange = (event) => {
  const { files } = event.target
  if (!files?.length) {
    selectedFiles.value = []
    return
  }
  const pdfOnly = Array.from(files).filter(
    (f) => /\.pdf$/i.test(f.name) || f.type === 'application/pdf'
  )
  selectedFiles.value = pdfOnly
  if (fileInputRef.value) {
    const dt = new DataTransfer()
    pdfOnly.forEach((f) => dt.items.add(f))
    fileInputRef.value.files = dt.files
    if (pdfOnly.length === 0) {
      fileInputRef.value.value = ''
    }
  }
}

const removeFileAt = (index) => {
  const next = selectedFiles.value.filter((_, i) => i !== index)
  selectedFiles.value = next
  if (fileInputRef.value) {
    const dt = new DataTransfer()
    next.forEach((f) => dt.items.add(f))
    fileInputRef.value.files = dt.files
    if (next.length === 0) {
      fileInputRef.value.value = ''
    }
  }
}

const onResultToolbarAgent = () => { }

const onResultToolbarRefresh = () => { }

const onViewAllUploadRecords = () => {
  router.push({ name: 'intelligentTranslationUploadRecords' })
}

/** 上传记录日期仅展示到年月日 */
function formatRecordDateOnly(timeStr) {
  if (timeStr == null || timeStr === '') {
    return ''
  }
  const s = String(timeStr).trim()
  const head = s.match(/^(\d{4}-\d{2}-\d{2})/)
  if (head) {
    return head[1]
  }
  const t = Date.parse(s)
  if (!Number.isNaN(t)) {
    const d = new Date(t)
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
  }
  return s
}
</script>

<style scoped lang="scss">
.intelligent-translation-page {
  display: flex;
  min-height: calc(100vh - 65px);
  background: #fff;
}

.translation-main {
  flex: 1;
  padding: 16px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background-color: var(--color-primary-2);
}

.translation-workspace {
  min-height: 560px;
  display: flex;
  gap: 16px;
}

.workspace-panel {
  border: none;
  border-radius: 10px;
  box-shadow: 0 0 20px 0 rgba(25, 69, 130, 0.1);
}

.workspace-left {
  width: 50%;
  min-width: 420px;
  flex: 0 0 auto;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.workspace-left--full {
  width: 100%;
  min-width: 0;
  flex: 1 1 auto;
  max-width: 100%;
}

.workspace-toolbar {
  box-sizing: border-box;
  height: 68px;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 0 0 #e8ecf2;
}

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

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

/* 业务系统 / 1级标题-综艺：YouSheBiaoTiHei，黑色主色 80% */
.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);
}

.translate-btn {
  box-sizing: border-box;
  width: 120px;
  height: 36px;
  padding: 0;
  border: none;
  border-radius: 50px;
  background: linear-gradient(90deg,
      rgba(0, 91, 244, 1) 0%,
      rgba(101, 0, 253, 1) 100%);
  color: #fff;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: center;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.translate-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.workspace-source-block {
  box-sizing: border-box;
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 16px 24px 23px 24px;
}

.source-input-panel {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
}

.upload-file-panel {
  box-sizing: border-box;
  width: 100%;
  flex: 0 1 auto;
  min-height: 0;
  max-height: 100%;
  overflow: auto;
  padding: 0;
}

.upload-file-item-delete {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-left: auto;
  padding: 4px;
  border: none;
  background: transparent;
  cursor: pointer;
  color: var(--color-red-100);
  line-height: 0;
}

.upload-file-delete-icon {
  display: inline-flex;
  width: 16px;
  height: 16px;
}

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

.source-textarea {
  box-sizing: border-box;
  width: 100%;
  flex: 1;
  min-height: 200px;
  border: none;
  border-radius: 6px;
  resize: vertical;
  padding: 10px;
  outline: none;
  background: transparent;
}

.upload-file-list {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.upload-file-item {
  box-sizing: border-box;
  height: 48px;
  padding: 12px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 8px;
  text-align: left;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 700;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  color: #475467;
  background: var(--bg-black-2);
  border: 1px solid var(--bg-black-5);
  border-radius: 6px;
}

.upload-file-type-icon {
  flex-shrink: 0;
  width: 24px;
  height: 24px;
  object-fit: contain;
  display: block;
}

.upload-file-name {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-action-row {
  flex-shrink: 0;
  width: 100%;
  margin-top: auto;
}

.upload-btn {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100px;
  margin: 0;
  border-radius: 6px;
  border: 1px dashed var(--color-primary-35);
  background: var(--color-primary-2);
  color: #344054;
  cursor: pointer;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: center;
}

.upload-btn-inner {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  min-width: 0;
  padding: 0 12px;
}

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

.upload-btn-icon {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: inherit;
  line-height: 0;
}

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

.upload-btn-text {
  flex-shrink: 0;
  text-align: center;
}

.upload-format-hint {
  align-self: stretch;
  box-sizing: border-box;
  width: 100%;
  margin: 0;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 14px;
  line-height: 22px;
  letter-spacing: 0;
  text-align: left;
  color: var(--text-primary-50-color);
}

.upload-input {
  display: none;
}

.workspace-right {
  background: var(--bg-white-100);
  flex: 1;
  min-width: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.workspace-result-toolbar {
  box-sizing: border-box;
  height: 68px;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 0 0 #e8ecf2;
  flex-shrink: 0;
}

.workspace-result-toolbar-title {
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 0;
}

.workspace-result-toolbar-icon {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--text-primary-80-color, #344054);
  line-height: 0;
}

.workspace-result-toolbar-icon :deep(svg) {
  display: block;
  width: 24px;
  height: 24px;
}

.workspace-result-toolbar-heading {
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: left;
  color: var(--text-primary-80-color);
}

.workspace-result-toolbar-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.workspace-result-tool-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  padding: 4px;
  border: none;
  border-radius: 6px;
  background: transparent;
  cursor: pointer;
  color: #5f656c;
  line-height: 0;
}

.workspace-result-tool-btn:hover {
  background: var(--bg-black-2, #f2f4f7);
}

.workspace-result-tool-btn-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.workspace-result-tool-btn-icon :deep(svg) {
  display: block;
  width: 24px;
  height: 24px;
}

.workspace-result-body {
  box-sizing: border-box;
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 16px 24px 23px 24px;
}

.result-content {
  flex: 1;
  min-height: 0;
  color: #475467;
  white-space: pre-wrap;
}

.upload-record-list {
  box-sizing: border-box;
  background: transparent;
}

.record-header {
  padding-inline: 18px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 12px;
}

.record-title {
  flex: 1;
  min-width: 0;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 700;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: left;
  color: var(--text-primary-80-color, #344054);
}

.record-view-all {
  flex-shrink: 0;
  margin: 0;
  padding: 0;
  border: none;
  background: transparent;
  cursor: pointer;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: right;
  color: var(--color-primary-100);
}

.record-view-all:hover {
  opacity: 0.85;
}

.record-cards {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 16px;
  align-items: stretch;
}

.record-card {
  box-sizing: border-box;
  width: 246px;
  height: 288px;
  flex: 0 0 auto;
  padding: 16px;
  border-radius: 10px;
  background: var(--bg-white-100);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 0;
}

.record-card-icon {
  flex-shrink: 0;
  display: block;
  width: 62px;
  height: 68px;
  object-fit: contain;
  margin-bottom: 30px;
}

.record-card-name {
  box-sizing: border-box;
  max-width: 184px;
  width: 100%;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: center;
  word-break: break-word;
  overflow-wrap: anywhere;
  color: var(--text-primary-80-color);
}

.record-card-time {
  margin-top: 12px;
  font-family: 'Source Han Sans CN', sans-serif;
  font-weight: 400;
  font-size: 16px;
  line-height: 24px;
  letter-spacing: 0;
  text-align: center;
  color: var(--text-primary-50-color);
}
</style>
