<template>
  <div class="export-list">
    <!-- 导出样式选择 -->
    <div class="export-style-grid">
      <div
        v-for="item in exportStyles"
        :key="item.type"
        class="export-style-item"
        :class="{ 'is-loading': loadingTypes.includes(item.type) }"
        @click="handleSelect(item)"
      >
        <div class="style-icon" :style="{ color: item.color }">
          <SvgIcon :icon-class="item.icon" size="24px" />
        </div>
        <div class="style-name">{{ item.name }}</div>
      </div>
    </div>

    <!-- 导出结果列表 -->
    <div class="export-result-section">
      <div v-if="exportResults.length > 0" class="result-list">
        <div v-for="(result, index) in exportResults" :key="result.id || index" class="result-item">
          <div class="result-icon" :style="{ color: result.color }">
            <SvgIcon :icon-class="result.icon" size="30px" />
          </div>
          <div class="result-info">
            <div class="result-name">{{ result.name }}</div>
            <div class="result-time">{{ formatTime(result.exportTime || result.created_at) }}</div>
          </div>
          <div class="result-actions">
            <el-popover
              placement="bottom-end"
              :width="120"
              :show-arrow="false"
              trigger="click"
              popper-class="action-popover"
            >
              <template #reference>
                <button class="more-btn" @click.stop>
                  <SvgIcon icon-class="more" class="more-icon" size="16px" />
                </button>
              </template>
              <div class="action-menu">
                <div class="action-item" @click="previewResult(result)">
                  <SvgIcon icon-class="YuLan" size="14px" />
                  <span>预览文件</span>
                </div>
                <div class="action-item" @click="downloadResult(result)">
                  <SvgIcon icon-class="XiaZai" size="14px" />
                  <span>下载文件</span>
                </div>
                <div class="action-item" @click="shareResult(result)">
                  <SvgIcon icon-class="FenXiang" size="14px" />
                  <span>分享文件</span>
                </div>
                <div class="action-item" @click="deleteResult(result)">
                  <SvgIcon icon-class="ShanChu" size="14px" />
                  <span>删除文件</span>
                </div>
              </div>
            </el-popover>
          </div>
        </div>
      </div>
      <div v-else class="result-empty">暂无导出记录</div>
    </div>

    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog
      v-model="dialogVisible"
      title="确认删除该导出记录 ?"
      content="删除后，该记录无法恢复 !"
      @confirm="confirmDelete"
    />

    <!-- 预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      :title="previewData?.file_name || '文件预览'"
      width="80%"
      :close-on-click-modal="true"
      class="preview-dialog"
    >
      <div class="preview-content">
        <div v-if="previewLoading" class="preview-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-else-if="previewData?.type === 'markdown'" class="preview-markdown">
          <pre>{{ previewData?.content }}</pre>
        </div>
        <div v-else-if="previewData?.file_url" class="preview-iframe">
          <iframe :src="previewData?.file_url" frameborder="0"></iframe>
          <div class="preview-tip">该文件类型暂不支持直接预览，请下载查看</div>
        </div>
        <div v-else class="preview-empty">无法预览此文件</div>
      </div>
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePreviewDownload">下载</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import SvgIcon from '@/components/SvgIcon/index.vue'
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
import { useAgentsStore } from '@/stores'
import api from '@/api'

const agentsStore = useAgentsStore()

// Props 接收大任务ID（数据库主键）
const props = defineProps<{
  TaskID?: string // 大任务ID，用于导出整个任务的执行结果
}>()

// 事件定义
const emit = defineEmits<{
  (e: 'close'): void
}>()

// 导出样式类型
interface ExportStyle {
  type: string
  name: string
  icon: string
  color: string
}

// 导出结果类型（与后端返回的数据结构匹配）
interface ExportResult {
  id?: number
  record_id?: number
  name: string
  icon: string
  type: string
  color: string
  exportTime?: number
  created_at?: string
  file_url?: string
  file_name?: string
  export_type?: string
}

