<!--培训课程设置-->
<template>
  <div class="app-container">
    <!-- 课程设置模版 -->
    <div class="template-section">
      <div class="template-card knowledge-card">
        <div class="card-header">
          <el-icon><Reading /></el-icon>
          <span class="card-title">知识培训模版</span>
        </div>
        <div class="card-structure">理论课件 + 法规文档 + 考核题库</div>
        <div class="card-content-list">
          <div class="content-item" v-for="item in knowledgeExamples" :key="item">
            <span class="dot knowledge-dot"></span>{{ item }}
          </div>
        </div>
        <div class="card-footer">
          预设课程：应急法规知识库 | 个人防护理论
        </div>
      </div>
      <div class="template-card scenario-card">
        <div class="card-header">
          <el-icon><VideoPlay /></el-icon>
          <span class="card-title">情景培训模版</span>
        </div>
        <div class="card-structure">情景脚本 + 角色扮演 + 仿真推演</div>
        <div class="card-content-list">
          <div class="content-item" v-for="item in scenarioExamples" :key="item">
            <span class="dot scenario-dot"></span>{{ item }}
          </div>
        </div>
        <div class="card-footer">
          预设课程：实战化情景演练 | 无脚本应急响应
        </div>
      </div>
    </div>

    <!-- 搜索区 -->
    <el-form :model="queryParams" :inline="true" class="search-form">
      <el-form-item>
        <el-input v-model="queryParams.keyword" placeholder="按课程名称/培训类型查询" clearable style="width: 260px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
      <el-form-item style="float: right">
        <el-button type="success" @click="handleAdd">新增课程</el-button>
        <el-button type="primary" @click="handleImport">导入课程表</el-button>
        <el-button type="primary" @click="handleExport">导出课程表</el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <el-table :data="filteredList" border stripe style="width: 100%">
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column prop="name" label="课程名称" min-width="180" show-overflow-tooltip />
      <el-table-column label="培训方式" width="130" align="center">
        <template #default="{ row }">
          <span class="method-tag" :class="row.method === '知识培训' ? 'method-knowledge' : 'method-scenario'">
            <el-icon v-if="row.method === '知识培训'"><Reading /></el-icon>
            <el-icon v-else><VideoPlay /></el-icon>
            {{ row.method }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="课程内容（知识/情景模拟）" min-width="280" show-overflow-tooltip />
      <el-table-column label="计划周期" width="200" align="center">
        <template #default="{ row }">
          <span v-if="row.startDate">{{ row.startDate }} ~ {{ row.endDate }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="完成情况" width="110" align="center">
        <template #default="{ row }">
          <span v-if="row.completion === '已完成'" class="status-completed">已完成</span>
          <span v-else-if="row.completion === '进行中'" class="status-ongoing">进行中</span>
          <span v-else-if="row.completion === '未开始'" class="status-notstarted">未开始</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)"><el-icon><Edit /></el-icon></el-button>
          <el-button link type="danger" @click="handleDeleteApi(row)"><el-icon><Delete /></el-icon></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/修改弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="560px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="所属系统" prop="category">
          <el-select v-model="form.category" placeholder="请选择" style="width: 100%">
            <el-option label="燃气" value="燃气" />
            <el-option label="排水" value="排水" />
            <el-option label="供水" value="供水" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训方式" prop="method">
          <el-select v-model="form.method" placeholder="请选择培训方式" style="width: 100%">
            <el-option label="知识培训" value="知识培训" />
            <el-option label="情景培训" value="情景培训" />
          </el-select>
        </el-form-item>
        <el-form-item label="课程内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="3"
            :placeholder="contentPlaceholder"
          />
        </el-form-item>
        <el-form-item label="计划周期" prop="dateRange">
          <el-date-picker
            v-model="form.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitApi">课程提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Reading, VideoPlay, Edit, Delete } from '@element-plus/icons-vue'
import { getCourseList, saveCourse, updateCourse, deleteCourse } from '@/api/pipeNetwork/basic'

// ---------- 模版示例数据 ----------
const knowledgeExamples = [
  '危化品事故应急原则与处置规范',
  '应急指挥体系标准化课程',
  '新《安全生产法》深度解读'
]
const scenarioExamples = [
  '船舶火灾应急处置情景模拟（指挥舱/现场联动）',
  '海上溢油事故跨国协作桌面推演',
  '突发风暴救援VR情景模拟'
]

// ---------- 查询 ----------
const queryParams = ref({ keyword: '' })

// ---------- Mock 数据 ----------
let idCounter = 5
const tableData = ref([
  {
    id: 1,
    name: '应急指挥体系知识培训',
    method: '知识培训',
    content: '知识内容: 应急指挥架构、岗位职责、信息报送规范，含线上考核题库。',
    startDate: '2025-05-10',
    endDate: '2025-05-12',
    completion: '已完成',
    remark: ''
  },
  {
    id: 2,
    name: '危化品泄漏情景模拟演练',
    method: '情景培训',
    content: '情景模拟: 设定化工厂储罐泄漏，角色扮演+现场处置决策+事后复盘。',
    startDate: '2025-05-18',
    endDate: '2025-05-20',
    completion: '进行中',
    remark: ''
  },
  {
    id: 3,
    name: '水域救援知识课程',
    method: '知识培训',
    content: '知识内容: 救援设备使用原理、水流分析基础、急救医学常识，附考试。',
    startDate: '2025-05-25',
    endDate: '2025-05-25',
    completion: '未开始',
    remark: ''
  },
  {
    id: 4,
    name: '地震救援情景模拟课程',
    method: '情景培训',
    content: '情景模拟: 设定地震灾害场景，救援队伍协同作战、人员搜救与医疗救治。',
    startDate: '2025-06-10',
    endDate: '2025-06-12',
    completion: '未开始',
    remark: ''
  },
  {
    id: 5,
    name: '消防器材操作知识培训',
    method: '知识培训',
    content: '知识内容: 各类消防器材识别、使用方法、维护保养规范，实操考核。',
    startDate: '2025-06-15',
    endDate: '2025-06-16',
    completion: '未开始',
    remark: ''
  }
])

