<template>
  <div class="practice-scene-management-container">
    <div class="page-header">
      <h1 class="page-title">陪练场景库管理</h1>
      <el-button type="primary" @click="createScene">
        <el-icon class="el-icon--left"><Plus /></el-icon>
        新增场景
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section card">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="关键词">
          <el-input 
            v-model="filterForm.name" 
            placeholder="搜索场景名称或描述" 
            clearable 
            @input="handleRealTimeSearch"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="场景类型">
          <el-select 
            v-model="filterForm.type" 
            placeholder="全部类型" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="电话销售" value="phone" />
            <el-option label="面对面销售" value="face" />
            <el-option label="客户投诉" value="complaint" />
            <el-option label="售后服务" value="after-sales" />
            <el-option label="产品介绍" value="product-intro" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度等级">
          <el-select 
            v-model="filterForm.difficulty" 
            placeholder="全部难度" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="入门" value="beginner" />
            <el-option label="初级" value="junior" />
            <el-option label="中级" value="intermediate" />
            <el-option label="高级" value="senior" />
            <el-option label="专家" value="expert" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="filterForm.status" 
            placeholder="全部状态" 
            clearable
            @change="handleRealTimeSearch"
            style="width: 120px"
          >
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">
            <el-icon class="el-icon--left"><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 当前筛选条件显示 -->
      <div v-if="hasActiveFilters" class="filter-tags">
        <span class="filter-label">当前筛选：</span>
        <el-tag 
          v-if="filterForm.name" 
          closable 
          @close="clearName"
          type="primary"
        >
          关键词：{{ filterForm.name }}
        </el-tag>
        <el-tag 
          v-if="filterForm.type" 
          closable 
          @close="clearType"
          type="success"
        >
          类型：{{ getTypeText(filterForm.type) }}
        </el-tag>
        <el-tag 
          v-if="filterForm.difficulty" 
          closable 
          @close="clearDifficulty"
          type="warning"
        >
          难度：{{ getDifficultyText(filterForm.difficulty) }}
        </el-tag>
        <el-tag 
          v-if="filterForm.status" 
          closable 
          @close="clearStatus"
          type="info"
        >
          状态：{{ getStatusText(filterForm.status) }}
        </el-tag>
        <el-button 
          link 
          type="danger" 
          size="small" 
          @click="handleReset"
          class="clear-all-btn"
        >
          清空全部
        </el-button>
      </div>

      <!-- 搜索结果统计 -->
      <div class="search-result-info">
        <span class="result-count">
          共找到 <strong>{{ filteredScenes.length }}</strong> 个场景
          <span v-if="hasActiveFilters" class="filter-hint">（已筛选）</span>
        </span>
      </div>
    </div>

    <!-- 场景统计 -->
    <div class="stats-section">
      <div class="stat-card card" v-for="stat in sceneStats" :key="stat.label">
        <div class="stat-icon" :style="{ backgroundColor: stat.bgColor }">
          <el-icon :size="28" :color="stat.color">
            <component :is="stat.icon" />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-value">{{ stat.value }}</div>
          <div class="stat-label">{{ stat.label }}</div>
        </div>
      </div>
    </div>

    <!-- 场景列表 -->
    <div v-if="filteredScenes.length > 0" class="scene-list">
      <div class="scene-card card" v-for="scene in filteredScenes" :key="scene.id">
        <div class="scene-header">
          <div class="scene-title-section">
            <h3 class="scene-title">{{ scene.name }}</h3>
            <div class="scene-tags">
              <el-tag :type="getTypeTagType(scene.type)" size="small">
                {{ getTypeText(scene.type) }}
              </el-tag>
              <el-tag :type="getDifficultyTagType(scene.difficulty)" size="small">
                {{ getDifficultyText(scene.difficulty) }}
              </el-tag>
              <el-tag :type="scene.status === 'active' ? 'success' : 'info'" size="small">
                {{ scene.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </div>
          </div>
          <el-dropdown trigger="click">
            <el-button link>
              <el-icon><More /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="viewScene(scene)">
                  <el-icon><View /></el-icon>
                  查看详情
                </el-dropdown-item>
                <el-dropdown-item @click="editScene(scene)">
                  <el-icon><Edit /></el-icon>
                  编辑场景
                </el-dropdown-item>
                <el-dropdown-item @click="testScene(scene)">
                  <el-icon><Microphone /></el-icon>
                  测试场景
                </el-dropdown-item>
                <el-dropdown-item @click="copyScene(scene)">
                  <el-icon><CopyDocument /></el-icon>
                  复制场景
                </el-dropdown-item>
                <el-dropdown-item @click="toggleStatus(scene)">
                  <el-icon>
                    <CircleClose v-if="scene.status === 'active'" />
                    <CircleCheck v-else />
                  </el-icon>
                  {{ scene.status === 'active' ? '禁用场景' : '启用场景' }}
                </el-dropdown-item>
                <el-dropdown-item @click="deleteScene(scene)" divided>
                  <el-icon><Delete /></el-icon>
                  删除场景
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <div class="scene-content">
          <p class="scene-desc">{{ scene.description }}</p>
          
          <div class="scene-details">
            <h4>场景背景</h4>
            <p>{{ scene.background }}</p>
            
            <h4>AI角色设定</h4>
            <p>{{ scene.ai_role }}</p>
            
            <h4>学习目标</h4>
            <ul class="objective-list">
              <li v-for="(objective, index) in scene.objectives" :key="index">
                {{ objective }}
              </li>
            </ul>
          </div>

          <div class="scene-info">
            <div class="info-item">
              <el-icon><Clock /></el-icon>
              <span>建议时长：{{ scene.duration }}分钟</span>
            </div>
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>使用次数：{{ scene.usage_count }}</span>
            </div>
            <div class="info-item">
              <el-icon><Star /></el-icon>
              <span>平均评分：{{ scene.rating }}/5.0</span>
            </div>
          </div>

          <div class="scene-keywords">
            <h4>关键技能点</h4>
            <div class="keyword-tags">
              <el-tag v-for="keyword in scene.keywords" :key="keyword" size="small" type="info">
                {{ keyword }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="scene-footer">
          <span class="footer-text">创建时间：{{ scene.created_at }}</span>
          <span class="footer-text">最后更新：{{ scene.updated_at }}</span>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else class="empty-state">
      <el-empty 
        :description="hasActiveFilters ? '没有符合条件的场景' : '暂无场景数据'"
        :image-size="120"
      >
        <el-button v-if="hasActiveFilters" type="primary" @click="handleReset">
          清空筛选条件
        </el-button>
        <el-button v-else type="primary" @click="createScene">
          创建第一个场景
        </el-button>
      </el-empty>
    </div>

    <!-- 新增/编辑场景弹窗 -->
    <el-dialog
      v-model="sceneDialogVisible"
      :title="isEdit ? '编辑场景' : '新增场景'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="sceneForm" :rules="rules" label-width="120px">
        <el-form-item label="场景名称" prop="name">
          <el-input v-model="sceneForm.name" placeholder="请输入场景名称" maxlength="50" show-word-limit />
        </el-form-item>

        <el-form-item label="场景描述" prop="description">
          <el-input
            v-model="sceneForm.description"
            type="textarea"
            placeholder="请输入场景描述"
            :rows="2"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="场景类型" prop="type">
              <el-select v-model="sceneForm.type" placeholder="请选择场景类型" style="width: 100%">
                <el-option label="电话销售" value="phone" />
                <el-option label="面对面销售" value="face" />
                <el-option label="客户投诉" value="complaint" />
                <el-option label="售后服务" value="after-sales" />
                <el-option label="产品介绍" value="product-intro" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度等级" prop="difficulty">
              <el-select v-model="sceneForm.difficulty" placeholder="请选择难度等级" style="width: 100%">
                <el-option label="入门" value="beginner" />
                <el-option label="初级" value="junior" />
                <el-option label="中级" value="intermediate" />
                <el-option label="高级" value="senior" />
                <el-option label="专家" value="expert" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="场景背景" prop="background">
          <el-input
            v-model="sceneForm.background"
            type="textarea"
            placeholder="请描述场景背景信息"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="AI角色设定" prop="aiRole">
          <el-input
            v-model="sceneForm.aiRole"
            type="textarea"
            placeholder="请描述AI在此场景中扮演的角色和特点"
            :rows="3"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="学习目标" prop="objectives">
          <div class="objectives-editor">
            <div v-for="(_objective, index) in sceneForm.objectives" :key="index" class="objective-item">
              <el-input v-model="sceneForm.objectives[index]" placeholder="请输入学习目标" />
              <el-button 
                link 
                type="danger" 
                @click="removeObjective(index)"
                :disabled="sceneForm.objectives.length <= 1"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
            <el-button 
              link 
              type="primary" 
              @click="addObjective"
              :disabled="sceneForm.objectives.length >= 5"
            >
              <el-icon><Plus /></el-icon>
              添加学习目标
            </el-button>
          </div>
        </el-form-item>

        <el-form-item label="关键技能点" prop="keywords">
          <el-select
            v-model="sceneForm.keywords"
            multiple
            filterable
            allow-create
            placeholder="请输入或选择关键技能点"
            style="width: 100%"
          >
            <el-option label="沟通技巧" value="沟通技巧" />
            <el-option label="需求挖掘" value="需求挖掘" />
            <el-option label="异议处理" value="异议处理" />
            <el-option label="情绪管理" value="情绪管理" />
            <el-option label="成交技巧" value="成交技巧" />
            <el-option label="产品介绍" value="产品介绍" />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="建议时长" prop="duration">
              <el-input-number v-model="sceneForm.duration" :min="5" :max="60" />
              <span style="margin-left: 8px">分钟</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="sceneForm.status"
                active-value="active"
                inactive-value="inactive"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="评分标准" prop="scoringCriteria">
          <el-input
            v-model="sceneForm.scoringCriteria"
            type="textarea"
            placeholder="请描述此场景的评分标准"
            :rows="3"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="sceneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { 
  getPracticeScenes, 
  createPracticeScene, 
  updatePracticeScene, 
  deletePracticeScene,
  type PracticeScene,
  type CreateSceneRequest,
  type UpdateSceneRequest
} from '@/api/practiceScene'
import { 
  Refresh, 
  Plus, 
  More, 
  View, 
  Edit, 
  Microphone, 
  CopyDocument, 
  CircleClose, 
  CircleCheck, 
  Delete, 
  Clock, 
  User, 
  Star 
} from '@element-plus/icons-vue'

// 搜索筛选
const filterForm = reactive({
  name: '',
  type: '',
  difficulty: '',
  status: ''
})

// 弹窗相关
const sceneDialogVisible = ref(false)
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const isEdit = ref(false)

// 场景表单
const sceneForm = reactive({
  id: '',
  name: '',
  description: '',
  type: '',
  difficulty: '',
  background: '',
  aiRole: '',
  objectives: [''],
  keywords: [],
  duration: 10,
  status: 'active',
  scoringCriteria: ''
})

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入场景名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入场景描述', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择场景类型', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  background: [
    { required: true, message: '请描述场景背景', trigger: 'blur' }
  ],
  aiRole: [
    { required: true, message: '请描述AI角色设定', trigger: 'blur' }
  ],
  keywords: [
    { required: true, message: '请选择关键技能点', trigger: 'change', type: 'array' }
  ]
})