// 导出样式数据
const exportStyles = ref<ExportStyle[]>([
  { type: 'doc', name: '文本报告', icon: 'DOCX', color: '#00A2D2' },
  { type: 'markdown', name: 'Markdown', icon: 'Markdown', color: '#FF5B5B' },
  { type: 'mindmap', name: '思维导图', icon: 'SiWeiDaoTu', color: '#FF5BEE' },
  { type: 'infographic', name: '信息图', icon: 'XinXiTu', color: '#FCE460' },
  { type: 'excel', name: '数据表格', icon: 'XLSX', color: '#65AE00' },
  { type: 'ppt', name: '演示文稿', icon: 'PPT', color: '#FF7914' }
])

// 导出结果列表
const exportResults = ref<ExportResult[]>([])

// 加载中的导出类型
const loadingTypes = ref<string[]>([])

// 删除对话框相关
const dialogVisible = ref(false)
const resultToDelete = ref<ExportResult | null>(null)

// 预览相关
const previewVisible = ref(false)
const previewLoading = ref(false)
const previewData = ref<{
  content?: string
  file_url?: string
  file_name?: string
  type: string
}>({ type: '' })

// 格式化时间显示
const formatTime = (timestamp: any): string => {
  if (!timestamp) return '未知时间'

  let time: number

  // 如果是 ISO 字符串，转换为时间戳
  if (typeof timestamp === 'string') {
    time = new Date(timestamp).getTime()
  } else if (typeof timestamp === 'number') {
    time = timestamp
  } else {
    return '未知时间'
  }

  const now = Date.now()
  const diff = now - time
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)

  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`

  const date = new Date(time)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(
    date.getDate()
  ).padStart(2, '0')}`
}

// 获取导出记录列表
const fetchExportList = async () => {
  // 使用大任务ID（从 TaskTemplate 传入的 props.TaskID）
  const taskId = props.TaskID
  if (!taskId) {
    console.warn('没有任务ID，无法获取导出列表')
    return
  }

  try {
    const result = await api.getExportList({ task_id: taskId })

    // 转换为前端显示格式
    exportResults.value = result.list.map((item) => {
      const style = exportStyles.value.find((s) => s.type === item.export_type)
      return {
        id: item.id,
        record_id: item.id,
        name: item.file_name,
        icon: style?.icon || 'DOCX',
        type: item.export_type,
        color: style?.color || '#999',
        exportTime: new Date(item.created_at).getTime(),
        created_at: item.created_at,
        file_url: item.file_url,
        file_name: item.file_name,
        export_type: item.export_type,
      }
    })

    console.log('获取导出列表成功:', exportResults.value)
  } catch (error) {
    console.error('获取导出列表失败:', error)
  }
}

// 预览文件
const previewResult = async (result: ExportResult) => {
  const recordId = result.id || result.record_id
  if (!recordId) {
    ElMessage.error('无法获取文件ID')
    return
  }

  // 先初始化数据，再显示对话框，避免渲染时属性不存在
  previewData.value = {
    content: '',
    file_url: '',
    file_name: result.file_name || '文件预览',
    type: result.type || ''
  }
  previewVisible.value = true
  previewLoading.value = true

  try {
    const data = await api.previewExport(recordId)
    previewData.value = {
      ...previewData.value,
      ...data,
    }
    previewLoading.value = false
  } catch (error) {
    console.error('预览失败:', error)
    ElMessage.error('预览失败')
    previewLoading.value = false
  }
}

// 预览弹窗中的下载按钮
const handlePreviewDownload = () => {
  const fileName = previewData.value?.file_name
  const recordId = fileName ? exportResults.value.find(
    (r) => r.file_name === fileName
  )?.id : null

  if (recordId) {
    downloadById(recordId)
  }
  previewVisible.value = false
}

