<template>
  <div class="export-container">
    <el-card shadow="never">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- Tab 1: 成绩导出 -->
        <el-tab-pane label="成绩导出" name="result">
          <div class="tab-content">
            <el-form :model="resultForm" label-width="120px" style="max-width: 800px">
              <el-form-item label="选择赛事" required>
                <el-select
                  v-model="resultForm.competitionId"
                  placeholder="请选择赛事"
                  clearable
                  filterable
                  style="width: 100%"
                  @change="handleCompetitionChange"
                >
                  <el-option
                    v-for="item in competitionList"
                    :key="item.id"
                    :label="item.competitionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择项目">
                <el-select
                  v-model="resultForm.projectId"
                  placeholder="请选择项目（不选则导出全部）"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in projectList"
                    :key="item.id"
                    :label="item.projectName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="分组类别">
                <el-select
                  v-model="resultForm.category"
                  placeholder="请选择分组类别（可选）"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="男子" value="1" />
                  <el-option label="女子" value="2" />
                  <el-option label="团体" value="3" />
                  <el-option label="混合" value="4" />
                </el-select>
              </el-form-item>
              <el-form-item label="导出内容">
                <el-checkbox-group v-model="resultForm.exportFields">
                  <el-checkbox label="ranking">排名</el-checkbox>
                  <el-checkbox label="athleteName">选手姓名</el-checkbox>
                  <el-checkbox label="teamName">团队名称</el-checkbox>
                  <el-checkbox label="projectName">项目</el-checkbox>
                  <el-checkbox label="totalScore">总分</el-checkbox>
                  <el-checkbox label="finalScore">最终成绩</el-checkbox>
                  <el-checkbox label="medal">奖牌</el-checkbox>
                  <el-checkbox label="judgeScores">裁判评分明细</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
              <el-form-item label="导出格式">
                <el-radio-group v-model="resultForm.format">
                  <el-radio label="xlsx">Excel (xlsx)</el-radio>
                  <el-radio label="pdf">PDF</el-radio>
                  <el-radio label="csv">CSV</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="Download"
                  :loading="resultLoading"
                  @click="handleExportResult"
                >
                  导出成绩单
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- Tab 2: 名单导出 -->
        <el-tab-pane label="名单导出" name="list">
          <div class="tab-content">
            <el-form :model="listForm" label-width="120px" style="max-width: 800px">
              <el-form-item label="选择赛事" required>
                <el-select
                  v-model="listForm.competitionId"
                  placeholder="请选择赛事"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in competitionList"
                    :key="item.id"
                    :label="item.competitionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="名单类型" required>
                <el-radio-group v-model="listForm.type">
                  <el-radio label="athlete">运动员名单</el-radio>
                  <el-radio label="referee">裁判名单</el-radio>
                  <el-radio label="staff">工作人员名单</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="导出格式">
                <el-radio-group v-model="listForm.format">
                  <el-radio label="xlsx">Excel (xlsx)</el-radio>
                  <el-radio label="pdf">PDF</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="Download"
                  :loading="listLoading"
                  @click="handleExportList"
                >
                  导出名单
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- Tab 3: 证书生成 -->
        <el-tab-pane label="证书生成" name="certificate">
          <div class="tab-content">
            <el-form :model="certForm" label-width="120px" style="max-width: 800px">
              <el-form-item label="选择赛事" required>
                <el-select
                  v-model="certForm.competitionId"
                  placeholder="请选择赛事"
                  clearable
                  filterable
                  style="width: 100%"
                  @change="handleCertCompetitionChange"
                >
                  <el-option
                    v-for="item in competitionList"
                    :key="item.id"
                    :label="item.competitionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择项目">
                <el-select
                  v-model="certForm.projectId"
                  placeholder="请选择项目"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in certProjectList"
                    :key="item.id"
                    :label="item.projectName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="证书类型" required>
                <el-radio-group v-model="certForm.certType">
                  <el-radio label="medal">获奖证书（金银铜牌）</el-radio>
                  <el-radio label="participation">参赛证书</el-radio>
                  <el-radio label="excellent">优秀运动员证书</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="证书模板" required>
                <el-select
                  v-model="certForm.templateId"
                  placeholder="请选择证书模板"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in certificateTemplates"
                    :key="item.id"
                    :label="item.templateName"
                    :value="item.id"
                  >
                    <span style="float: left">{{ item.templateName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">
                      {{ item.description }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="导出格式">
                <el-radio-group v-model="certForm.format">
                  <el-radio label="pdf">PDF</el-radio>
                  <el-radio label="jpg">JPG图片</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="批量生成">
                <el-switch v-model="certForm.batch" />
                <span style="margin-left: 10px; color: #909399; font-size: 13px">
                  开启后将根据筛选条件批量生成
                </span>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="DocumentAdd"
                  :loading="certLoading"
                  @click="handleGenerateCertificate"
                >
                  生成证书
                </el-button>
                <el-button
                  type="success"
                  :icon="View"
                  @click="handlePreviewCertificate"
                >
                  预览模板
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 证书列表 -->
            <el-divider />
            <h4>已生成证书</h4>
            <el-table :data="certificateList" border stripe>
              <el-table-column prop="athleteName" label="选手姓名" width="120" />
              <el-table-column prop="projectName" label="项目" min-width="150" />
              <el-table-column prop="ranking" label="排名" width="80" align="center" />
              <el-table-column prop="medal" label="奖牌" width="100" align="center">
                <template #default="{ row }">
                  <el-tag v-if="row.medal === 'gold'" type="danger">🏅 金牌</el-tag>
                  <el-tag v-else-if="row.medal === 'silver'" type="warning">🥈 银牌</el-tag>
                  <el-tag v-else-if="row.medal === 'bronze'" type="success">🥉 铜牌</el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="generateTime" label="生成时间" width="160" align="center">
                <template #default="{ row }">
                  {{ formatDate(row.generateTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" align="center">
                <template #default="{ row }">
                  <el-button link type="primary" :icon="View" @click="handleViewCertificate(row)">
                    预览
                  </el-button>
                  <el-button link type="success" :icon="Download" @click="handleDownloadCertificate(row)">
                    下载
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- Tab 4: 报表导出 -->
        <el-tab-pane label="报表导出" name="report">
          <div class="tab-content">
            <el-form :model="reportForm" label-width="120px" style="max-width: 800px">
              <el-form-item label="报表类型" required>
                <el-select
                  v-model="reportForm.reportType"
                  placeholder="请选择报表类型"
                  style="width: 100%"
                  @change="handleReportTypeChange"
                >
                  <el-option
                    label="赛事统计报表"
                    value="competition"
                    description="包含赛事基本信息、参赛人数、项目数量等统计"
                  />
                  <el-option
                    label="项目统计报表"
                    value="project"
                    description="各项目报名人数、参赛人数、获奖分布等"
                  />
                  <el-option
                    label="裁判工作量报表"
                    value="referee"
                    description="裁判评分数量、工作时长等统计"
                  />
                  <el-option
                    label="报名统计报表"
                    value="registration"
                    description="报名趋势、地域分布、团队排名等"
                  />
                  <el-option
                    label="奖牌榜报表"
                    value="medal"
                    description="团队/地区奖牌榜"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="选择赛事" required>
                <el-select
                  v-model="reportForm.competitionId"
                  placeholder="请选择赛事"
                  clearable
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in competitionList"
                    :key="item.id"
                    :label="item.competitionName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="导出格式">
                <el-radio-group v-model="reportForm.format">
                  <el-radio label="xlsx">Excel (xlsx)</el-radio>
                  <el-radio label="pdf">PDF</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="包含图表">
                <el-switch v-model="reportForm.includeCharts" />
                <span style="margin-left: 10px; color: #909399; font-size: 13px">
                  导出PDF时包含统计图表
                </span>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  :icon="Download"
                  :loading="reportLoading"
                  @click="handleExportReport"
                >
                  导出报表
                </el-button>
              </el-form-item>
            </el-form>

            <!-- 报表说明 -->
            <el-divider />
            <el-alert type="info" :closable="false" show-icon>
              <template #title>
                <strong>报表说明</strong>
              </template>
              <div style="margin-top: 10px">
                <p><strong>赛事统计报表：</strong>包含赛事基本信息、时间、地点、参赛人数、项目数量、裁判数量等综合统计信息</p>
                <p><strong>项目统计报表：</strong>各项目报名人数、实际参赛人数、获奖分布、平均分、最高分、最低分等详细数据</p>
                <p><strong>裁判工作量报表：</strong>每位裁判的评分数量、负责项目、工作时长、评分准确性等统计</p>
                <p><strong>报名统计报表：</strong>报名趋势分析、地域分布、团队排名、报名费收入统计等</p>
                <p><strong>奖牌榜报表：</strong>按团队或地区统计金银铜牌数量，包含总积分排名</p>
              </div>
            </el-alert>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 证书预览弹窗 -->
    <el-dialog v-model="previewVisible" title="证书预览" width="900px">
      <div class="certificate-preview">
        <img v-if="previewUrl" :src="previewUrl" style="width: 100%" />
        <el-empty v-else description="暂无预览" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Download,
  DocumentAdd,
  View
} from '@element-plus/icons-vue'
import {
  exportResults,
  exportAwardList,
  generateCertificate,
  batchGenerateCertificates
} from '@/api/martial/result'
import { getCompetitionList } from '@/api/martial/competition'
import { getProjectsByCompetition } from '@/api/martial/project'
import {
  exportAthletes,
  exportReferees,
  exportStaff
} from '@/api/martial/export'
import dayjs from 'dayjs'

// 数据定义
const activeTab = ref('result')
const resultLoading = ref(false)
const listLoading = ref(false)
const certLoading = ref(false)
const reportLoading = ref(false)
const previewVisible = ref(false)
const previewUrl = ref('')

const competitionList = ref([])
const projectList = ref([])
const certProjectList = ref([])
const certificateList = ref([])
const certificateTemplates = ref([
  { id: 1, templateName: '标准证书模板', description: '简洁大方' },
  { id: 2, templateName: '豪华证书模板', description: '精美设计' },
  { id: 3, templateName: '传统证书模板', description: '古典风格' }
])

// 成绩导出表单
const resultForm = reactive({
  competitionId: '',
  projectId: '',
  category: '',
  exportFields: ['ranking', 'athleteName', 'teamName', 'projectName', 'finalScore', 'medal'],
  format: 'xlsx'
})

// 名单导出表单
const listForm = reactive({
  competitionId: '',
  type: 'athlete',
  format: 'xlsx'
})

// 证书生成表单
const certForm = reactive({
  competitionId: '',
  projectId: '',
  certType: 'medal',
  templateId: null,
  format: 'pdf',
  batch: false
})

// 报表导出表单
const reportForm = reactive({
  reportType: 'competition',
  competitionId: '',
  format: 'xlsx',
  includeCharts: true
})

// 加载赛事列表
const loadCompetitionList = async () => {
  try {
    const res = await getCompetitionList(1, 1000, { status: 1 })
    if (res.data && res.data.records) {
      competitionList.value = res.data.records
    }
  } catch (error) {
    console.error('加载赛事列表失败:', error)
  }
}

// 赛事变化
const handleCompetitionChange = async (competitionId) => {
  resultForm.projectId = ''
  projectList.value = []

  if (competitionId) {
    try {
      const res = await getProjectsByCompetition(competitionId)
      if (res.data) {
        projectList.value = res.data
      }
    } catch (error) {
      console.error('加载项目列表失败:', error)
    }
  }
}

// 证书赛事变化
const handleCertCompetitionChange = async (competitionId) => {
  certForm.projectId = ''
  certProjectList.value = []

  if (competitionId) {
    try {
      const res = await getProjectsByCompetition(competitionId)
      if (res.data) {
        certProjectList.value = res.data
      }
    } catch (error) {
      console.error('加载项目列表失败:', error)
    }
  }
}

// 报表类型变化
const handleReportTypeChange = (type) => {
  // 可根据不同报表类型显示不同的配置项
  console.log('报表类型:', type)
}

// 导出成绩
const handleExportResult = async () => {
  if (!resultForm.competitionId) {
    ElMessage.warning('请选择赛事')
    return
  }

  resultLoading.value = true
  try {
    const res = await exportResults(resultForm)
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `成绩单_${dayjs().format('YYYYMMDDHHmmss')}.${resultForm.format}`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    resultLoading.value = false
  }
}

// 导出名单
const handleExportList = async () => {
  if (!listForm.competitionId) {
    ElMessage.warning('请选择赛事')
    return
  }

  listLoading.value = true
  try {
    let exportFunc
    switch (listForm.type) {
      case 'athlete':
        exportFunc = exportAthletes
        break
      case 'referee':
        exportFunc = exportReferees
        break
      case 'staff':
        exportFunc = exportStaff
        break
    }

    const res = await exportFunc({
      competitionId: listForm.competitionId,
      format: listForm.format
    })

    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `${listForm.type}_名单_${dayjs().format('YYYYMMDDHHmmss')}.${listForm.format}`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    listLoading.value = false
  }
}

// 生成证书
const handleGenerateCertificate = async () => {
  if (!certForm.competitionId) {
    ElMessage.warning('请选择赛事')
    return
  }
  if (!certForm.templateId) {
    ElMessage.warning('请选择证书模板')
    return
  }

  certLoading.value = true
  try {
    let res
    if (certForm.batch) {
      res = await batchGenerateCertificates(certForm)
      ElMessage.success('批量生成成功，正在下载...')
    } else {
      res = await generateCertificate(certForm)
      ElMessage.success('生成成功，正在下载...')
    }

    const blob = new Blob([res], { type: 'application/pdf' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `证书_${dayjs().format('YYYYMMDDHHmmss')}.${certForm.format}`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    ElMessage.error('生成失败')
  } finally {
    certLoading.value = false
  }
}

// 预览证书模板
const handlePreviewCertificate = () => {
  if (!certForm.templateId) {
    ElMessage.warning('请先选择证书模板')
    return
  }
  // 这里可以加载模板预览图
  previewUrl.value = `/static/templates/cert_${certForm.templateId}.jpg`
  previewVisible.value = true
}

// 查看证书
const handleViewCertificate = (row) => {
  previewUrl.value = row.certificateUrl
  previewVisible.value = true
}

// 下载证书
const handleDownloadCertificate = (row) => {
  window.open(row.certificateUrl, '_blank')
}

// 导出报表
const handleExportReport = async () => {
  if (!reportForm.competitionId) {
    ElMessage.warning('请选择赛事')
    return
  }

  reportLoading.value = true
  try {
    // 根据不同的报表类型调用不同的API
    // 这里简化处理，实际应该有不同的API接口
    const res = await exportResults({
      ...reportForm,
      reportType: reportForm.reportType
    })

    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `${reportForm.reportType}_报表_${dayjs().format('YYYYMMDDHHmmss')}.${reportForm.format}`
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    ElMessage.error('导出失败')
  } finally {
    reportLoading.value = false
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 生命周期
onMounted(() => {
  loadCompetitionList()
})
</script>

<style scoped lang="scss">
.export-container {
  padding: 20px;

  .tab-content {
    padding: 20px 0;
  }

  .certificate-preview {
    text-align: center;
    padding: 20px;
  }

  :deep(.el-tabs__content) {
    padding: 20px;
  }

  :deep(.el-checkbox-group) {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  :deep(.el-alert) {
    p {
      margin: 5px 0;
      line-height: 1.8;
    }
  }
}
</style>
