<template>
  <div class="history-container">
    <!-- 头部 -->
    <header class="header">
      <div class="logo">
        <el-icon>
          <Clock />
        </el-icon>
        下载历史
      </div>
      <div class="header-actions">
        <el-button @click="clearAllHistory" type="danger" size="small">
          清空历史
        </el-button>
        <el-button @click="goBack" type="primary" size="small">
          返回下载器
        </el-button>
      </div>
    </header>

    <!-- 主要内容 -->
    <div class="main-content">
      <!-- 统计信息 -->
      <el-card class="stats-card">
        <div class="stats-grid">
          <div class="stat-item">
            <div class="stat-number">{{ totalNumObj.countNum }}</div>
            <div class="stat-label">总记录数</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ totalNumObj.status3 }}</div>
            <div class="stat-label">已完成</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ totalNumObj.status4 }}</div>
            <div class="stat-label">失败</div>
          </div>
          <div class="stat-item">
            <div class="stat-number">{{ totalNumObj.fileLength }}</div>
            <div class="stat-label">总大小</div>
          </div>
        </div>
      </el-card>

      <!-- 历史记录列表 -->
      <el-card class="history-card">
        <template #header>
          <div class="card-header">
            <span>历史记录</span>
            <div class="header-actions">
              <el-select v-model="statusFilter" placeholder="状态筛选" size="small" style="width: 120px;" @change="statusChange">
                <el-option label="全部" value="all" />
                <el-option label="已完成" value="completed" />
                <el-option label="失败" value="error" />
                <el-option label="暂停" value="paused" />
              </el-select>
              <el-select v-model="excelFileFilter" placeholder="Excel文件筛选" size="small"
                style="width: 150px; margin-left: 10px;" @change="excelFileFilterChange">
                <el-option label="全部Excel文件" value="" />
                <el-option v-for="excelFile in excelFileFilterList" :key="excelFile" :label="excelFile"
                  :value="excelFile" />
              </el-select>
              <el-input v-model="searchKeyword" placeholder="搜索文件名或Excel文件" size="small"
                style="width: 200px; margin-left: 10px;" clearable @change="searchKeywordChange">
                <template #prefix>
                  <el-icon>
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </template>

        <!-- 历史记录表格 -->
        <el-table :data="filteredHistory" style="width: 100%" :default-sort="{ prop: 'timestamp', order: 'descending' }"
          stripe>
          <el-table-column prop="timestamp" label="时间" width="180" sortable>
            <template #default="scope">
              {{ formatDate(scope.row.timestamp) }}
            </template>
          </el-table-column>

          <el-table-column prop="excelFileName" label="Excel文件" width="180">
            <template #default="scope">
              <div class="excel-file-info">
                <el-icon>
                  <Document />
                </el-icon>
                <span class="excel-file-name">{{ scope.row.excelFileName || '-' }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="fileName" label="文件名" min-width="200">
            <template #default="scope">
              <div class="file-info">
                <span class="file-name">
                  <span v-if="scope.row.fileNamePrefix" class="file-prefix">
                    {{ scope.row.fileNamePrefix }}_
                  </span>
                  {{ scope.row.fileName }}
                </span>
                <span class="file-url">{{ scope.row.url }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- <el-table-column prop="progress" label="进度" width="120">
            <template #default="scope">
              <div v-if="scope.row.status === 'completed'">
                <el-progress :percentage="100" status="success" />
              </div>
              <div v-else-if="scope.row.status === 'error'">
                <el-progress :percentage="scope.row.progress || 0" status="exception" />
              </div>
              <div v-else>
                <el-progress :percentage="scope.row.progress || 0" />
              </div>
            </template>
          </el-table-column> -->

          <el-table-column prop="fileSize" label="文件大小" width="120">
            <template #default="scope">
                {{ scope.row.status=='completed' ? scope.row.fileSize : '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="downloadedBytes" label="已下载" width="120">
            <template #default="scope">
                {{ scope.row.status=='completed' ? scope.row.fileSize : '-' }}
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <!-- <el-button v-if="scope.row.status === 'error'" @click="retryDownload(scope.row)" type="primary"
                size="small">
                重试
              </el-button> -->
              <el-button @click="viewDetails(scope.row)" type="info" size="small">
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="deTotal" layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailsVisible" title="下载详情" width="600px">
      <div v-if="selectedRecord" class="details-content">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="Excel文件">{{ selectedRecord.excelFileName || '-' }}</el-descriptions-item>
          <el-descriptions-item label="文件名">
            <span v-if="selectedRecord.fileNamePrefix" class="file-prefix">
              {{ selectedRecord.fileNamePrefix }}_
            </span>
            {{ selectedRecord.fileName }}
          </el-descriptions-item>
          <el-descriptions-item label="下载地址">{{ selectedRecord.url }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(selectedRecord.status)">
              {{ getStatusText(selectedRecord.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="进度">{{ selectedRecord.progress || 0 }}%</el-descriptions-item>
          <!-- <el-descriptions-item label="文件大小">{{ formatFileSize(selectedRecord.fileSize) }}</el-descriptions-item> -->
           <el-descriptions-item label="文件大小">{{ selectedRecord.fileSize }}</el-descriptions-item>
          <!-- <el-descriptions-item label="已下载">{{ formatFileSize(selectedRecord.downloadedBytes) }}</el-descriptions-item> -->
           <el-descriptions-item label="已下载">{{ selectedRecord.downloadedBytes }}</el-descriptions-item>
          <el-descriptions-item label="开始时间">{{ formatDate(selectedRecord.startTime) }}</el-descriptions-item>
          <el-descriptions-item label="结束时间">{{ formatDate(selectedRecord.endTime) }}</el-descriptions-item>
          <el-descriptions-item v-if="selectedRecord.error" label="错误信息">
            <span class="error-message">{{ selectedRecord.error }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, valueEquals } from 'element-plus'
import { Clock, Search } from '@element-plus/icons-vue'
import { useAuthStore } from '../stores/auth'
import http from '@/utils/request.js';
import config from '@/api/api.js';
import { ca } from 'element-plus/es/locales.mjs'

const router = useRouter()
const authStore = useAuthStore()

// 状态
const historyData = ref([])
const statusFilter = ref('completed')
const excelFileFilter = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const detailsVisible = ref(false)
const selectedRecord = ref(null)
const excelFileFilterList = ref([])

// const deQuery = ref({
//   current: 1,
//   pageSize: 10,
//   fileStatus: 3,
//   fileName: ''
// })
// let deTableData =
//  reactive([])
let deTotal = ref(0)
const statusMap = {
  0: 'pending',
  1: 'downloading',
  2: 'paused',
  3: 'completed',
  4: 'error'
}
function laodFileAll(){
  http.post(config.queryFileAll).then(res=>{
    if (res.code === 200){
      excelFileFilterList.value = res.data
    }else {
      ElMessage.error(res.message)
    }
  })
}
const statusFilterMap = {
  'all': '',
  'completed': 3,
  'error': 4,
  'paused': 2
}
// 加载历史数据
const loadHistory = () => {
  // historyData.value = authStore.getDownloadHistory()
  http.post(config.uploadDetailList, {
    current: currentPage.value,
    pageSize: pageSize.value,
    fileStatus: statusFilterMap[statusFilter.value],
    uploadName: excelFileFilter.value,
    fileName: searchKeyword.value
  }).then(res => {
    if (res.code === 200) {
      var list = []
      var updateTime = ''
      for (const element of res.data.rows) {
        updateTime = element.updateTime
        list.push({
          "id": element.detailId,
          "fileName": element.fileName,
          "fileNamePrefix": "",
          "excelFileName": element.uploadName,
          "url": element.fileUrl,
          "status": statusMap[element.fileStatus],
          "progress": 100,
          "fileSize": element.fileLength,
          "downloadedBytes": 0,
          "startTime": element.createTime,
          "endTime": '',
          "error": null,
          "fileNamePrefix": element.filePrefix
        })
      }
      historyData.value = [{
        downloads: list,
        timestamp: updateTime,
        userId: ''
      }]
      // deTableData = res.data.rows
      deTotal.value = res.data.total
    } else {
      ElMessage.error(res.message)
    }
  })
}
let totalNumObj = ref({
  "countNum": 0,
  "fileLength": '0 KB',
  "status0": 0,
  "status1": 0,
  "status2": 0,
  "status3": 0,
  "status4": 0
})
function loadUploadDetailTotalNum(){
  http.post(config.uploadDetailTotalNum).then(res=>{ 
    if (res.code === 200){
      totalNumObj.value.countNum = res.data.countNum
      totalNumObj.value.status3 = res.data.status3
      totalNumObj.value.status4 = res.data.status4
      totalNumObj.value.fileLength = res.data.fileLength
    }else {
      ElMessage.error(res.message)
    }
  })
}
function statusChange(){
  currentPage.value = 1
  loadHistory()
}
function excelFileFilterChange(){
  currentPage.value = 1
  loadHistory()
}
function searchKeywordChange(){
  currentPage.value = 1
  loadHistory()
}

// 获取唯一的Excel文件列表
const uniqueExcelFiles = computed(() => {
  const allDownloads = historyData.value.flatMap(record =>
    record.downloads.map(download => ({
      ...download,
      timestamp: record.timestamp
    }))
  )

  const excelFiles = allDownloads
    .map(item => item.excelFileName)
    .filter(file => file && file.trim())

  return [...new Set(excelFiles)]
})

// 筛选历史记录
const filteredHistory = computed(() => {
  let filtered = historyData.value.flatMap(record =>
    record.downloads.map(download => ({
      ...download,
      timestamp: record.timestamp
    }))
  )

  // 状态筛选
  // if (statusFilter.value) {
  //   filtered = filtered.filter(item => item.status === statusFilter.value)
  // }

  // Excel文件筛选
  // if (excelFileFilter.value) {
  //   filtered = filtered.filter(item => item.excelFileName === excelFileFilter.value)
  // }

  // 关键词搜索
  // if (searchKeyword.value) {
  //   const keyword = searchKeyword.value.toLowerCase()
  //   filtered = filtered.filter(item =>
  //     item.fileName.toLowerCase().includes(keyword) ||
  //     item.url.toLowerCase().includes(keyword) ||
  //     (item.excelFileName && item.excelFileName.toLowerCase().includes(keyword))
  //   )
  // }

  return filtered
})

// 分页后的数据
const paginatedHistory = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredHistory.value.slice(start, end)
})

// 统计信息
const totalRecords = computed(() => filteredHistory.value.length)
const completedCount = computed(() => filteredHistory.value.filter(item => item.status === 'completed').length)
const failedCount = computed(() => filteredHistory.value.filter(item => item.status === 'error').length)
const totalSize = computed(() => {
  const total = filteredHistory.value
    .filter(item => item.status === 'completed')
    .reduce((sum, item) => sum + (item.fileSize || 0), 0)
  return formatFileSize(total)
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString()
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes || bytes === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'completed': return 'success'
    case 'error': return 'danger'
    case 'paused': return 'warning'
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'completed': return '已完成'
    case 'error': return '失败'
    case 'paused': return '暂停'
    case 'downloading': return '下载中'
    case 'pending': return '等待中'
    default: return '未知'
  }
}

// 查看详情
const viewDetails = (record) => {
  http.post(config.detailInfo,{detailId: record.id}).then(res=>{
    if (res.code === 200){
      selectedRecord.value = {
        "id": res.data.detailId,
        "fileName": res.data.fileName,
        "fileNamePrefix": res.data.filePrefix,
        "excelFileName": res.data.uploadName,
        "url": res.data.fileUrl,
        "status": statusMap[res.data.fileStatus],
        "progress": res.data.fileStatus == 3 ? 100: 0,
        "fileSize": res.data.fileLength,
        "downloadedBytes": res.data.fileStatus == 3 ? res.data.fileLength: '-',
        "startTime": res.data.createTime,
        "endTime": '',
        "error": res.data.errorMsg
      }
      detailsVisible.value = true
    }else {
      ElMessage.error(res.message)
    }
  })
}

// 重试下载
const retryDownload = async (record) => {
  try {
    await ElMessageBox.confirm(
      `确定要重新下载 "${record.fileName}" 吗？`,
      '确认重试',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    // 这里可以调用下载store的方法重新下载
    ElMessage.success('已添加到下载队列')
  } catch {
    // 用户取消
  }
}

// 清空所有历史
const clearAllHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有下载历史记录吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    authStore.clearDownloadHistory()

    http.post(config.uploadDetailDeleteAll, {
      type: 1
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('历史记录已清空')
        loadHistory()
        loadUploadDetailTotalNum()
      } else {
        ElMessage.error(res.message)
      }
    })
  } catch {
    // 用户取消
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadHistory()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadHistory()
}

// 返回下载器
const goBack = () => {
  router.push('/downloader')
}

// 组件挂载时初始化
onMounted(() => {
  loadHistory()
  loadUploadDetailTotalNum()
  laodFileAll()
})
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  background: #f5f5f5;
}

.header {
  background: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.main-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.stat-number {
  font-size: 32px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.history-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.file-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.file-name {
  font-weight: 500;
  color: #333;
}

.file-url {
  font-size: 12px;
  color: #666;
  word-break: break-all;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.details-content {
  max-height: 400px;
  overflow-y: auto;
}

.error-message {
  color: #f56c6c;
  word-break: break-all;
}

@media (max-width: 768px) {
  .main-content {
    padding: 0 10px;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    flex-direction: column;
  }
}
</style>
