<!--模拟演练管理-->
<template>
  <div class="sim-wrap">
  <div class="app-container">
    <div class="sim-layout">
      <!-- ===== 左列 ===== -->
      <div class="col-left">
        <!-- 演练项目设置 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><Folder /></el-icon> 演练项目设置</span>
            <el-button type="primary" size="small" @click="handleAddProject">新增</el-button>
          </div>
          <div class="panel-body">
            <div class="project-item" v-for="item in projects" :key="item.id" :class="{ selected: activeProjectId === item.id }" @click="selectProject(item)">
              <div class="project-info">
                <div class="project-name">{{ item.name }}</div>
                <div class="project-date">{{ item.date }}</div>
              </div>
              <div class="project-actions">
                <el-button link type="primary" @click="handleEditProject(item)"><el-icon><Edit /></el-icon></el-button>
                <el-button link type="danger" @click="handleDeleteProject(item)"><el-icon><Delete /></el-icon></el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 场景设置 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><PictureFilled /></el-icon> 场景设置</span>
            <el-button type="primary" size="small" @click="handleEditScene">编辑</el-button>
          </div>
          <div class="panel-body">
            <div class="scene-section">
              <div class="scene-label">当前场景元素：</div>
              <div class="tag-list">
                <el-tag v-for="tag in currentSceneTags" :key="tag" size="small" closable @close="removeSceneTag(tag)">{{ tag }}</el-tag>
              </div>
            </div>
            <div class="scene-section">
              <div class="scene-label">场景元素库：</div>
              <div class="tag-list">
                <el-tag v-for="tag in sceneLibrary" :key="tag" size="small" type="info" class="clickable-tag" @click="addSceneTag(tag)">{{ tag }}</el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 搜索 + 统计 -->
        <div class="panel">
          <div class="search-bar">
            <el-input v-model="projectSearch" placeholder="查询项目名称..." size="small" style="width: 160px" />
            <el-button type="primary" size="small" @click="handleSearchProject">查询</el-button>
          </div>
          <div class="stat-line">项目总数：{{ projects.length }}</div>
        </div>
      </div>

      <!-- ===== 中列 ===== -->
      <div class="col-center">
        <!-- 事件设置 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><Warning /></el-icon> 事件设置（突发事件制作）</span>
            <el-button type="primary" size="small" @click="handleAddEvent">新增事件</el-button>
          </div>
          <div class="panel-body">
            <div class="event-card" v-for="evt in events" :key="evt.id">
              <div class="event-info">
                <div class="event-name">
                  <el-icon style="color: #e6a23c"><Warning /></el-icon>
                  {{ evt.name }}
                </div>
                <div class="event-desc">{{ evt.desc }}</div>
              </div>
              <el-button type="primary" size="small" @click="addToScene(evt)">添加到场景</el-button>
            </div>
            <div class="tip-text">提示：可随时向场景中添加新事件，培养应变能力</div>
          </div>
        </div>

        <!-- 角色设置 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><User /></el-icon> 角色设置（救援/指挥/观摩）</span>
            <el-button type="primary" size="small" @click="handleAddRole">新增角色</el-button>
          </div>
          <div class="panel-body">
            <div class="role-item" v-for="role in roles" :key="role.id">
              <div class="role-name">{{ role.name }}（{{ role.type }}）</div>
              <div class="role-detail">技能：{{ role.skills }} | 装备：{{ role.equipment }}</div>
            </div>
          </div>
        </div>

        <!-- 任务设置 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><List /></el-icon> 任务设置（任务模型库）</span>
            <el-button type="primary" size="small" @click="handleAddTask">新增任务</el-button>
          </div>
          <div class="panel-body">
            <div class="task-item" v-for="task in tasks" :key="task.id">
              <div class="task-name">{{ task.name }}</div>
              <div class="task-desc">{{ task.desc }}</div>
              <div class="task-bind">绑定角色：{{ task.bindRole }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- ===== 右列 ===== -->
      <div class="col-right">
        <!-- 过程管理 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><VideoPlay /></el-icon> 过程管理</span>
          </div>
          <div class="panel-body">
            <div class="process-buttons">
              <el-button type="primary" size="small" @click="startDrill">启动</el-button>
              <el-button type="warning" size="small" @click="pauseDrill">暂停</el-button>
              <el-button type="danger" size="small" @click="exitDrill">退出</el-button>
            </div>
            <div class="event-log">
              <div class="log-item" v-for="(log, idx) in eventLogs" :key="idx">
                <span class="log-time">[{{ log.time }}]</span>
                <span class="log-text">{{ log.text }}</span>
              </div>
            </div>
            <div class="event-control">
              <div class="control-label">事件控制</div>
              <div class="control-buttons">
                <el-button type="primary" size="small" @click="triggerEvent">
                  <el-icon><Promotion /></el-icon>触发事件(发展)
                </el-button>
                <el-button size="small" @click="endEvent">
                  <el-icon><Document /></el-icon>结束事件
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 结果分析与评估 -->
        <div class="panel">
          <div class="panel-header">
            <span><el-icon><DataAnalysis /></el-icon> 结果分析与评估</span>
          </div>
          <div class="panel-body">
            <div class="metric-grid">
              <div class="metric-item"><div class="metric-label">任务完成率</div><div class="metric-value">{{ simResultData.task_completion_rate || '--' }}</div></div>
              <div class="metric-item"><div class="metric-label">平均响应时间</div><div class="metric-value">{{ simResultData.avg_response_time || '--' }}</div></div>
              <div class="metric-item"><div class="metric-label">应急评估等级</div><div class="metric-value highlight">{{ simResultData.emergency_level || '--' }}</div></div>
              <div class="metric-item"><div class="metric-label">建议</div><div class="metric-value small">{{ simResultData.suggestion || '暂无' }}</div></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 项目表单弹窗 -->
  <el-dialog v-model="projDialogVisible" title="演练项目" width="450px" destroy-on-close>
    <el-form :model="projForm" label-width="80px">
      <el-form-item label="项目名称"><el-input v-model="projForm.name" /></el-form-item>
      <el-form-item label="所属系统">
        <el-select v-model="projForm.category" style="width:100%">
          <el-option label="燃气" value="燃气" /><el-option label="排水" value="排水" /><el-option label="供水" value="供水" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer><el-button @click="projDialogVisible=false">取消</el-button><el-button type="primary" @click="handleProjSubmit">确定</el-button></template>
  </el-dialog>

  <!-- 场景编辑弹窗 -->
  <el-dialog v-model="sceneDialogVisible" title="场景编辑" width="450px" destroy-on-close>
    <el-input v-model="sceneNewTag" placeholder="输入新场景元素" style="width:70%"><template #append><el-button @click="addSceneTag()">添加</el-button></template></el-input>
    <div style="margin-top:12px"><el-tag v-for="t in currentSceneTags" :key="t" closable @close="removeSceneTag(t)" style="margin:4px">{{t}}</el-tag></div>
    <template #footer><el-button @click="sceneDialogVisible=false">关闭</el-button></template>
  </el-dialog>

  <!-- 事件弹窗 -->
  <el-dialog v-model="eventDialogVisible" title="新增事件" width="450px" destroy-on-close>
    <el-form :model="eventForm" label-width="80px">
      <el-form-item label="事件名称"><el-input v-model="eventForm.name" /></el-form-item>
      <el-form-item label="事件描述"><el-input v-model="eventForm.description" type="textarea" :rows="3" /></el-form-item>
    </el-form>
    <template #footer><el-button @click="eventDialogVisible=false">取消</el-button><el-button type="primary" @click="handleEventSubmit">确定</el-button></template>
  </el-dialog>

  <!-- 角色弹窗 -->
  <el-dialog v-model="roleDialogVisible" title="新增角色" width="450px" destroy-on-close>
    <el-form :model="roleForm" label-width="80px">
      <el-form-item label="角色名称"><el-input v-model="roleForm.name" /></el-form-item>
      <el-form-item label="角色类型"><el-select v-model="roleForm.roleType" style="width:100%"><el-option label="指挥类" value="指挥类"/><el-option label="救援类" value="救援类"/><el-option label="观摩类" value="观摩类"/></el-select></el-form-item>
      <el-form-item label="技能"><el-input v-model="roleForm.skills" /></el-form-item>
      <el-form-item label="装备"><el-input v-model="roleForm.equipment" /></el-form-item>
    </el-form>
    <template #footer><el-button @click="roleDialogVisible=false">取消</el-button><el-button type="primary" @click="handleRoleSubmit">确定</el-button></template>
  </el-dialog>

  <!-- 任务弹窗 -->
  <el-dialog v-model="taskDialogVisible" title="新增任务" width="450px" destroy-on-close>
    <el-form :model="taskForm" label-width="80px">
      <el-form-item label="任务名称"><el-input v-model="taskForm.name" /></el-form-item>
      <el-form-item label="任务描述"><el-input v-model="taskForm.description" type="textarea" :rows="3" /></el-form-item>
      <el-form-item label="绑定角色"><el-select v-model="taskForm.bindRoleId" style="width:100%"><el-option v-for="r in roles" :key="r.id" :label="r.name" :value="r.id"/></el-select></el-form-item>
    </el-form>
    <template #footer><el-button @click="taskDialogVisible=false">取消</el-button><el-button type="primary" @click="handleTaskSubmit">确定</el-button></template>
  </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Folder, Edit, Delete, PictureFilled, Warning, User, List,
  VideoPlay, Promotion, Document, DataAnalysis
} from '@element-plus/icons-vue'
import { getSimProjects, saveSimProject, deleteSimProject, addSimLog, processSimDrill, getSimScene, getSimEvent, getSimRole, getSimTask, getSimLog, getSimResult, saveSimScene, deleteSimScene, saveSimEvent, deleteSimEvent, saveSimRole, saveSimTask } from '@/api/pipeNetwork/basic'