// 场景统计数据
const sceneStats = ref([
  {
    label: '场景总数',
    value: '45',
    icon: 'Microphone',
    color: '#667eea',
    bgColor: 'rgba(102, 126, 234, 0.1)'
  },
  {
    label: '电话销售',
    value: '12',
    icon: 'Phone',
    color: '#67c23a',
    bgColor: 'rgba(103, 194, 58, 0.1)'
  },
  {
    label: '面对面销售',
    value: '15',
    icon: 'User',
    color: '#e6a23c',
    bgColor: 'rgba(230, 162, 60, 0.1)'
  },
  {
    label: '客户投诉',
    value: '8',
    icon: 'Warning',
    color: '#f56c6c',
    bgColor: 'rgba(245, 108, 108, 0.1)'
  },
  {
    label: '售后服务',
    value: '10',
    icon: 'Service',
    color: '#409eff',
    bgColor: 'rgba(64, 158, 255, 0.1)'
  }
])

// 场景列表数据
const sceneList = ref<PracticeScene[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

/**
 * 加载场景列表
 */
const loadScenes = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      type: filterForm.type || undefined,
      difficulty: filterForm.difficulty || undefined,
      search: filterForm.name || undefined
    }
    console.log('🔍 请求参数:', params)
    
    const response = await getPracticeScenes(params)
    console.log('📦 响应数据:', response)
    
    if (response.code === 200 && response.data) {
      console.log('✅ 场景列表:', response.data.items)
      console.log('📊 场景总数:', response.data.total)
      sceneList.value = response.data.items
      total.value = response.data.total
      console.log('✅ sceneList.value 已更新:', sceneList.value.length, '条')
    } else {
      console.error('❌ 响应失败:', response)
      ElMessage.error(response.message || '加载场景列表失败')
    }
  } catch (error: any) {
    console.error('❌ 加载场景列表失败:', error)
    ElMessage.error(error.message || '加载场景列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 场景列表（后端已处理筛选，前端直接展示）
const filteredScenes = computed(() => {
  console.log('🔄 computed: filteredScenes 被调用, sceneList.value:', sceneList.value.length, '条')
  return sceneList.value
})

// 是否有活跃的筛选条件
const hasActiveFilters = computed(() => {
  return !!(filterForm.name || filterForm.type || filterForm.difficulty || filterForm.status)
})

/**
 * 实时搜索处理
 */
const handleRealTimeSearch = () => {
  currentPage.value = 1
  loadScenes()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  filterForm.name = ''
  filterForm.type = ''
  filterForm.difficulty = ''
  filterForm.status = ''
  currentPage.value = 1
  loadScenes()
  ElMessage.success('已重置所有筛选条件')
}

/**
 * 清除关键词筛选
 */
const clearName = () => {
  filterForm.name = ''
}

/**
 * 清除类型筛选
 */
const clearType = () => {
  filterForm.type = ''
}

/**
 * 清除难度筛选
 */
const clearDifficulty = () => {
  filterForm.difficulty = ''
}

/**
 * 清除状态筛选
 */
const clearStatus = () => {
  filterForm.status = ''
}

/**
 * 获取类型文本
 */
const getTypeText = (type: string) => {
  const map: Record<string, string> = {
    phone: '电话销售',
    face: '面对面销售',
    complaint: '客户投诉',
    'after-sales': '售后服务',
    'product-intro': '产品介绍'
  }
  return map[type] || '未知'
}

/**
 * 获取难度文本
 */
const getDifficultyText = (difficulty: string) => {
  const map: Record<string, string> = {
    beginner: '入门',
    junior: '初级',
    intermediate: '中级',
    senior: '高级',
    expert: '专家'
  }
  return map[difficulty] || '未知'
}

/**
 * 获取状态文本
 */
const getStatusText = (status: string) => {
  const map: Record<string, string> = {
    active: '启用',
    inactive: '禁用'
  }
  return map[status] || '未知'
}

/**
 * 新增场景
 */
const createScene = () => {
  isEdit.value = false
  resetForm()
  sceneDialogVisible.value = true
}

/**
 * 查看场景
 */
const viewScene = (scene: any) => {
  ElMessage.info('查看场景：' + scene.name)
}

/**
 * 编辑场景
 */
const editScene = (scene: any) => {
  isEdit.value = true
  // 填充表单数据
  Object.assign(sceneForm, {
    id: scene.id,
    name: scene.name,
    description: scene.description,
    type: scene.type,
    difficulty: scene.difficulty,
    background: scene.background,
    aiRole: scene.aiRole,
    objectives: [...scene.objectives],
    keywords: [...scene.keywords],
    duration: scene.duration,
    status: scene.status,
    scoringCriteria: scene.scoringCriteria || ''
  })
  sceneDialogVisible.value = true
}

/**
 * 测试场景
 */
const testScene = (scene: any) => {
  ElMessage.info('启动场景测试：' + scene.name)
}

/**
 * 复制场景
 */
const copyScene = (scene: any) => {
  ElMessageBox.confirm(
    '确定要复制场景"' + scene.name + '"吗？',
    '复制场景',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    ElMessage.success('场景复制成功')
  }).catch(() => {})
}

/**
 * 切换状态
 */
const toggleStatus = (scene: any) => {
  const action = scene.status === 'active' ? '禁用' : '启用'
  ElMessageBox.confirm(
    '确定要' + action + '场景"' + scene.name + '"吗？',
    action + '场景',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    scene.status = scene.status === 'active' ? 'inactive' : 'active'
    ElMessage.success('场景已' + action)
  }).catch(() => {})
}

