<template>
  <div class="page-shell module-page">
    <BrandTopBar active="delete-brand" />

    <div class="main-content">
      <aside class="left-panel">
        <div class="section-title">选择文件</div>
        <div class="upload-zone">
          <div class="hint">上传删除品牌 Excel；无论是直接上传文件还是上传文件夹批量导入，都会按每个 Excel 文件名匹配紫鸟店铺。</div>
          <div class="btns">
            <button type="button" class="opt-btn" @click="selectFiles">选择 Excel 文件</button>
            <button type="button" class="opt-btn" @click="selectFolder">选择文件夹</button>
          </div>

          <div class="selected-files clean-placeholder split-selected-files">
            <template v-if="selectedPaths.length">
              <span v-for="path in displayPaths" :key="path">{{ path }}</span>
              <span v-if="selectedPaths.length > displayPaths.length" class="more-line">
                还有 {{ selectedPaths.length - displayPaths.length }} 个文件未展开显示
              </span>
            </template>
            <span v-else>暂未选择删除品牌文件</span>
          </div>
        </div>

        <div class="section-title">执行说明</div>
        <div class="option-group">
          <label class="radio-item active">
            <input type="checkbox" checked disabled />
            <div>
              <span class="label">文件名作为店铺名</span>
              <div class="desc">例如 鲍丽明.xlsx 会匹配紫鸟店铺 鲍丽明；选择文件夹时也仍按每个 Excel 文件名匹配</div>
            </div>
          </label>

          <label class="radio-item active">
            <input type="checkbox" checked disabled />
            <div>
              <span class="label">文件夹仅用于批量导入</span>
              <div class="desc">文件夹名和子目录名不会参与店铺匹配，只是方便一次上传多个 Excel</div>
            </div>
          </label>

          <label class="radio-item active">
            <input type="checkbox" checked disabled />
            <div>
              <span class="label">大表仅返回预览</span>
              <div class="desc">当前最多展示前 200 行，避免大文件直接拖慢页面</div>
            </div>
          </label>
        </div>

        <div class="run-row">
          <button type="button" class="btn-run" :disabled="running" @click="submitRun">
            {{ running ? '解析中...' : '开始解析' }}
          </button>
          <span class="loading-msg">
            {{ running ? '正在读取删除品牌数据并匹配紫鸟店铺，请稍候…' : '解析后会在右侧展示预览数据和紫鸟店铺打开链接' }}
          </span>
        </div>
      </aside>

      <section class="right-panel">
        <div class="panel-header">删除品牌结果</div>
        <div class="task-list-wrap">
          <div class="clean-result-summary">
            <div class="summary-card">
              <span class="summary-label">已处理文件</span>
              <strong>{{ summary.total }}</strong>
            </div>
            <div class="summary-card">
              <span class="summary-label">成功结果</span>
              <strong>{{ summary.successCount }}</strong>
            </div>
            <div class="summary-card">
              <span class="summary-label">失败文件</span>
              <strong>{{ summary.failedCount }}</strong>
            </div>
          </div>

          <div class="result-list-wrap">
            <div class="result-list-header">
              <span>删除品牌结果列表</span>
            </div>

            <div v-if="resultItems.length === 0" class="empty-tasks">
              暂无删除品牌结果，完成解析后会在这里展示店铺匹配结果和预览数据
            </div>

            <ul v-else class="task-list clean-result-list">
              <li
                v-for="item in resultItems"
                :key="`${item.resultId || item.sourceFilename}-${item.shopId || ''}`"
                class="task-item split-result-item"
              >
                <div class="left split-result-main">
                  <span class="id" :title="item.sourceFilename">{{ item.sourceFilename || '-' }}</span>
                  <div class="files">店铺名：{{ item.shopName || '-' }}</div>
                  <div class="files">匹配结果：{{ item.matched ? `已匹配 ${item.shopId || ''}` : '未匹配到紫鸟店铺' }}</div>
                  <div v-if="item.platform" class="files">平台：{{ item.platform }}</div>
                  <div v-if="item.totalRows !== undefined" class="time">预览 {{ item.previewRows?.length || 0 }} / {{ item.totalRows }} 行</div>
                  <div v-if="item.truncated" class="files">数据较大，当前仅展示前 200 行</div>
                  <div v-if="item.previewRows?.length" class="files split-entry-list delete-brand-preview">
                    {{ formatPreview(item.previewRows) }}
                  </div>
                  <div v-if="item.error" class="files">错误信息：{{ item.error }}</div>
                </div>

                <div class="task-right split-result-actions">
                  <span class="status" :class="item.success ? 'success' : 'failed'">
                    {{ item.success ? '已完成' : '失败' }}
                  </span>
                  <button
                    v-if="item.openStoreUrl"
                    type="button"
                    class="download"
                    @click="openShop(item.openStoreUrl)"
                  >
                    打开店铺
                  </button>
                  <button
                    v-if="item.resultId"
                    type="button"
                    class="btn-delete"
                    @click="deleteHistoryRecord(item.resultId)"
                  >
                    删除
                  </button>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import BrandTopBar from './BrandTopBar.vue'