const projects = ref([])
const projectSearch = ref('')
const handleSearchProject = () => { loadData() }
// 项目弹窗
const projDialogVisible = ref(false)
const projForm = ref({ id: null, name: '', category: '燃气' })
const handleAddProject = () => { projForm.value = { id: null, name: '', category: '燃气' }; projDialogVisible.value = true }
const handleEditProject = async (item) => { projForm.value = { ...item }; projDialogVisible.value = true }
const handleDeleteProject = (item) => { ElMessageBox.confirm('确认删除?', '提示', { type: 'warning' }).then(async () => { await deleteSimProject(item.id); ElMessage.success('删除成功'); loadData() }).catch(() => {}) }
const handleProjSubmit = async () => {
  const d = projForm.value
  try {
    if (d.id) { const p = projects.value.find(x => x.id === d.id); if (p) { p.name = d.name; p.category = d.category } }
    else { await saveSimProject({ name: d.name, category: d.category, createDate: new Date().toISOString().substring(0,10) }); }
    ElMessage.success('保存成功'); projDialogVisible.value = false; loadData()
  } catch (e) { ElMessage.error('保存失败') }
}

// 选中项目时加载子数据
const activeProjectId = ref(null)
const activeCategory = ref('')

// 场景
const currentSceneTags = ref([])
const sceneLibrary = ref([])
const sceneDialogVisible = ref(false)
const sceneNewTag = ref('')
let sceneDataCache = []
async function loadScene(id) { try { const r = await getSimScene(id); sceneDataCache = r.data||[]; sceneLibrary.value = sceneDataCache.map(s => s.tagName); currentSceneTags.value = sceneDataCache.filter(s => s.isActive===1).map(s => s.tagName) } catch (e) {} }
const addSceneTag = async (tag) => {
  const t = String(tag || sceneNewTag.value || '').trim(); if (!t) return
  if (currentSceneTags.value.includes(t)) { ElMessage.warning('已存在'); return }
  try {
    await saveSimScene({ projectId: activeProjectId.value, tagName: t, isActive: 1 })
    sceneNewTag.value = ''; loadScene(activeProjectId.value)
  } catch (e) { ElMessage.error('添加失败') }
}
const removeSceneTag = async (tag) => {
  const existing = sceneDataCache.find(s => s.tagName === tag && s.isActive === 1)
  if (existing) { try { await deleteSimScene(existing.id); loadScene(activeProjectId.value) } catch (e) { ElMessage.error('删除失败') } }
  else { currentSceneTags.value = currentSceneTags.value.filter(t => t !== tag) }
}
const handleEditScene = () => { sceneNewTag.value = ''; sceneDialogVisible.value = true }