// 下载文件（根据ID）
const downloadById = async (recordId: number) => {
  try {
    await api.downloadExport(recordId)
    ElMessage.success('开始下载')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 下载文件
const downloadResult = (result: ExportResult) => {
  const recordId = result.id || result.record_id
  if (!recordId) {
    ElMessage.error('无法获取文件ID')
    return
  }

  downloadById(recordId)
}

// 分享
const shareResult = async (result: ExportResult) => {
  const recordId = result.id || result.record_id
  if (!recordId) {
    ElMessage.error('无法获取文件ID')
    return
  }

  try {
    const data = await api.shareExport(recordId)
    // 将分享链接复制到剪贴板
    const fullUrl = window.location.origin + data.share_url
    await navigator.clipboard.writeText(fullUrl)
    ElMessage.success('分享链接已复制到剪贴板')
  } catch (error) {
    console.error('分享失败:', error)
    ElMessage.error('分享失败')
  }
}

// 删除
const deleteResult = (result: ExportResult) => {
  resultToDelete.value = result
  dialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!resultToDelete.value) return

  const recordId = resultToDelete.value.id || resultToDelete.value.record_id
  if (!recordId) {
    ElMessage.error('无法获取文件ID')
    dialogVisible.value = false
    resultToDelete.value = null
    return
  }

  try {
    const success = await api.deleteExport(recordId)
    if (success) {
      // 从列表中移除
      const index = exportResults.value.findIndex(
        (r) => (r.id || r.record_id) === recordId
      )
      if (index > -1) {
        exportResults.value.splice(index, 1)
      }
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }

  dialogVisible.value = false
  resultToDelete.value = null
}

// 选择导出样式
const handleSelect = async (item: ExportStyle) => {
  // 使用大任务ID（从 TaskTemplate 传入的 props.TaskID）
  const taskId = props.TaskID
  console.log('导出任务 - TaskID:', taskId)

  if (!taskId) {
    ElMessage.warning('请先选择任务')
    return
  }

  // 防止重复点击
  if (loadingTypes.value.includes(item.type)) {
    return
  }

  // 添加加载状态
  loadingTypes.value.push(item.type)

  try {
    // 调用后端接口导出（导出整个大任务的执行结果）
    console.log('开始导出 - task_id:', taskId, 'type:', item.type)
    const result = await api.exportTask({
      task_id: taskId,
      export_type: item.type,
      user_id: 'current_user', // TODO: 获取实际用户ID
    })
    console.log('导出结果:', result)

    // 添加到导出结果列表（添加到最前面）
    const newItem: ExportResult = {
      id: result.record_id,
      record_id: result.record_id,
      name: result.file_name,
      icon: item.icon,
      type: item.type,
      color: item.color,
      exportTime: Date.now(),
      created_at: new Date().toISOString(),
      file_url: result.file_url,
      file_name: result.file_name,
      export_type: item.type,
    }

    exportResults.value.unshift(newItem)

    console.log('导出成功:', result)
    ElMessage.success(`导出成功: ${item.name}`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error(`导出失败: ${item.name}`)
  } finally {
    // 移除加载状态
    const idx = loadingTypes.value.indexOf(item.type)
    if (idx > -1) {
      loadingTypes.value.splice(idx, 1)
    }
  }
}

// 组件挂载时获取导出列表
onMounted(() => {
  fetchExportList()
})
</script>

<style scoped lang="scss">
.export-list {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.export-style-grid {
  display: grid;
  grid-template-columns: repeat(3, 152px);
  gap: 12px;
  justify-content: center;
  margin: 0 -16px 16px -16px;
  padding: 0 16px 16px 16px;
  border-bottom: 1px solid var(--color-border-separate);
}

.export-style-item {
  width: 152px;
  height: 50px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  padding: 0 12px;
  gap: 8px;
  border-radius: 12px;
  background: var(--color-bg-detail);
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    background: var(--color-bg-content-hover);
  }

  &.is-loading {
    opacity: 0.6;
    cursor: not-allowed;
  }

  .style-icon {
    flex-shrink: 0;
    color: var(--color-text-plan-item);
  }

  .style-name {
    font-size: 14px;
    font-weight: 500;
    color: var(--color-text-plan-item);
    white-space: nowrap;
  }
}

.export-result-section {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .result-title {
    font-size: 14px;
    font-weight: 500;
    color: var(--color-text-primary);
    margin-bottom: 12px;
  }

  .result-list {
    flex: 1;
    overflow-y: auto;
    max-height: calc(100vh - 430px);
  }

  .result-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px;
    margin-bottom: 8px;
    border-radius: 8px;
    background: var(--color-bg-three);
    transition: background 0.2s;

    &:hover {
      background: var(--color-bg-hover);

      .result-name {
        color: var(--color-text-plan-item-hover);
      }
    }
    .result-icon {
      color: var(--color-text-plan-item);
    }

    .result-info {
      flex: 1;
      min-width: 0;

      .result-name {
        font-size: 14px;
        color: var(--color-text-placeholder);
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        transition: color 0.2s;
      }

      .result-time {
        font-size: 12px;
        color: var(--color-text-plan-item);
        margin-top: 4px;
      }
    }

    .result-actions {
      display: flex;
      gap: 8px;
      margin-left: 12px;
    }
  }

  // 更多按钮
  .more-btn {
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    transition: background-color 0.2s;

    .more-icon {
      color: var(--color-text-plan-item);
      transition: color 0.2s;
    }

    &:hover {
      background-color: var(--color-card-border-three);

      .more-icon {
        color: var(--color-text-plan-item-hover);
      }
    }
  }

  // 操作菜单
  .action-menu {
    display: flex;
    flex-direction: column;
  }

  .result-empty {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--color-text-placeholder);
    font-size: 14px;
  }
}

// 预览内容样式
.preview-content {
  min-height: 300px;
  max-height: 60vh;
  overflow: auto;

  .preview-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 300px;
    gap: 12px;
    color: var(--color-text-placeholder);

    .el-icon {
      font-size: 32px;
    }
  }

  .preview-markdown {
    padding: 16px;
    background: var(--color-bg-detail);
    border-radius: 8px;

    pre {
      white-space: pre-wrap;
      word-wrap: break-word;
      font-family: monospace;
      font-size: 14px;
      line-height: 1.6;
    }
  }

  .preview-iframe {
    display: flex;
    flex-direction: column;
    align-items: center;

    iframe {
      width: 100%;
      height: 400px;
      border: none;
      border-radius: 8px;
      background: var(--color-bg-detail);
    }

    .preview-tip {
      margin-top: 12px;
      color: var(--color-text-placeholder);
      font-size: 14px;
    }
  }

  .preview-empty {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: var(--color-text-placeholder);
  }
}
</style>

<style lang="scss">
.action-popover {
  padding: 0 !important;
  border-radius: 8px !important;
  width: 120px !important;
  min-width: 120px !important;
  background: var(--color-bg-three) !important;
  border: 1px solid var(--color-card-border-three) !important;
}

.action-menu {
  display: flex;
  flex-direction: column;

  .el-popover__content {
    padding: 0;
  }
}

.action-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 13px;
  color: var(--color-text-plan-item);
  transition: background-color 0.2s, color 0.2s;

  .svg-icon {
    color: var(--color-text-plan-item);
    transition: color 0.2s;
  }

  &:hover {
    background-color: var(--color-card-border-three);
    color: var(--color-text-plan-item-hover);

    .svg-icon {
      color: var(--color-text-plan-item-hover);
    }
  }

  &:first-child {
    border-radius: 8px 8px 0 0;
  }

  &:last-child {
    border-radius: 0 0 8px 8px;
  }
}

// 预览弹窗样式
.preview-dialog {
  .el-dialog__body {
    padding: 16px;
  }
}
</style>