/**
 * 删除场景
 */
const deleteScene = async (scene: PracticeScene) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除场景"${scene.name}"吗？删除后不可恢复。`,
      '删除场景',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deletePracticeScene(scene.id)
    if (response.code === 200) {
      ElMessage.success('场景已删除')
      loadScenes() // 刷新列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除场景失败:', error)
      ElMessage.error(error.message || '删除失败，请稍后重试')
    }
  }
}

/**
 * 添加学习目标
 */
const addObjective = () => {
  sceneForm.objectives.push('')
}

/**
 * 移除学习目标
 */
const removeObjective = (index: number) => {
  sceneForm.objectives.splice(index, 1)
}

/**
 * 重置表单
 */
const resetForm = () => {
  sceneForm.id = ''
  sceneForm.name = ''
  sceneForm.description = ''
  sceneForm.type = ''
  sceneForm.difficulty = ''
  sceneForm.background = ''
  sceneForm.aiRole = ''
  sceneForm.objectives = ['']
  sceneForm.keywords = []
  sceneForm.duration = 10
  sceneForm.status = 'active'
  sceneForm.scoringCriteria = ''
  formRef.value?.resetFields()
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      // 验证学习目标
      const validObjectives = sceneForm.objectives.filter(obj => obj.trim())
      if (validObjectives.length === 0) {
        ElMessage.error('请至少输入一个学习目标')
        return
      }
      
      submitLoading.value = true
      
      try {
        if (isEdit.value) {
          // 更新场景
          const updateData: UpdateSceneRequest = {
            name: sceneForm.name,
            description: sceneForm.description,
            type: sceneForm.type,
            difficulty: sceneForm.difficulty,
            status: sceneForm.status,
            background: sceneForm.background,
            ai_role: sceneForm.aiRole,
            objectives: validObjectives,
            keywords: sceneForm.keywords,
            duration: sceneForm.duration
          }
          const response = await updatePracticeScene(Number(sceneForm.id), updateData)
          if (response.code === 200) {
            ElMessage.success('场景编辑成功')
            sceneDialogVisible.value = false
            resetForm()
            loadScenes() // 刷新列表
          } else {
            ElMessage.error(response.message || '编辑失败')
          }
        } else {
          // 创建场景
          const createData: CreateSceneRequest = {
            name: sceneForm.name,
            description: sceneForm.description,
            type: sceneForm.type,
            difficulty: sceneForm.difficulty,
            status: sceneForm.status,
            background: sceneForm.background,
            ai_role: sceneForm.aiRole,
            objectives: validObjectives,
            keywords: sceneForm.keywords,
            duration: sceneForm.duration
          }
          const response = await createPracticeScene(createData)
          if (response.code === 200) {
            ElMessage.success('场景创建成功')
            sceneDialogVisible.value = false
            resetForm()
            loadScenes() // 刷新列表
          } else {
            ElMessage.error(response.message || '创建失败')
          }
        }
      } catch (error: any) {
        console.error('提交场景失败:', error)
        ElMessage.error(error.message || '操作失败，请稍后重试')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

/**
 * 获取类型标签类型
 */
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    phone: '',
    face: 'success',
    complaint: 'danger',
    'after-sales': 'warning',
    'product-intro': 'info'
  }
  return typeMap[type] || ''
}

/**
 * 获取难度标签类型
 */
const getDifficultyTagType = (difficulty: string) => {
  const difficultyMap: Record<string, string> = {
    beginner: 'success',
    junior: '',
    intermediate: 'warning',
    senior: 'danger',
    expert: 'danger'
  }
  return difficultyMap[difficulty] || ''
}

// 初始化加载数据
onMounted(() => {
  console.log('🚀 onMounted: 页面已挂载，开始加载场景列表')
  loadScenes()
})

</script>

<style lang="scss" scoped>
.practice-scene-management-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #333;
    }

    .el-button {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 20px;

    .filter-form {
      .el-form-item {
        margin-bottom: 0;
      }
    }

    .filter-tags {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      gap: 8px;

      .filter-label {
        color: #666;
        font-size: 14px;
        margin-right: 8px;
      }

      .clear-all-btn {
        margin-left: 8px;
      }
    }

    .search-result-info {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;

      .result-count {
        color: #666;
        font-size: 14px;

        strong {
          color: #409eff;
          font-weight: 600;
        }
      }

      .filter-hint {
        color: #e6a23c;
        font-size: 12px;
      }
    }
  }

  .empty-state {
    padding: 40px 20px;
    text-align: center;
  }

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

    .stat-card {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 20px;

      .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .stat-content {
        .stat-value {
          font-size: 24px;
          font-weight: 600;
          color: #333;
          margin-bottom: 4px;
        }

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

  .scene-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(500px, 1fr));
    gap: 24px;

    .scene-card {
      padding: 24px;

      .scene-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16px;

        .scene-title-section {
          flex: 1;

          .scene-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
          }

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

      .scene-content {
        .scene-desc {
          font-size: 14px;
          color: #666;
          line-height: 1.6;
          margin-bottom: 20px;
        }

        .scene-details {
          margin-bottom: 20px;

          h4 {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
            margin-top: 16px;

            &:first-child {
              margin-top: 0;
            }
          }

          p {
            font-size: 13px;
            color: #666;
            line-height: 1.6;
          }

          .objective-list {
            list-style: none;
            padding: 0;
            margin: 0;

            li {
              position: relative;
              padding-left: 20px;
              font-size: 13px;
              color: #666;
              line-height: 1.8;

              &::before {
                content: '•';
                position: absolute;
                left: 8px;
                color: #667eea;
              }
            }
          }
        }

        .scene-info {
          display: flex;
          gap: 24px;
          margin-bottom: 20px;
          padding: 16px;
          background: #f5f7fa;
          border-radius: 8px;

          .info-item {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 13px;
            color: #666;

            .el-icon {
              color: #909399;
            }
          }
        }

        .scene-keywords {
          h4 {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 12px;
          }

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

      .scene-footer {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
        padding-top: 16px;
        border-top: 1px solid #ebeef5;
        font-size: 12px;
        color: #909399;
      }
    }
  }

  .objectives-editor {
    width: 100%;

    .objective-item {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 12px;

      .el-input {
        flex: 1;
      }
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .practice-scene-management-container {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;

      .el-button {
        width: 100%;
      }
    }

    .filter-form {
      .el-form-item {
        display: block;
        margin-bottom: 16px !important;
      }
    }

    .stats-section {
      grid-template-columns: 1fr;
    }

    .scene-list {
      grid-template-columns: 1fr;
    }

    .scene-info {
      flex-direction: column;
      gap: 8px !important;
    }
  }
}
</style>
