<!--
  页面名称：FunctionalReport.vue
  页面描述：报告中心-功能测试模块页面，支持上传Excel、生成报告（含ERP上传选项）

  @author czj
  @date 2026-08-12
-->

<template>
  <div class="functional-report-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>功能测试报告</h2>
      <el-button @click="resetAll">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
    </div>

    <!-- 步骤1：上传Excel -->
    <el-card class="step-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="step-title">① 上传测试数据</span>
          <span class="step-tip">上传测试用例 Excel 和 BUG 列表 Excel</span>
        </div>
      </template>

      <div class="upload-grid">
        <el-upload
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="(file: any) => (testcaseFile = file.raw)"
          :on-remove="() => (testcaseFile = null)"
          accept=".xlsx,.xls"
          class="upload-item"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">拖拽测试用例 Excel 到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">测试用例表：表头第 3 行，数据从第 4 行开始（17 列）</div>
          </template>
        </el-upload>

        <el-upload
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="(file: any) => (buglistFile = file.raw)"
          :on-remove="() => (buglistFile = null)"
          accept=".xlsx,.xls"
          class="upload-item"
        >
          <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
          <div class="el-upload__text">拖拽 BUG 列表 Excel 到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip">BUG 列表：表头第 1 行，数据从第 2 行开始（9 列）</div>
          </template>
        </el-upload>
      </div>

      <div class="upload-actions">
        <el-button
          type="primary"
          :loading="uploading"
          :disabled="!testcaseFile || !buglistFile"
          @click="handleUpload"
        >
          <el-icon><Upload /></el-icon>
          上传文件
        </el-button>
        <el-tag v-if="sessionId" type="success" size="small">会话: {{ sessionId }}</el-tag>
      </div>
    </el-card>

    <!-- 步骤2：生成报告（含ERP上传选项） -->
    <el-card class="step-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="step-title">② 生成报告</span>
          <span class="step-tip">配置项目信息，选择是否自动上传到 ERP</span>
        </div>
      </template>

      <el-form label-width="100px">
        <!-- 基本配置 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="项目名称">
              <el-input v-model="projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="报告模板">
              <el-select v-model="selectedTemplateId" placeholder="使用默认模板" clearable style="width: 100%">
                <el-option v-for="tpl in templateList" :key="tpl.id" :label="tpl.name" :value="tpl.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="报告格式">
              <el-radio-group v-model="reportFormat">
                <el-radio value="docx">Word</el-radio>
                <el-radio value="md">Markdown</el-radio>
                <el-radio value="both">两者</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- ERP 上传选项 -->
        <el-divider content-position="left">ERP 自动上传（可选）</el-divider>

        <el-row :gutter="20">
          <!-- 上传到测试单 -->
          <el-col :span="8">
            <el-checkbox v-model="erpEnabled" label="上传到ERP测试单" border class="erp-checkbox" />
            <div v-if="erpEnabled" class="erp-options">
              <el-form-item label="测试单ID">
                <el-input-number v-model="developtestingId" :min="1" style="width: 180px" />
                <span class="form-tip">留空使用默认</span>
              </el-form-item>
              <el-form-item label="抄送人">
                <el-select
                  v-model="copyuserNames"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  placeholder="输入姓名，回车添加"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="创建人">
                <el-input v-model="createuserName" placeholder="创建人姓名" style="width: 180px" />
              </el-form-item>
            </div>
          </el-col>

          <!-- 上传到项目资料 -->
          <el-col :span="8">
            <el-checkbox v-model="projectEnabled" label="上传到项目资料" border class="erp-checkbox" />
            <div v-if="projectEnabled" class="erp-options">
              <el-form-item label="项目ID" required>
                <el-input-number v-model="projectId" :min="1" style="width: 180px" />
              </el-form-item>
              <el-form-item label="文件名称">
                <el-input v-model="projectFileName" placeholder="默认取报告名" style="width: 220px" />
              </el-form-item>
            </div>
          </el-col>

          <!-- 上传到协作文档 -->
          <el-col :span="8">
            <el-checkbox v-model="cooperationEnabled" label="上传到协作文档" border class="erp-checkbox" />
            <div v-if="cooperationEnabled" class="erp-options">
              <el-form-item label="项目ID" required>
                <el-input-number v-model="cooperationProjectId" :min="1" style="width: 180px" />
              </el-form-item>
              <el-form-item label="文件名称">
                <el-input v-model="cooperationFileName" placeholder="默认取报告名" style="width: 220px" />
              </el-form-item>
              <el-form-item label="分组ID">
                <el-input-number v-model="cooperationGroupId" :min="1" style="width: 180px" />
                <span class="form-tip">可选</span>
              </el-form-item>
            </div>
          </el-col>
        </el-row>

        <el-divider />

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            :loading="generating"
            :disabled="!sessionId"
            @click="handleGenerate"
          >
            <el-icon><Document /></el-icon>
            {{ generating ? '生成中...' : '生成报告' }}
          </el-button>
          <span v-if="generating" class="generate-status">
            正在生成报告
            <template v-if="erpEnabled">→ 上传ERP测试单</template>
            <template v-if="projectEnabled">→ 上传项目资料</template>
            <template v-if="cooperationEnabled">→ 上传协作文档</template>
            ...
          </span>
        </el-form-item>
      </el-form>

      <!-- 生成结果 -->
      <template v-if="generateResult">
        <el-divider />
        <div class="result-summary">
          <h4>分析结果</h4>
          <div class="summary-grid">
            <div class="summary-item">
              <span class="label">项目名称</span>
              <span class="value">{{ generateResult.project_name }}</span>
            </div>
            <div class="summary-item">
              <span class="label">用例总数</span>
              <span class="value">{{ generateResult.case_analysis.total_cases }}</span>
            </div>
            <div class="summary-item">
              <span class="label">通过率</span>
              <span class="value success">{{ generateResult.case_analysis.pass_rate }}%</span>
            </div>
            <div class="summary-item">
              <span class="label">执行率</span>
              <span class="value">{{ generateResult.case_analysis.execution_rate }}%</span>
            </div>
            <div class="summary-item">
              <span class="label">BUG总数</span>
              <span class="value">{{ generateResult.bug_analysis.total_bugs }}</span>
            </div>
            <div class="summary-item">
              <span class="label">遗留BUG</span>
              <span class="value danger">{{ generateResult.bug_analysis.remaining_bugs }}</span>
            </div>
            <div class="summary-item">
              <span class="label">用例-BUG关联</span>
              <span class="value">{{ generateResult.case_bug_link_count }}</span>
            </div>
          </div>
        </div>

        <!-- ERP上传结果 -->
        <div v-if="erpResults.length" class="erp-results">
          <h4>ERP 上传结果</h4>
          <div class="erp-result-list">
            <div
              v-for="item in erpResults"
              :key="item.label"
              class="erp-result-item"
              :class="{ success: item.success, fail: !item.success }"
            >
              <el-icon v-if="item.success" class="icon-success"><CircleCheck /></el-icon>
              <el-icon v-else class="icon-fail"><CircleClose /></el-icon>
              <span class="erp-result-label">{{ item.label }}</span>
              <span class="erp-result-msg">{{ item.message }}</span>
            </div>
          </div>
        </div>

        <!-- 图表预览 -->
        <div v-if="generateResult.charts && Object.keys(generateResult.charts).length" class="charts-block">
          <h4>统计图表</h4>
          <div class="charts-grid">
            <div v-for="(path, key) in generateResult.charts" :key="key" class="chart-item">
              <span class="chart-label">{{ chartLabels[key] || key }}</span>
              <el-image
                :src="getChartUrl(path)"
                :preview-src-list="[getChartUrl(path)]"
                fit="contain"
                class="chart-img"
              />
            </div>
          </div>
        </div>

        <!-- 报告列表 -->
        <div class="reports-block">
          <h4>生成的报告</h4>
          <div class="report-list">
            <div v-for="report in generateResult.reports" :key="report" class="report-item">
              <span class="report-name">{{ getReportFileName(report) }}</span>
              <div class="report-actions">
                <el-button size="small" type="primary" @click="downloadReport(report)">
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button
                  v-if="getReportFileName(report).endsWith('.md')"
                  size="small"
                  type="primary"
                  link
                  @click="previewReport(report)"
                >
                  <el-icon><View /></el-icon>
                  预览
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </template>
    </el-card>

    <!-- Markdown 报告预览弹窗 -->
    <el-dialog
      v-model="previewVisible"
      title="功能测试报告预览"
      width="90%"
      top="5vh"
      destroy-on-close
      fullscreen
    >
      <div class="preview-container" v-loading="previewLoading">
        <iframe v-if="previewUrl" :src="previewUrl" class="preview-iframe" />
        <el-empty v-else-if="!previewLoading" description="报告加载失败" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 功能测试报告页面
 *
 * 功能：
 * 1. 上传测试用例 Excel + BUG 列表 Excel
 * 2. 生成功能测试报告，可选自动上传到 ERP 测试单/项目资料/协作文档
 * 3. 下载、预览报告
 */