// ---------- 过滤 ----------
const filteredList = computed(() => {
  if (!queryParams.value.keyword) return tableData.value
  const kw = queryParams.value.keyword.toLowerCase()
  return tableData.value.filter(
    i => i.name.toLowerCase().includes(kw) || i.method.toLowerCase().includes(kw)
  )
})

const handleSearch = () => { loadData() }
const handleReset = () => { queryParams.value.keyword = ''; loadData() }
async function loadData() { try { const res = await getCourseList({ pageSize: 50 }); const rows = res.data?.records || []; if (rows.length) tableData.value = rows } catch (e) {} }
onMounted(() => { loadData() })
const handleSubmitApi = async () => {
  const v = await formRef.value?.validate().catch(() => false); if (!v) return
  const data = { name: form.value.name, category: form.value.category, method: form.value.method, content: form.value.content, completion: form.value.completion, remark: form.value.remark, id: form.value.id }
  if (form.value.dateRange?.length === 2) { data.startDate = form.value.dateRange[0]; data.endDate = form.value.dateRange[1] }
  try { data.id ? await updateCourse(data) : await saveCourse(data); dialogVisible.value = false; ElMessage.success('保存成功'); loadData() } catch (e) { ElMessage.error('保存失败') }
}
const handleDeleteApi = (row) => { ElMessageBox.confirm('确认删除?', '提示', { type: 'warning' }).then(async () => { await deleteCourse(row.id); ElMessage.success('删除成功'); loadData() }).catch(() => {}) }

// ---------- 弹窗 ----------
const dialogVisible = ref(false)
const dialogTitle = ref('新增课程')
const formRef = ref(null)

const defaultForm = () => ({
  id: null,
  name: '',
  category: '燃气',
  method: '知识培训',
  content: '',
  dateRange: null,
  completion: '未开始',
  remark: ''
})

const form = ref(defaultForm())

const contentPlaceholder = computed(() => {
  return form.value.method === '知识培训'
    ? '知识培训内容：基础理论、法律法规、考核标准等'
    : '情景模拟培训内容：情景脚本、角色扮演、仿真推演等'
})

const formRules = {
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  method: [{ required: true, message: '请选择培训方式', trigger: 'change' }]
}

const handleAdd = () => {
  form.value = defaultForm()
  dialogTitle.value = '新增课程'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  form.value = {
    ...row,
    dateRange: row.startDate ? [row.startDate, row.endDate] : null
  }
  dialogTitle.value = '修改课程'
  dialogVisible.value = true
}

const handleSubmit = () => {
  formRef.value?.validate((valid) => {
    if (!valid) return
    const data = { ...form.value }
    if (data.dateRange && data.dateRange.length === 2) {
      data.startDate = data.dateRange[0]
      data.endDate = data.dateRange[1]
    } else {
      data.startDate = ''
      data.endDate = ''
    }
    delete data.dateRange

    if (data.id) {
      const idx = tableData.value.findIndex(i => i.id === data.id)
      if (idx !== -1) tableData.value[idx] = { ...data }
    } else {
      data.id = ++idCounter
      tableData.value.unshift({ ...data })
    }
    dialogVisible.value = false
    ElMessage.success('保存成功')
  })
}

// ---------- 删除 ----------
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该课程?', '提示', { type: 'warning' }).then(() => {
    tableData.value = tableData.value.filter(i => i.id !== row.id)
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// ---------- 导入/导出 ----------
const handleImport = () => { ElMessage.success('导入课程表（Mock）') }
const handleExport = () => { ElMessage.success('导出课程表（Mock）') }
</script>

<style scoped lang="scss">
.template-section {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.template-card {
  flex: 1;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  background: #fafafa;

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

    .card-title {
      font-weight: bold;
      font-size: 15px;
      color: #303133;
    }

    .el-icon {
      font-size: 18px;
    }
  }

  .card-structure {
    font-size: 13px;
    color: #909399;
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 1px dashed #dcdfe6;
  }

  .card-content-list {
    margin-bottom: 10px;

    .content-item {
      display: flex;
      align-items: flex-start;
      gap: 8px;
      font-size: 13px;
      color: #606266;
      line-height: 1.6;
      margin-bottom: 4px;

      .dot {
        display: inline-block;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        margin-top: 7px;
        flex-shrink: 0;

        &.knowledge-dot { background: #e6a23c; }
        &.scenario-dot { background: #409eff; }
      }
    }
  }

  .card-footer {
    font-size: 12px;
    color: #409eff;
    padding-top: 8px;
    border-top: 1px dashed #dcdfe6;
  }
}

.knowledge-card {
  .el-icon { color: #e6a23c; }
}

.scenario-card {
  .el-icon { color: #409eff; }
}

.search-form {
  margin-bottom: 12px;
  :deep(.el-form-item) {
    margin-bottom: 8px;
  }
}

.method-tag {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 13px;

  &.method-knowledge {
    color: #e6a23c;
  }

  &.method-scenario {
    color: #409eff;
  }
}

.status-completed {
  color: #67c23a;
  font-weight: bold;
}

.status-ongoing {
  color: #e6a23c;
  font-weight: bold;
}

.status-notstarted {
  color: #f56c6c;
  font-weight: bold;
}
</style>