import { expandBrandFolderRecursive, type BrandExpandFolderItem } from '@/shared/api/brand'
import {
  deleteDeleteBrandHistory,
  getDeleteBrandHistory,
  runDeleteBrand,
  type DeleteBrandPreviewRow,
  type DeleteBrandResultItem,
  type DeleteBrandRunVo,
} from '@/shared/api/java-modules'
import { getPywebviewApi, type UploadedJavaFile } from '@/shared/bridges/pywebview'

const selectedPaths = ref<string[]>([])
const uploadedFiles = ref<UploadedJavaFile[]>([])
const running = ref(false)
const resultItems = ref<DeleteBrandResultItem[]>([])
const summary = ref<DeleteBrandRunVo>({ total: 0, successCount: 0, failedCount: 0, items: [] })
const displayPaths = computed(() => selectedPaths.value.slice(0, 8))

function updateSummary(items: DeleteBrandResultItem[]) {
  summary.value = {
    total: items.length,
    successCount: items.filter((item) => item.success).length,
    failedCount: items.filter((item) => !item.success).length,
    items,
  }
}

async function uploadPathsToJava(paths: Array<string | BrandExpandFolderItem>) {
  const api = getPywebviewApi()
  if (!api?.upload_file_to_java) {
    throw new Error('当前桌面端未提供文件上传桥接能力')
  }
  const uploaded: UploadedJavaFile[] = []
  for (const item of paths) {
    const filePath = typeof item === 'string' ? item : item.absolutePath
    const relativePath = typeof item === 'string' ? undefined : item.relativePath
    const result = await api.upload_file_to_java(filePath, relativePath)
    if (!result?.success || !result.data) {
      throw new Error(result?.error || result?.message || `上传失败：${filePath}`)
    }
    uploaded.push(result.data)
  }
  return uploaded
}

async function selectFiles() {
  const api = getPywebviewApi()
  if (!api?.select_brand_xlsx_files) {
    ElMessage.warning('当前环境不支持文件选择，请在本机客户端中打开')
    return
  }
  try {
    const paths = await api.select_brand_xlsx_files()
    if (!paths?.length) return
    selectedPaths.value = paths
    uploadedFiles.value = await uploadPathsToJava(paths)
    ElMessage.success(`已选择 ${paths.length} 个删除品牌文件`)
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '选择失败')
  }
}

async function selectFolder() {
  const api = getPywebviewApi()
  if (!api?.select_brand_folder) {
    ElMessage.warning('当前环境不支持文件夹选择，请在本机客户端中打开')
    return
  }

  try {
    const folder = await api.select_brand_folder()
    if (!folder) return
    const result = await expandBrandFolderRecursive(folder)
    if (!result.success || !result.items?.length) {
      ElMessage.warning(result.error || '该文件夹下没有 xlsx 文件')
      return
    }
    selectedPaths.value = result.items.map((item) => item.relativePath || item.absolutePath)
    uploadedFiles.value = await uploadPathsToJava(result.items)
    ElMessage.success(`已选择文件夹内 ${result.items.length} 个 xlsx 文件`)
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '选择失败')
  }
}