import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Upload,
  UploadFilled,
  Document,
  Download,
  View,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import { functionalReportApi } from '@/api/functionalReport'
import { reportTemplateApi } from '@/api/reportTemplate'

// ==================== 响应式数据 ====================

// 文件上传
const testcaseFile = ref<File | null>(null)
const buglistFile = ref<File | null>(null)
const sessionId = ref('')
const uploading = ref(false)

// 报告生成
const projectName = ref('')
const reportFormat = ref('docx')
const generating = ref(false)
const generateResult = ref<any>(null)

// 报告模板
const selectedTemplateId = ref<number | undefined>(undefined)
const templateList = ref<any[]>([])

// ERP 上传选项
const erpEnabled = ref(false)
const projectEnabled = ref(false)
const cooperationEnabled = ref(false)

// ERP 测试单配置
const developtestingId = ref<number | undefined>(undefined)
const copyuserNames = ref<string[]>([])
const createuserName = ref('')

// 项目资料配置
const projectId = ref<number | undefined>(undefined)
const projectFileName = ref('')

// 协作文档配置
const cooperationProjectId = ref<number | undefined>(undefined)
const cooperationFileName = ref('')
const cooperationGroupId = ref<number | undefined>(undefined)

// ERP 上传结果
const erpResults = ref<{ label: string; success: boolean; message: string }[]>([])