// 事件
const events = ref([])
const eventDialogVisible = ref(false)
const eventForm = ref({ name: '', description: '' })
async function loadEvent(id) { try { const r = await getSimEvent(id); events.value = (r.data||[]).map(e => ({ id: e.id, name: e.name, desc: e.description })) } catch (e) {} }
const handleAddEvent = () => { eventForm.value = { name: '', description: '' }; eventDialogVisible.value = true }
const handleEventSubmit = async () => {
  try { await saveSimEvent({ projectId: activeProjectId.value, name: eventForm.value.name, description: eventForm.value.description }); ElMessage.success('新增成功'); eventDialogVisible.value = false; loadEvent(activeProjectId.value) } catch (e) { ElMessage.error('新增失败') }
}
const addToScene = async (evt) => {
  const existing = sceneDataCache.find(s => s.tagName === evt.name)
  if (existing) {
    try { await saveSimScene({ id: existing.id, projectId: activeProjectId.value, tagName: evt.name, isActive: 1 }); loadScene(activeProjectId.value); ElMessage.success(`已将"${evt.name}"添加到场景`) } catch (e) {}
  } else {
    try { await saveSimScene({ projectId: activeProjectId.value, tagName: evt.name, isActive: 1 }); loadScene(activeProjectId.value); ElMessage.success(`已将"${evt.name}"添加到场景`) } catch (e) {}
  }
}