async function submitRun() {
  if (!uploadedFiles.value.length) {
    ElMessage.warning('请先选择待处理文件')
    return
  }
  try {
    running.value = true
    const result = await runDeleteBrand({
      files: uploadedFiles.value.map((item) => ({
        fileKey: item.fileKey,
        originalFilename: item.originalFilename,
        relativePath: item.relativePath,
      })),
    })
    summary.value = result
    resultItems.value = result.items || []
    await loadHistory()
    ElMessage.success('删除品牌解析完成')
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '执行失败')
  } finally {
    running.value = false
  }
}

async function loadHistory() {
  try {
    const response = await getDeleteBrandHistory()
    resultItems.value = response.items || []
    updateSummary(resultItems.value)
  } catch {
    // ignore history load errors
  }
}

async function deleteHistoryRecord(resultId: number) {
  try {
    await deleteDeleteBrandHistory(resultId)
    await loadHistory()
    ElMessage.success('已删除')
  } catch (error) {
    ElMessage.error(error instanceof Error ? error.message : '删除失败')
  }
}

function formatPreview(rows: DeleteBrandPreviewRow[]) {
  const preview = rows.slice(0, 5).map((item) => `${item.country}:${item.asin}${item.status ? `（${item.status}）` : ''}`)
  const hiddenCount = rows.length - preview.length
  return hiddenCount > 0 ? `${preview.join('、')} 等 ${rows.length} 条` : preview.join('、')
}

function openShop(url: string) {
  window.open(url, '_blank')
}

onMounted(() => {
  loadHistory().catch(() => undefined)
})
</script>

