<!--
  组件名称：TemplateConfig.vue
  组件描述：功能测试报告模板配置管理页面，支持多模板的增删改、默认模板设置

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

<template>
  <div class="template-config-page">
    <!-- 左侧：模板列表 -->
    <div class="template-sidebar">
      <el-card shadow="never" class="list-card">
        <template #header>
          <div class="card-header">
            <span>模板列表</span>
            <el-button type="primary" size="small" @click="handleCreate">
              <el-icon><Plus /></el-icon>
              新建模板
            </el-button>
          </div>
        </template>

        <div v-if="templates.length === 0" class="empty-tips">
          <el-empty description="暂无模板，请新建" />
        </div>

        <div v-else class="template-list">
          <div
            v-for="tpl in templates"
            :key="tpl.id"
            class="template-item"
            :class="{ active: selectedId === tpl.id }"
            @click="selectTemplate(tpl.id)"
          >
            <div class="template-left">
              <div class="template-info">
                <span class="template-name">{{ tpl.name }}</span>
                <el-tag v-if="tpl.is_default" size="small" type="success" class="default-tag">默认</el-tag>
              </div>
              <div v-if="tpl.description" class="template-desc" :title="tpl.description">{{ tpl.description }}</div>
            </div>
            <div class="template-actions">
              <el-tooltip content="设为默认" placement="top">
                <el-button
                  v-if="!tpl.is_default"
                  size="small"
                  circle
                  text
                  @click.stop="handleSetDefault(tpl)"
                >
                  <el-icon><Star /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="复制模板" placement="top">
                <el-button
                  size="small"
                  circle
                  text
                  @click.stop="handleDuplicate(tpl)"
                >
                  <el-icon><CopyDocument /></el-icon>
                </el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  size="small"
                  circle
                  text
                  type="danger"
                  @click.stop="handleDelete(tpl)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 右侧：配置表单 -->
    <div class="template-form">
      <template v-if="selectedId">
        <el-card shadow="never" class="form-card">
          <template #header>
            <div class="card-header">
              <span>编辑模板</span>
              <el-button type="primary" :loading="saving" @click="handleSave">
                {{ saving ? '保存中...' : '保存模板' }}
              </el-button>
            </div>
          </template>

          <el-form label-width="130px" label-position="right">
            <!-- ===== 基本信息 ===== -->
            <el-divider content-position="left">基本信息</el-divider>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="模板名称">
                  <el-input v-model="editForm.name" placeholder="请输入模板名称" maxlength="100" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="设为默认">
                  <el-switch v-model="editForm.is_default" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="18">
                <el-form-item label="模板描述">
                  <el-input v-model="editForm.description" type="textarea" :rows="2" maxlength="200" show-word-limit placeholder="模板用途说明（可选）" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- ===== 报告章节开关 ===== -->
            <el-divider content-position="left">报告章节开关</el-divider>
            <el-row :gutter="20">
              <el-col v-for="item in chapterOptions" :key="item.key" :span="6">
                <el-form-item :label="item.label" label-width="100px">
                  <el-switch v-model="(editForm.config.chapters as any)[item.key]" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- ===== Word 样式 ===== -->
            <el-divider content-position="left">Word 样式</el-divider>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="字体名称">
                  <el-input v-model="editForm.config.word_style.font_name" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="字号">
                  <el-input-number v-model="editForm.config.word_style.font_size" :min="8" :max="72" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标题颜色">
                  <el-color-picker v-model="editForm.config.word_style.title_color" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="首行缩进">
                  <el-input-number v-model="editForm.config.word_style.paragraph_first_line_indent" :min="0" :max="4" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="一级标题字号">
                  <el-input-number v-model="editForm.config.word_style.title_level_1_size" :min="8" :max="72" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="二级标题字号">
                  <el-input-number v-model="editForm.config.word_style.title_level_2_size" :min="8" :max="72" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="三级标题字号">
                  <el-input-number v-model="editForm.config.word_style.title_level_3_size" :min="8" :max="72" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="四级标题字号">
                  <el-input-number v-model="editForm.config.word_style.title_level_4_size" :min="8" :max="72" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- ===== 图表样式 ===== -->
            <el-divider content-position="left">图表样式</el-divider>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="DPI">
                  <el-input-number v-model="editForm.config.chart_style.dpi" :min="72" :max="600" :step="50" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="图表宽度">
                  <el-input-number v-model="editForm.config.chart_style.figure_width" :min="4" :max="30" :step="0.5" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="图表高度">
                  <el-input-number v-model="editForm.config.chart_style.figure_height" :min="3" :max="20" :step="0.5" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="中文字体">
                  <el-input v-model="editForm.config.chart_style.chinese_font" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-divider content-position="left">图表颜色配置</el-divider>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="通过">
                  <el-color-picker v-model="editForm.config.chart_style.colors.pass" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="失败">
                  <el-color-picker v-model="editForm.config.chart_style.colors.fail" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="未验证">
                  <el-color-picker v-model="editForm.config.chart_style.colors.unverified" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="未开发">
                  <el-color-picker v-model="editForm.config.chart_style.colors.undeveloped" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="BUG-严重">
                  <el-color-picker v-model="editForm.config.chart_style.colors.bug_1" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="BUG-一般">
                  <el-color-picker v-model="editForm.config.chart_style.colors.bug_2" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="BUG-轻微">
                  <el-color-picker v-model="editForm.config.chart_style.colors.bug_3" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="BUG-建议">
                  <el-color-picker v-model="editForm.config.chart_style.colors.bug_4" />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- ===== 报告默认值 ===== -->
            <el-divider content-position="left">报告默认值</el-divider>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="测试负责人">
                  <el-input v-model="editForm.config.defaults.test_lead" placeholder="未填写" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="测试人员">
                  <el-input v-model="editForm.config.defaults.tester" placeholder="未填写" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="测试环境">
                  <el-input v-model="editForm.config.defaults.test_env" placeholder="未填写" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="系统版本">
                  <el-input v-model="editForm.config.defaults.system_version" placeholder="未填写" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="服务器地址">
                  <el-input v-model="editForm.config.defaults.server_address" placeholder="未填写" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="部署环境">
                  <el-input v-model="editForm.config.defaults.deployment_env" placeholder="未填写" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-divider />
            <el-form-item>
              <el-button type="primary" size="large" :loading="saving" @click="handleSave">
                {{ saving ? '保存中...' : '保存模板' }}
              </el-button>
              <el-button size="large" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </template>

      <template v-else>
        <el-card shadow="never">
          <el-empty description="请从左侧选择一个模板进行编辑" />
        </el-card>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * 功能测试报告模板配置管理页面
 *
 * 功能：
 * 1. 左侧模板列表，支持新建、删除、设为默认
 * 2. 右侧配置表单，支持章节开关、Word样式、图表样式、默认值配置
 */