// 角色
const roles = ref([])
const roleDialogVisible = ref(false)
const roleForm = ref({ name: '', roleType: '指挥类', skills: '', equipment: '' })
async function loadRole(id) { try { const r = await getSimRole(id); roles.value = (r.data||[]).map(rr => ({ id: rr.id, name: rr.name, type: rr.roleType, skills: rr.skills, equipment: rr.equipment })) } catch (e) {} }
const handleAddRole = () => { roleForm.value = { name: '', roleType: '指挥类', skills: '', equipment: '' }; roleDialogVisible.value = true }
const handleRoleSubmit = async () => {
  try { await saveSimRole({ projectId: activeProjectId.value, ...roleForm.value }); ElMessage.success('新增成功'); roleDialogVisible.value = false; loadRole(activeProjectId.value) } catch (e) { ElMessage.error('新增失败') }
}

// 任务
const tasks = ref([])
const taskDialogVisible = ref(false)
const taskForm = ref({ name: '', description: '', bindRoleId: null })
async function loadTask(id) { try { const r = await getSimTask(id); tasks.value = (r.data||[]).map(t => ({ id: t.id, name: t.name, desc: t.description, bindRole: t.bindRoleId })) } catch (e) {} }
const handleAddTask = () => { taskForm.value = { name: '', description: '', bindRoleId: roles.value[0]?.id || null }; taskDialogVisible.value = true }
const handleTaskSubmit = async () => {
  try { await saveSimTask({ projectId: activeProjectId.value, ...taskForm.value }); ElMessage.success('新增成功'); taskDialogVisible.value = false; loadTask(activeProjectId.value) } catch (e) { ElMessage.error('新增失败') }
}

// 结果数据
const simResultData = ref({})
async function loadResult(id) { try { const r = await getSimResult(id); simResultData.value = r.data || {} } catch (e) {} }
async function loadLogs(id) { try { const r = await getSimLog(id); const rows = r.data || []; if (rows.length) eventLogs.value = rows.map(l => ({ time: (l.logTime||'').substring(11,19) || '--', text: l.content || l.action })) } catch (e) {} }

// 选中项目
function selectProject(item) {
  activeProjectId.value = item.id
  activeCategory.value = item.category || item.category_name || ''
  loadScene(item.id); loadEvent(item.id); loadRole(item.id); loadTask(item.id); loadResult(item.id); loadLogs(item.id)
}

// ---------- 过程管理 ----------
const eventLogs = ref([])

async function loadData() { try { const res = await getSimProjects(); const rows = res.data || []; if (rows.length) { projects.value = rows.map(d => ({ id: d.id, name: d.name, category: d.category, date: d.create_date || d.createDate })); selectProject(projects.value[0]) } } catch (e) {} }
onMounted(() => { loadData() })