<style scoped>
.module-page { min-height: 100vh; background: #1a1a1a; }
.main-content { display: flex; min-height: calc(100vh - 56px); height: calc(100vh - 56px); }
.left-panel { width: 380px; background: #1e1e1e; padding: 20px; overflow-y: auto; border-right: 1px solid #2a2a2a; }
.right-panel { flex: 1; display: flex; flex-direction: column; min-width: 0; background: #1a1a1a; }
.section-title { font-size: 13px; color: #bbb; margin-bottom: 10px; }
.upload-zone { border: 1px dashed #3a3a3a; border-radius: 10px; padding: 24px; text-align: center; background: #252525; margin-bottom: 20px; transition: all 0.2s ease; }
.upload-zone:hover { border-color: #3498db; background: #2a2a2a; }
.hint { color: #888; font-size: 13px; margin-bottom: 12px; line-height: 1.5; }
.btns { display: flex; gap: 10px; justify-content: center; flex-wrap: wrap; }
.opt-btn, .btn-run, .download, .btn-delete { border: none; cursor: pointer; transition: all 0.2s ease; }
.opt-btn { padding: 8px 16px; font-size: 13px; color: #ccc; background: #2a2a2a; border: 1px solid #3a3a3a; border-radius: 6px; }
.opt-btn:hover { color: #3498db; background: #333; border-color: #3498db; }
.selected-files { margin-top: 14px; font-size: 12px; color: #888; max-height: 112px; overflow-y: auto; text-align: left; }
.selected-files span { display: block; margin: 4px 0; word-break: break-all; }
.more-line { color: #b8c1cc; }
.split-selected-files { max-height: 120px; min-height: 72px; padding-right: 4px; }
.option-group { margin-bottom: 20px; }
.radio-item { display: flex; align-items: flex-start; gap: 10px; cursor: pointer; padding: 10px 12px; border-radius: 8px; background: #252525; border: 1px solid #2a2a2a; margin-bottom: 8px; transition: all 0.2s ease; }
.radio-item:hover, .radio-item.active { background: #2a2a2a; border-color: #3a3a3a; }
.radio-item input { margin-top: 3px; }
.label { font-weight: 500; color: #e0e0e0; font-size: 13px; }
.desc { font-size: 12px; color: #888; margin-top: 2px; line-height: 1.5; font-weight: 400; }
.run-row { display: flex; align-items: center; flex-wrap: wrap; gap: 10px 12px; margin-top: 16px; }
.btn-run { padding: 10px 22px; background: #3498db; color: #fff; border-radius: 8px; font-size: 14px; }
.btn-run:hover { background: #2980b9; }
.btn-run:disabled { background: #555; color: #999; cursor: not-allowed; }
.loading-msg { color: #3498db; font-size: 13px; }
.panel-header { padding: 16px 20px; border-bottom: 1px solid #2a2a2a; font-size: 15px; font-weight: 600; color: #ddd; }
.task-list-wrap { flex: 1; overflow-y: auto; padding: 16px; }
.task-list { list-style: none; margin: 0; padding: 0; }
.task-item { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: 14px 16px; border: 1px solid #2a2a2a; border-radius: 8px; margin-bottom: 10px; background: #1e1e1e; }
.split-result-item { align-items: flex-start; }
.left { flex: 1; min-width: 0; }
.split-result-main { display: flex; flex-direction: column; gap: 4px; }
.id { display: inline-block; font-weight: 600; color: #e0e0e0; font-size: 13px; }
.files { font-size: 12px; color: #888; margin-top: 4px; }
.time { font-size: 12px; color: #666; margin-top: 2px; }
.split-entry-list { line-height: 1.6; word-break: break-all; max-width: 100%; }
.delete-brand-preview { white-space: normal; }
.task-right { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; justify-content: flex-end; }
.split-result-actions { flex-shrink: 0; min-width: 180px; justify-content: flex-end; align-self: center; }
.status { padding: 4px 10px; border-radius: 6px; font-size: 12px; white-space: nowrap; }
.status.success { background: rgba(46, 204, 113, 0.18); color: #2ecc71; }
.status.failed { background: rgba(231, 76, 60, 0.18); color: #ff6b6b; }
.download { padding: 6px 10px; border-radius: 6px; font-size: 12px; background: rgba(52, 152, 219, 0.18); color: #69b6ff; }
.download:hover { background: rgba(52, 152, 219, 0.28); }
.btn-delete { padding: 6px 10px; border-radius: 6px; font-size: 12px; background: rgba(231, 76, 60, 0.12); color: #ff8f8f; }
.btn-delete:hover { background: rgba(231, 76, 60, 0.22); }
.empty-tasks { color: #666; font-size: 13px; padding: 24px 8px; }
.clean-placeholder { max-height: 112px; }
.clean-result-summary { display: grid; grid-template-columns: repeat(3, minmax(0, 220px)); gap: 16px; margin-bottom: 18px; }
.summary-card { padding: 16px 18px; border: 1px solid #2a2a2a; border-radius: 10px; background: #1e1e1e; }
.summary-card strong { display: block; margin-top: 8px; font-size: 24px; color: #eaf4ff; }
.summary-label { font-size: 12px; color: #8d8d8d; }
.result-list-wrap { border: 1px solid #2a2a2a; border-radius: 10px; background: #1e1e1e; min-height: 260px; }
.result-list-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid #2a2a2a; font-size: 14px; color: #ddd; }
@media (max-width: 1100px) { .main-content { flex-direction: column; height: auto; } .left-panel { width: 100%; border-right: none; border-bottom: 1px solid #2a2a2a; } .right-panel { min-height: 420px; } .task-item { flex-direction: column; align-items: flex-start; } .task-right { width: 100%; justify-content: flex-start; } .split-result-actions { min-width: 0; align-self: flex-start; } .clean-result-summary { grid-template-columns: 1fr; } }
</style>