// 预览
const previewVisible = ref(false)
const previewLoading = ref(false)
const previewUrl = ref('')

/** 图表中文标签 */
const chartLabels: Record<string, string> = {
  bug_level: 'BUG等级分布',
  test_result: '用例执行结果分布',
  pass_rate: '用例执行情况统计',
  bug_by_module: '各模块BUG分布'
}

// ==================== 方法定义 ====================

/** 加载报告模板列表 */
const loadTemplates = async () => {
  try {
    templateList.value = await reportTemplateApi.list()
  } catch (error: any) {
    console.warn('加载报告模板失败:', error.message)
  }
}

onMounted(() => {
  loadTemplates()
})

/** 上传文件 */
const handleUpload = async () => {
  if (!testcaseFile.value || !buglistFile.value) {
    ElMessage.warning('请先选择测试用例和 BUG 列表文件')
    return
  }
  uploading.value = true
  try {
    const result = await functionalReportApi.upload(
      testcaseFile.value,
      buglistFile.value,
      sessionId.value
    )
    sessionId.value = result.session_id
    ElMessage.success('文件上传成功')
  } catch (error: any) {
    ElMessage.error('文件上传失败: ' + error.message)
  } finally {
    uploading.value = false
  }
}

/** 获取报告文件名 */
const getReportFileName = (path: string) => {
  if (!path) return ''
  const parts = path.split(/[\\/]/)
  return parts[parts.length - 1]
}

/** 生成报告 + ERP 上传 */
const handleGenerate = async () => {
  if (!sessionId.value) {
    ElMessage.warning('请先上传文件')
    return
  }
  generating.value = true
  erpResults.value = []

  try {
    // 生成报告，同时由后端处理勾选的 ERP 自动上传
    const result = await functionalReportApi.generate(
      sessionId.value,
      projectName.value,
      reportFormat.value,
      selectedTemplateId.value,
      {
        upload_to_erp: erpEnabled.value,
        upload_to_project: projectEnabled.value,
        upload_to_cooperation: cooperationEnabled.value,
        developtesting_id: developtestingId.value,
        copyuser_names: copyuserNames.value,
        createuser_name: createuserName.value || undefined,
        project_id: projectId.value,
        project_file_name: projectFileName.value || undefined,
        cooperation_project_id: cooperationProjectId.value,
        cooperation_file_name: cooperationFileName.value || undefined,
        cooperation_group_id: cooperationGroupId.value
      }
    )
    generateResult.value = result

    // 展示后端返回的 ERP 上传结果
    if (result.erp_results && result.erp_results.length) {
      erpResults.value = result.erp_results.map((r: any) => ({
        label: r.label,
        success: r.success,
        message: r.message
      }))
    }

    // 统计成功数
    const successCount = erpResults.value.filter(r => r.success).length
    if (erpResults.value.length > 0) {
      if (successCount === erpResults.value.length) {
        ElMessage.success(`报告生成成功，ERP上传全部完成（${successCount}/${erpResults.value.length}）`)
      } else {
        ElMessage.warning(`报告生成成功，但 ${erpResults.value.length - successCount} 个ERP上传未完成，请查看详情`)
      }
    } else {
      ElMessage.success('报告生成成功')
    }

  } catch (error: any) {
    ElMessage.error('报告生成失败: ' + error.message)
  } finally {
    generating.value = false
  }
}