const doProcess = (action) => { return processSimDrill(activeProjectId.value, action, activeCategory.value) }
const reloadLogs = () => { if (activeProjectId.value) loadLogs(activeProjectId.value) }
const startDrill = () => { doProcess('启动').then(() => { reloadLogs(); ElMessage.success('演练已启动') }).catch(()=>{}) }
const pauseDrill = () => { doProcess('暂停').then(() => { reloadLogs(); ElMessage.warning('演练已暂停') }).catch(()=>{}) }
const exitDrill = () => { ElMessageBox.confirm('确认退出?','提示',{type:'warning'}).then(()=>{ doProcess('退出').then(() => reloadLogs()).catch(()=>{}) }).catch(()=>{}) }
const triggerEvent = () => { doProcess('触发事件').then(() => { reloadLogs(); ElMessage.success('事件已触发') }).catch(()=>{}) }
const endEvent = () => { doProcess('结束事件').then(() => { reloadLogs(); ElMessage.info('事件已结束') }).catch(()=>{}) }
</script>

<style scoped lang="scss">
.sim-layout {
  display: flex;
  gap: 12px;
  min-height: calc(100vh - 160px);
}

.col-left {
  width: 25%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.col-center {
  width: 50%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.col-right {
  width: 25%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.panel {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fff;
  overflow: hidden;

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 14px;
    background: #f5f7fa;
    border-bottom: 1px solid #e4e7ed;
    font-weight: bold;
    font-size: 14px;
    color: #303133;

    span {
      display: flex;
      align-items: center;
      gap: 6px;
    }

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

  .panel-body {
    padding: 12px 14px;
  }
}

// 项目列表
.project-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;
  cursor: pointer;

  &.selected { background: #ecf5ff; border-left: 3px solid #409eff; padding-left: 8px; }
  &:last-child { border-bottom: none; }

  .project-info {
    .project-name { font-size: 13px; color: #303133; font-weight: 500; }
    .project-date { font-size: 12px; color: #909399; margin-top: 2px; }
  }

  .project-actions {
    display: flex;
    gap: 2px;
  }
}

// 场景设置
.scene-section {
  margin-bottom: 12px;

  .scene-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 6px;
  }
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;

  .clickable-tag {
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      color: #409eff;
      border-color: #409eff;
    }
  }
}

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

.stat-line {
  font-size: 12px;
  color: #909399;
  text-align: right;
}

// 事件卡片
.event-card {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 10px;
  margin-bottom: 8px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fafafa;

  .event-info {
    flex: 1;
    margin-right: 10px;

    .event-name {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .event-desc {
      font-size: 12px;
      color: #909399;
      margin-top: 4px;
    }
  }
}

.tip-text {
  font-size: 12px;
  color: #909399;
  padding: 8px;
  background: #f0f9eb;
  border-radius: 4px;
  margin-top: 4px;
}

// 角色列表
.role-item {
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;

  &:last-child { border-bottom: none; }

  .role-name {
    font-size: 13px;
    font-weight: 500;
    color: #303133;
  }

  .role-detail {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
  }
}

// 任务列表
.task-item {
  padding: 8px 0;
  border-bottom: 1px dashed #ebeef5;

  &:last-child { border-bottom: none; }

  .task-name {
    font-size: 13px;
    font-weight: 500;
    color: #303133;
  }

  .task-desc {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }

  .task-bind {
    font-size: 12px;
    color: #409eff;
    margin-top: 2px;
  }
}

// 过程管理
.process-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 10px;
}

.event-log {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 10px;
  background: #fafafa;

  .log-item {
    font-size: 12px;
    line-height: 1.8;
    color: #606266;

    .log-time {
      color: #409eff;
      margin-right: 6px;
      font-family: monospace;
    }
  }
}

.event-control {
  border-top: 1px solid #ebeef5;
  padding-top: 10px;

  .control-label {
    font-size: 13px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 8px;
  }

  .control-buttons {
    display: flex;
    gap: 8px;
  }
}

// 结果分析
.metric-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-bottom: 12px;
}

.metric-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  text-align: center;

  .metric-label {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }

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

    &.highlight { color: #67c23a; }
    &.small { font-size: 13px; font-weight: normal; color: #606266; }
  }
}

.stat-cards {
  display: flex;
  gap: 10px;
}

.stat-card {
  flex: 1;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  text-align: center;
  background: #fafafa;

  .stat-title {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }

  .stat-content {
    font-size: 14px;
    font-weight: bold;
    color: #409eff;
  }
}
</style>