import { reactive, ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Star, CopyDocument } from '@element-plus/icons-vue'
import {
  reportTemplateApi,
  type ReportTemplateListItem,
  type ReportTemplateConfig,
  type ReportTemplateResponse,
} from '@/api/reportTemplate'

// ==================== 类型定义 ====================

interface EditForm {
  name: string
  description: string
  is_default: boolean
  config: ReportTemplateConfig
}

// ==================== 章节选项 ====================

const chapterOptions: { key: keyof ReportTemplateConfig['chapters']; label: string }[] = [
  { key: 'report_basic_info', label: '报告基本信息' },
  { key: 'execution_summary', label: '执行概况' },
  { key: 'test_scope', label: '测试范围' },
  { key: 'case_details', label: '用例详情' },
  { key: 'bug_list', label: 'BUG列表' },
  { key: 'chart_analysis', label: '图表分析' },
  { key: 'execution_records', label: '执行记录' },
  { key: 'attachments', label: '测试附件' },
  { key: 'risk_assessment', label: '风险评估' },
  { key: 'appendix', label: '附录' },
]

// ==================== 工具函数 ====================

/** 创建默认配置对象 */
function createDefaultConfig(): ReportTemplateConfig {
  return {
    chapters: {
      report_basic_info: true,
      execution_summary: true,
      test_scope: true,
      case_details: true,
      bug_list: true,
      chart_analysis: true,
      execution_records: true,
      attachments: true,
      risk_assessment: true,
      appendix: true,
    },
    defaults: {
      test_lead: '未填写',
      tester: '未填写',
      test_env: '未填写',
      system_version: '未填写',
      server_address: '未填写',
      deployment_env: '未填写',
    },
    word_style: {
      font_name: '宋体',
      font_size: 11,
      title_level_1_size: 21,
      title_level_2_size: 19,
      title_level_3_size: 17,
      title_level_4_size: 15,
      paragraph_first_line_indent: 2,
      title_color: '#000000',
    },
    chart_style: {
      dpi: 300,
      figure_width: 10,
      figure_height: 6,
      chinese_font: 'Microsoft YaHei',
      colors: {
        pass: '#04AA6D',
        fail: '#bb4069',
        unverified: '#f0c040',
        undeveloped: '#dcbdbd',
        bug_1: '#d32f2f',
        bug_2: '#f57c00',
        bug_3: '#fbc02d',
        bug_4: '#388e3c',
      },
    },
  }
}