/** 重置所有状态 */
const resetAll = () => {
  testcaseFile.value = null
  buglistFile.value = null
  sessionId.value = ''
  projectName.value = ''
  reportFormat.value = 'docx'
  selectedTemplateId.value = undefined
  generateResult.value = null
  previewVisible.value = false
  erpEnabled.value = false
  projectEnabled.value = false
  cooperationEnabled.value = false
  developtestingId.value = undefined
  copyuserNames.value = []
  createuserName.value = ''
  projectId.value = undefined
  projectFileName.value = ''
  cooperationProjectId.value = undefined
  cooperationFileName.value = ''
  cooperationGroupId.value = undefined
  erpResults.value = []
  ElMessage.success('已重置')
}

/** 获取图表预览URL */
const getChartUrl = (path: string) => {
  return `/api/files/${encodeURIComponent(path)}`
}

/** 下载报告 */
const downloadReport = (path: string) => {
  window.open(functionalReportApi.downloadUrl(sessionId.value, getReportFileName(path)), '_blank')
}

/** 预览 Markdown 报告 */
const previewReport = (path: string) => {
  getReportFileName(path)
  previewUrl.value = functionalReportApi.previewUrl(sessionId.value)
  previewLoading.value = true
  previewVisible.value = true
  setTimeout(() => {
    previewLoading.value = false
  }, 1000)
}
</script>

<style lang="scss" scoped>
.functional-report-page {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
    }
  }

  .step-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      align-items: center;
      gap: 12px;

      .step-title {
        font-size: 16px;
        font-weight: 600;
      }

      .step-tip {
        font-size: 12px;
        color: #909399;
      }
    }

    .upload-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      margin-bottom: 16px;

      .upload-item {
        :deep(.el-upload) {
          width: 100%;
        }
      }
    }

    .upload-actions {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .erp-checkbox {
      margin-bottom: 12px;
      width: 100%;
      :deep(.el-checkbox__label) {
        font-weight: 600;
        font-size: 14px;
      }
    }

    .erp-options {
      padding: 8px 12px;
      background: #fafafa;
      border-radius: 4px;
      border: 1px solid #f0f0f0;
    }

    .generate-status {
      margin-left: 12px;
      font-size: 13px;
      color: #909399;
    }

    .result-summary {
      .summary-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 12px;
        margin-top: 12px;

        .summary-item {
          display: flex;
          flex-direction: column;
          gap: 4px;
          padding: 12px;
          background: #f5f7fa;
          border-radius: 4px;

          .label {
            font-size: 12px;
            color: #909399;
          }

          .value {
            font-size: 18px;
            font-weight: 600;
            color: #303133;

            &.success { color: #67c23a; }
            &.danger { color: #f56c6c; }
          }
        }
      }
    }

    .erp-results {
      margin-top: 16px;

      .erp-result-list {
        margin-top: 8px;
        display: flex;
        flex-direction: column;
        gap: 6px;

        .erp-result-item {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          border-radius: 4px;
          font-size: 13px;

          &.success {
            background: #f0f9eb;
            color: #67c23a;
          }
          &.fail {
            background: #fef0f0;
            color: #f56c6c;
          }

          .icon-success, .icon-fail {
            font-size: 16px;
          }

          .erp-result-label {
            font-weight: 600;
            min-width: 80px;
          }

          .erp-result-msg {
            color: #606266;
          }
        }
      }
    }

    .charts-block {
      margin-top: 16px;

      .charts-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 16px;
        margin-top: 12px;

        .chart-item {
          .chart-label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #606266;
          }

          .chart-img {
            width: 100%;
            border: 1px solid #ebeef5;
            border-radius: 4px;
          }
        }
      }
    }

    .reports-block {
      margin-top: 16px;

      .report-list {
        margin-top: 12px;

        .report-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 10px 12px;
          border: 1px solid #ebeef5;
          border-radius: 4px;
          margin-bottom: 8px;

          &:hover {
            background: #f5f7fa;
          }

          .report-name {
            font-size: 14px;
            color: #303133;
          }

          .report-actions {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
    }
  }

  .preview-container {
    height: calc(100vh - 200px);

    .preview-iframe {
      width: 100%;
      height: 100%;
      border: none;
      border-radius: 4px;
    }
  }

  .form-tip {
    margin-left: 8px;
    font-size: 12px;
    color: #909399;
  }
}
</style>