<template>
  <div class="decomposition-template-page">
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">拆解模板管理</h1>
          <p class="page-desc">管理复杂问题的拆解模板，支持版本管理与生效标记。[AC-IDSMETA-22]</p>
        </div>
        <div class="header-actions">
          <el-select v-model="filterStatus" placeholder="按状态筛选" clearable style="width: 130px;">
            <el-option
              v-for="opt in DECOMPOSITION_STATUS_OPTIONS"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
          <el-select v-model="filterScene" placeholder="按场景筛选" clearable style="width: 140px;">
            <el-option
              v-for="opt in DECOMPOSITION_SCENE_OPTIONS"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新建模板
          </el-button>
        </div>
      </div>
    </div>

    <el-card shadow="hover" class="template-card" v-loading="loading">
      <el-table :data="templates" stripe style="width: 100%">
        <el-table-column prop="name" label="模板名称" min-width="180">
          <template #default="{ row }">
            <div class="template-name">
              <span class="name-text">{{ row.name }}</span>
              <el-tag v-if="row.is_latest_effective" type="success" size="small" class="effective-tag">
                最近生效
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="scene" label="场景" width="120">
          <template #default="{ row }">
            <el-tag size="small">{{ getSceneLabel(row.scene) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="current_version" label="版本" width="100">
          <template #default="{ row }">
            <span class="version-badge">v{{ row.current_version }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="effective_at" label="生效时间" width="180">
          <template #default="{ row }">
            <span v-if="row.effective_at">{{ formatDate(row.effective_at) }}</span>
            <span v-else class="no-date">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updated_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button
              v-if="row.status === 'draft'"
              type="success"
              link
              size="small"
              @click="handleActivate(row)"
            >
              <el-icon><Check /></el-icon>
              生效
            </el-button>
            <el-button
              v-if="row.status === 'active'"
              type="warning"
              link
              size="small"
              @click="handleArchive(row)"
            >
              <el-icon><FolderOpened /></el-icon>
              归档
            </el-button>
            <el-button type="info" link size="small" @click="handleViewDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑模板' : '新建模板'"
      width="850px"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场景" prop="scene">
              <el-select v-model="formData.scene" placeholder="请选择场景" style="width: 100%;">
                <el-option
                  v-for="opt in DECOMPOSITION_SCENE_OPTIONS"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述">
          <el-input v-model="formData.description" type="textarea" :rows="2" placeholder="请输入模板描述（可选）" />
        </el-form-item>

        <el-divider content-position="left">拆解步骤</el-divider>

        <div class="steps-editor">
          <div
            v-for="(step, index) in formData.steps"
            :key="step.step_id"
            class="step-item"
          >
            <div class="step-header">
              <span class="step-order">步骤 {{ index + 1 }}</span>
              <el-button type="danger" link size="small" @click="removeStep(index)">
                删除
              </el-button>
            </div>
            <el-form-item label="指令" required>
              <el-input
                v-model="step.instruction"
                type="textarea"
                :rows="2"
                placeholder="请输入该步骤的处理指令"
              />
            </el-form-item>
            <el-form-item label="期望输出">
              <el-input
                v-model="step.expected_output"
                placeholder="可选：描述该步骤期望的输出格式"
              />
            </el-form-item>
          </div>
          <el-button type="primary" plain @click="addStep" style="width: 100%; margin-top: 12px;">
            <el-icon><Plus /></el-icon>
            添加步骤
          </el-button>
        </div>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ isEdit ? '保存' : '创建' }}
        </el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="detailDrawer" title="模板详情" size="600px" destroy-on-close>
      <div v-if="currentTemplate" class="detail-content">
        <div class="detail-header">
          <h3>{{ currentTemplate.name }}</h3>
          <div class="detail-tags">
            <el-tag :type="getStatusTagType(currentTemplate.status)" size="small">
              {{ getStatusLabel(currentTemplate.status) }}
            </el-tag>
            <el-tag v-if="currentTemplate.is_latest_effective" type="success" size="small">
              最近生效
            </el-tag>
          </div>
        </div>

        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="场景">{{ getSceneLabel(currentTemplate.scene) }}</el-descriptions-item>
          <el-descriptions-item label="当前版本">v{{ currentTemplate.current_version }}</el-descriptions-item>
          <el-descriptions-item label="生效时间">
            {{ currentTemplate.effective_at ? formatDate(currentTemplate.effective_at) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentTemplate.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">
            {{ currentTemplate.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">版本历史</el-divider>

        <el-timeline>
          <el-timeline-item
            v-for="version in currentTemplate.versions"
            :key="version.version"
            :type="version.status === 'active' ? 'success' : 'info'"
            :timestamp="formatDate(version.created_at)"
            placement="top"
          >
            <div class="version-item">
              <div class="version-header">
                <span class="version-number">v{{ version.version }}</span>
                <el-tag :type="getStatusTagType(version.status)" size="small">
                  {{ getStatusLabel(version.status) }}
                </el-tag>
              </div>
              <div class="version-steps">
                <div v-for="(step, idx) in version.steps" :key="step.step_id" class="version-step">
                  <span class="step-no">{{ idx + 1 }}.</span>
                  <span class="step-instruction">{{ step.instruction }}</span>
                </div>
              </div>
              <el-button
                v-if="version.status === 'archived'"
                type="primary"
                link
                size="small"
                @click="handleRollback(version.version)"
              >
                回滚到此版本
              </el-button>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete, Check, FolderOpened, View } from '@element-plus/icons-vue'
import { decompositionTemplateApi } from '@/api/decomposition-template'
import { DECOMPOSITION_STATUS_OPTIONS, DECOMPOSITION_SCENE_OPTIONS } from '@/types/decomposition-template'
import type {
  DecompositionTemplate,
  DecompositionTemplateDetail,
  DecompositionTemplateCreate,
  DecompositionTemplateUpdate,
  DecompositionStatus
} from '@/types/decomposition-template'

const loading = ref(false)
const templates = ref<DecompositionTemplate[]>([])
const filterStatus = ref('')
const filterScene = ref('')
const dialogVisible = ref(false)
const detailDrawer = ref(false)
const isEdit = ref(false)
const submitting = ref(false)
const formRef = ref()
const currentTemplate = ref<DecompositionTemplateDetail | null>(null)
const currentEditId = ref('')

const generateStepId = () => `step_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

const formData = ref<DecompositionTemplateCreate>({
  name: '',
  scene: '',
  description: '',
  steps: [],
  metadata: {}
})

const formRules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  scene: [{ required: true, message: '请选择场景', trigger: 'change' }]
}

const getSceneLabel = (scene: string) => {
  const opt = DECOMPOSITION_SCENE_OPTIONS.find(o => o.value === scene)
  return opt?.label || scene
}

const getStatusLabel = (status: DecompositionStatus) => {
  const opt = DECOMPOSITION_STATUS_OPTIONS.find(o => o.value === status)
  return opt?.label || status
}

const getStatusTagType = (status: DecompositionStatus): '' | 'success' | 'warning' | 'danger' | 'info' => {
  const typeMap: Record<DecompositionStatus, '' | 'success' | 'warning' | 'danger' | 'info'> = {
    draft: 'info',
    active: 'success',
    archived: 'warning'
  }
  return typeMap[status] || 'info'
}

const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const loadTemplates = async () => {
  loading.value = true
  try {
    const res = await decompositionTemplateApi.list({
      status: filterStatus.value || undefined,
      scene: filterScene.value || undefined
    })
    templates.value = res.data || []
  } catch (error) {
    ElMessage.error('加载模板列表失败')
  } finally {
    loading.value = false
  }
}

const handleCreate = () => {
  isEdit.value = false
  currentEditId.value = ''
  formData.value = {
    name: '',
    scene: '',
    description: '',
    steps: [],
    metadata: {}
  }
  dialogVisible.value = true
}

const handleEdit = async (row: DecompositionTemplate) => {
  isEdit.value = true
  currentEditId.value = row.id
  try {
    const detail = await decompositionTemplateApi.get(row.id)
    formData.value = {
      name: detail.name,
      scene: detail.scene,
      description: detail.description || '',
      steps: detail.steps || [],
      metadata: detail.metadata || {}
    }
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('加载模板详情失败')
  }
}

const handleDelete = async (row: DecompositionTemplate) => {
  try {
    await ElMessageBox.confirm('确定要删除该模板吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await decompositionTemplateApi.delete(row.id)
    ElMessage.success('删除成功')
    loadTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleActivate = async (row: DecompositionTemplate) => {
  try {
    await ElMessageBox.confirm('确定要将该模板设为生效状态吗？', '确认生效', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })
    await decompositionTemplateApi.activate(row.id)
    ElMessage.success('已生效')
    loadTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleArchive = async (row: DecompositionTemplate) => {
  try {
    await ElMessageBox.confirm('确定要归档该模板吗？', '确认归档', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await decompositionTemplateApi.archive(row.id)
    ElMessage.success('已归档')
    loadTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const handleViewDetail = async (row: DecompositionTemplate) => {
  try {
    currentTemplate.value = await decompositionTemplateApi.get(row.id)
    detailDrawer.value = true
  } catch (error) {
    ElMessage.error('加载模板详情失败')
  }
}

const handleRollback = async (version: number) => {
  if (!currentTemplate.value) return
  try {
    await ElMessageBox.confirm(`确定要回滚到版本 v${version} 吗？`, '确认回滚', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await decompositionTemplateApi.rollback(currentTemplate.value.id, version)
    ElMessage.success('回滚成功')
    currentTemplate.value = await decompositionTemplateApi.get(currentTemplate.value.id)
    loadTemplates()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('回滚失败')
    }
  }
}

const addStep = () => {
  formData.value.steps.push({
    step_id: generateStepId(),
    step_no: formData.value.steps.length + 1,
    instruction: '',
    expected_output: '',
    dependencies: []
  })
}

const removeStep = (index: number) => {
  formData.value.steps.splice(index, 1)
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  if (formData.value.steps.length === 0) {
    ElMessage.warning('请至少添加一个步骤')
    return
  }

  for (let i = 0; i < formData.value.steps.length; i++) {
    if (!formData.value.steps[i].instruction?.trim()) {
      ElMessage.warning(`步骤 ${i + 1} 的指令不能为空`)
      return
    }
  }

  submitting.value = true
  try {
    const submitData = {
      ...formData.value,
      steps: formData.value.steps.map((step, index) => ({
        ...step,
        step_no: index + 1
      }))
    }

    if (isEdit.value) {
      const updateData: DecompositionTemplateUpdate = submitData
      await decompositionTemplateApi.update(currentEditId.value, updateData)
      ElMessage.success('保存成功')
    } else {
      await decompositionTemplateApi.create(submitData)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    loadTemplates()
  } catch (error) {
    ElMessage.error(isEdit.value ? '保存失败' : '创建失败')
  } finally {
    submitting.value = false
  }
}

watch([filterStatus, filterScene], () => {
  loadTemplates()
})

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

<style scoped>
.decomposition-template-page {
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  flex-wrap: wrap;
}

.title-section {
  flex: 1;
  min-width: 300px;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 700;
  color: var(--el-text-color-primary);
}

.page-desc {
  margin: 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

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

.template-card {
  border-radius: 8px;
}

.template-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.name-text {
  font-weight: 500;
}

.effective-tag {
  font-size: 10px;
}

.version-badge {
  display: inline-block;
  padding: 2px 8px;
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.no-date {
  color: var(--el-text-color-placeholder);
}

.steps-editor {
  max-height: 350px;
  overflow-y: auto;
  padding: 12px;
  background-color: var(--el-fill-color-lighter);
  border-radius: 6px;
}

.step-item {
  background-color: var(--el-bg-color);
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 12px;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.step-order {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.detail-content {
  padding: 0 16px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.detail-header h3 {
  margin: 0;
  font-size: 18px;
}

.detail-tags {
  display: flex;
  gap: 8px;
}

.version-item {
  padding: 8px 0;
}

.version-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.version-number {
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.version-steps {
  margin-bottom: 8px;
  padding-left: 12px;
}

.version-step {
  font-size: 13px;
  color: var(--el-text-color-regular);
  margin-bottom: 4px;
}

.step-no {
  color: var(--el-text-color-secondary);
  margin-right: 4px;
}

.step-instruction {
  word-break: break-all;
}
</style>