/** 深拷贝对象 */
function deepClone<T>(obj: T): T {
  return JSON.parse(JSON.stringify(obj))
}

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

/** 模板列表 */
const templates = ref<ReportTemplateListItem[]>([])

/** 当前选中的模板 ID */
const selectedId = ref<number | null>(null)

/** 保存中 */
const saving = ref(false)

/** 编辑表单数据 */
const editForm = reactive<EditForm>({
  name: '',
  description: '',
  is_default: false,
  config: createDefaultConfig(),
})

/** 原始快照（用于重置） */
let originalSnapshot = ''

// ==================== 方法 ====================

/** 加载模板列表 */
async function loadTemplates() {
  try {
    templates.value = await reportTemplateApi.list()
    if (templates.value.length > 0 && !selectedId.value) {
      selectedId.value = templates.value[0].id
      await loadTemplateDetail(selectedId.value)
    }
  } catch (err: any) {
    ElMessage.error('加载模板列表失败：' + (err?.message || '未知错误'))
  }
}

/** 加载单个模板详情 */
async function loadTemplateDetail(id: number) {
  try {
    const detail: ReportTemplateResponse = await reportTemplateApi.get(id)
    editForm.name = detail.name
    editForm.description = detail.description || ''
    editForm.is_default = detail.is_default
    // 合并配置，确保所有字段存在
    editForm.config = deepClone(mergeConfig(detail.config))
    originalSnapshot = JSON.stringify(deepClone(editForm))
  } catch (err: any) {
    ElMessage.error('加载模板详情失败：' + (err?.message || '未知错误'))
  }
}

/** 合并配置，补齐缺失字段 */
function mergeConfig(config: ReportTemplateConfig): ReportTemplateConfig {
  const defaults = createDefaultConfig()
  const result = deepClone(defaults)

  if (config) {
    // 合并 chapters
    if (config.chapters) {
      Object.assign(result.chapters!, config.chapters)
    }
    // 合并 defaults
    if (config.defaults) {
      Object.assign(result.defaults!, config.defaults)
    }
    // 合并 word_style
    if (config.word_style) {
      Object.assign(result.word_style!, config.word_style)
    }
    // 合并 chart_style
    if (config.chart_style) {
      if (config.chart_style.colors) {
        Object.assign(result.chart_style!.colors!, config.chart_style.colors)
      }
      Object.assign(result.chart_style!, { ...config.chart_style, colors: result.chart_style!.colors })
    }
  }

  return result
}

/** 选中模板 */
async function selectTemplate(id: number) {
  if (selectedId.value === id) return
  selectedId.value = id
  await loadTemplateDetail(id)
}

/** 新建模板 */
async function handleCreate() {
  try {
    await ElMessageBox.prompt('请输入模板名称', '新建模板', {
      inputPlaceholder: '模板名称',
      inputPattern: /\S+/,
      inputErrorMessage: '模板名称不能为空',
    }).then(async ({ value }) => {
      const newConfig = createDefaultConfig()
      const result = await reportTemplateApi.create({
        name: value,
        config: newConfig,
      })
      ElMessage.success('模板创建成功')
      await loadTemplates()
      // 选中新建的模板
      selectedId.value = result.id
      await loadTemplateDetail(result.id)
    })
  } catch (err: any) {
    if (err !== 'cancel') {
      ElMessage.error('创建模板失败：' + (err?.message || '未知错误'))
    }
  }
}

/** 保存模板 */
async function handleSave() {
  if (!editForm.name.trim()) {
    ElMessage.warning('请输入模板名称')
    return
  }
  if (!selectedId.value) return

  saving.value = true
  try {
    await reportTemplateApi.update(selectedId.value, {
      name: editForm.name,
      description: editForm.description,
      is_default: editForm.is_default,
      config: editForm.config,
    })
    ElMessage.success('模板保存成功')
    originalSnapshot = JSON.stringify(deepClone(editForm))
    await loadTemplates()
  } catch (err: any) {
    ElMessage.error('保存模板失败：' + (err?.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

/** 设为默认 */
async function handleSetDefault(tpl: ReportTemplateListItem) {
  try {
    await reportTemplateApi.setDefault(tpl.id)
    ElMessage.success(`已将「${tpl.name}」设为默认模板`)
    await loadTemplates()
    // 刷新当前选中模板的详情
    if (selectedId.value) {
      await loadTemplateDetail(selectedId.value)
    }
  } catch (err: any) {
    ElMessage.error('设为默认失败：' + (err?.message || '未知错误'))
  }
}

/** 复制模板 */
async function handleDuplicate(tpl: ReportTemplateListItem) {
  try {
    const result = await reportTemplateApi.duplicate(tpl.id)
    ElMessage.success(`已复制模板「${result.name}」`)
    await loadTemplates()
    selectedId.value = result.id
    await loadTemplateDetail(result.id)
  } catch (err: any) {
    ElMessage.error('复制模板失败：' + (err?.message || '未知错误'))
  }
}

/** 删除模板 */
async function handleDelete(tpl: ReportTemplateListItem) {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板「${tpl.name}」吗？`,
      '删除确认',
      { confirmButtonText: '确认删除', cancelButtonText: '取消', type: 'warning' }
    )
    await reportTemplateApi.delete(tpl.id)
    ElMessage.success('模板已删除')
    await loadTemplates()
    // 如果删除的是当前选中的模板，切换到第一个
    if (selectedId.value === tpl.id) {
      if (templates.value.length > 0) {
        selectedId.value = templates.value[0].id
        await loadTemplateDetail(selectedId.value)
      } else {
        selectedId.value = null
      }
    }
  } catch (err: any) {
    if (err !== 'cancel') {
      ElMessage.error('删除模板失败：' + (err?.message || '未知错误'))
    }
  }
}

/** 重置表单 */
function handleReset() {
  if (!originalSnapshot) return
  const snapshot = JSON.parse(originalSnapshot)
  editForm.name = snapshot.name
  editForm.description = snapshot.description
  editForm.is_default = snapshot.is_default
  editForm.config = snapshot.config
  ElMessage.success('已重置到上次保存状态')
}

// ==================== 监听：选中变化时加载详情 ====================

watch(selectedId, (newId) => {
  if (newId) {
    loadTemplateDetail(newId)
  }
})

// ==================== 生命周期 ====================

onMounted(() => {
  loadTemplates()
})
</script>

<style scoped>
.template-config-page {
  display: flex;
  gap: 20px;
  height: 100%;
  min-height: calc(100vh - 120px);
}

/* ===== 左侧模板列表 ===== */
.template-sidebar {
  width: 280px;
  flex-shrink: 0;
}

.list-card {
  height: 100%;
}

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

.empty-tips {
  padding: 40px 0;
}

.template-list {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.template-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.2s;
  border: 1px solid transparent;
}

.template-item:hover {
  background: #f5f7fa;
}

.template-item.active {
  background: #ecf5ff;
  border-color: #409eff;
}

.template-left {
  display: flex;
  flex-direction: column;
  gap: 2px;
  flex: 1;
  min-width: 0;
}

.template-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.template-name {
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.default-tag {
  flex-shrink: 0;
}

.template-actions {
  display: flex;
  align-items: center;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.template-item:hover .template-actions {
  opacity: 1;
}

/* ===== 右侧配置表单 ===== */
.template-form {
  flex: 1;
  min-width: 0;
  overflow: auto;
}

.form-card {
  min-height: 100%;
}
</style>