<!--应急总结评估-->
<template>
  <div class="app-container">
    <div class="summary-layout">
      <!-- 左侧事件面板 -->
      <div class="left-panel">
        <el-card shadow="hover" class="event-list-card">
          <template #header>
            <div class="panel-title">应急事件列表</div>
          </template>
          <div class="event-list">
            <div
              v-for="event in events"
              :key="event.id"
              class="event-item"
              :class="{ selected: currentEventId === event.id }"
              @click="selectEvent(event.id)"
            >
              <div class="event-name">
                {{ event.name }}
                <el-tag :type="levelTagType(event.level)" size="small" effect="dark" style="margin-left: 6px">{{ event.level }}</el-tag>
              </div>
              <div class="event-meta">{{ event.location }}</div>
              <div class="event-status">
                <el-tag v-if="event.evaluated" type="success" size="small">已评估</el-tag>
                <el-tag v-else type="info" size="small">待评估</el-tag>
              </div>
            </div>
          </div>
          <el-button type="primary" plain style="width: 100%; margin-top: 12px" @click="handleRefresh">刷新事件列表</el-button>
        </el-card>

        <el-card shadow="hover" class="event-detail-card" v-if="currentEvent">
          <template #header>
            <div class="panel-title">事件基本记录</div>
          </template>
          <el-form label-width="80px" size="default" class="detail-form">
            <el-form-item label="事件名称">
              <el-input :model-value="currentEvent.name" readonly />
            </el-form-item>
            <el-form-item label="发生时间">
              <el-input :model-value="currentEvent.time" readonly />
            </el-form-item>
            <el-form-item label="事件地点">
              <el-input :model-value="currentEvent.location" readonly />
            </el-form-item>
            <el-form-item label="事件等级">
              <el-input :model-value="currentEvent.level" readonly />
            </el-form-item>
            <el-form-item label="事件类型">
              <el-input :model-value="currentEvent.type" readonly />
            </el-form-item>
            <el-form-item label="简要描述">
              <el-input :model-value="currentEvent.desc" type="textarea" :rows="3" readonly />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <!-- 右侧评估面板 -->
      <div class="right-panel">
        <el-card shadow="hover">
          <template #header>
            <div class="panel-title-row">
              <span class="panel-title">应急事件事后评估</span>
              <el-tag v-if="currentEvent?.evaluated" type="success" effect="dark" size="large">已评估</el-tag>
              <el-tag v-else type="warning" effect="dark" size="large">未评估</el-tag>
            </div>
          </template>

          <!-- 应急组织体系 -->
          <div class="assess-group">
            <div class="assess-header">
              <span class="assess-title">应急组织体系</span>
              <el-rate v-model="assessments.org.score" :max="5" allow-half show-score score-template="{value}分" />
            </div>
            <el-input v-model="assessments.org.comment" type="textarea" :rows="2" placeholder="组织架构、指挥体系等" />
          </div>

          <!-- 应急能力 -->
          <div class="assess-group">
            <div class="assess-header">
              <span class="assess-title">应急能力</span>
              <el-rate v-model="assessments.cap.score" :max="5" allow-half show-score score-template="{value}分" />
            </div>
            <el-input v-model="assessments.cap.comment" type="textarea" :rows="2" placeholder="响应速度、资源调配等" />
          </div>

          <!-- 处置效果 -->
          <div class="assess-group">
            <div class="assess-header">
              <span class="assess-title">处置效果</span>
              <el-rate v-model="assessments.effect.score" :max="5" allow-half show-score score-template="{value}分" />
            </div>
            <el-input v-model="assessments.effect.comment" type="textarea" :rows="2" placeholder="措施有效性、协同配合等" />
          </div>

          <!-- 灾害损失 -->
          <div class="assess-group">
            <div class="assess-header">
              <span class="assess-title">灾害损失</span>
              <el-rate v-model="assessments.loss.score" :max="5" allow-half show-score score-template="{value}分" />
            </div>
            <el-input v-model="assessments.loss.comment" type="textarea" :rows="2" placeholder="人员伤亡、经济损失等" />
          </div>

          <!-- 操作按钮 -->
          <div class="action-row">
            <el-button type="primary" @click="generateReport">生成评估报告下载</el-button>
            <el-button type="success" @click="saveToCaseLibrary">录入案例库</el-button>
            <el-button @click="resetEvaluation">重新评估</el-button>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Mock 事件数据
const events = ref([
  {
    id: 1, name: '化工园区氯气泄漏事故', time: '2025-05-15 08:30', location: '华东化工园区',
    level: '重大', type: '事故灾难', desc: '储罐区氯气阀门失效导致泄漏，影响周边2km范围，已启动二级应急响应。',
    evaluated: false, caseAdded: false,
    assessments: { org: { score: 0, comment: '' }, cap: { score: 0, comment: '' }, effect: { score: 0, comment: '' }, loss: { score: 0, comment: '' } }
  },
  {
    id: 2, name: '特大暴雨洪涝灾害', time: '2025-07-20 14:00', location: '华南沿海城市',
    level: '特别重大', type: '自然灾害', desc: '连续强降雨引发城市内涝，受灾人口超10万，多处基础设施受损。',
    evaluated: false, caseAdded: false,
    assessments: { org: { score: 0, comment: '' }, cap: { score: 0, comment: '' }, effect: { score: 0, comment: '' }, loss: { score: 0, comment: '' } }
  },
  {
    id: 3, name: '地铁施工坍塌事故', time: '2025-03-10 10:15', location: '城西地铁5号线',
    level: '较大', type: '事故灾难', desc: '隧道施工段发生坍塌，3人被困，已组织现场救援。',
    evaluated: false, caseAdded: false,
    assessments: { org: { score: 0, comment: '' }, cap: { score: 0, comment: '' }, effect: { score: 0, comment: '' }, loss: { score: 0, comment: '' } }
  },
  {
    id: 4, name: '太常片区供水管道爆裂', time: '2025-01-25 06:45', location: '太常片区主干道',
    level: '重大', type: '管网泄漏', desc: 'DN800供水主管爆裂，影响周边3万居民用水，已紧急调度供水车。',
    evaluated: true, caseAdded: true,
    assessments: { org: { score: 4, comment: '组织架构较为清晰，指挥层级明确' }, cap: { score: 3.5, comment: '响应速度较快，但资源调配稍显滞后' }, effect: { score: 4, comment: '现场处置得当，各部门协同配合良好' }, loss: { score: 3, comment: '经济损失较大，但人员伤亡控制较好' } }
  },
  {
    id: 5, name: '城南片区排水管网堵塞', time: '2025-04-08 16:30', location: '城南片区低洼路段',
    level: '一般', type: '管道堵塞', desc: '排水管网严重堵塞导致路面积水，影响交通通行。',
    evaluated: false, caseAdded: false,
    assessments: { org: { score: 0, comment: '' }, cap: { score: 0, comment: '' }, effect: { score: 0, comment: '' }, loss: { score: 0, comment: '' } }
  }
])

const currentEventId = ref(1)
const assessments = reactive({
  org: { score: 0, comment: '' },
  cap: { score: 0, comment: '' },
  effect: { score: 0, comment: '' },
  loss: { score: 0, comment: '' }
})

// 当前选中事件
const currentEvent = computed(() => {
  return events.value.find(e => e.id === currentEventId.value) || events.value[0]
})

// 加载评估数据到表单
const loadAssessmentsToForm = () => {
  const event = currentEvent.value
  if (event && event.evaluated && event.assessments) {
    assessments.org.score = event.assessments.org.score
    assessments.org.comment = event.assessments.org.comment
    assessments.cap.score = event.assessments.cap.score
    assessments.cap.comment = event.assessments.cap.comment
    assessments.effect.score = event.assessments.effect.score
    assessments.effect.comment = event.assessments.effect.comment
    assessments.loss.score = event.assessments.loss.score
    assessments.loss.comment = event.assessments.loss.comment
  } else {
    assessments.org.score = 0; assessments.org.comment = ''
    assessments.cap.score = 0; assessments.cap.comment = ''
    assessments.effect.score = 0; assessments.effect.comment = ''
    assessments.loss.score = 0; assessments.loss.comment = ''
  }
}

// 选择事件
const selectEvent = (id) => {
  currentEventId.value = id
  loadAssessmentsToForm()
}

// 等级tag颜色
const levelTagType = (level) => {
  const map = { '一般': 'info', '较大': 'warning', '重大': 'danger', '特别重大': 'danger' }
  return map[level] || 'info'
}

// 生成评估报告
const generateReport = () => {
  const event = currentEvent.value
  const scores = {
    org: assessments.org.score,
    cap: assessments.cap.score,
    effect: assessments.effect.score,
    loss: assessments.loss.score
  }
  const totalScore = (scores.org + scores.cap + scores.effect + scores.loss) / 4
  const totalPercent = (totalScore / 5 * 100).toFixed(1)

  let grade = ''
  if (totalScore >= 4.5) grade = '优秀'
  else if (totalScore >= 3.5) grade = '良好'
  else if (totalScore >= 2.5) grade = '一般'
  else grade = '较差'

  const reportText = `
应急事件总结评估报告
====================

【基本信息】
事件名称: ${event.name}
发生时间: ${event.time}
发生地点: ${event.location}
事件等级: ${event.level}
事件类型: ${event.type}
简要描述: ${event.desc}

【评估维度】
1. 应急组织体系: ${scores.org}/5分
   评语: ${assessments.org.comment || '无'}
2. 应急能力: ${scores.cap}/5分
   评语: ${assessments.cap.comment || '无'}
3. 处置效果: ${scores.effect}/5分
   评语: ${assessments.effect.comment || '无'}
4. 灾害损失: ${scores.loss}/5分
   评语: ${assessments.loss.comment || '无'}

【综合评分】
总分: ${totalScore.toFixed(1)}/5 (${totalPercent}%)
评价等级: ${grade}

报告生成时间: ${new Date().toLocaleString()}
  `.trim()

  // 保存到事件对象
  event.evaluated = true
  event.assessments = {
    org: { score: scores.org, comment: assessments.org.comment },
    cap: { score: scores.cap, comment: assessments.cap.comment },
    effect: { score: scores.effect, comment: assessments.effect.comment },
    loss: { score: scores.loss, comment: assessments.loss.comment }
  }

  // 生成下载
  const blob = new Blob([reportText], { type: 'text/plain;charset=utf-8' })
  const url = URL.createObjectURL(blob)
  const link = document.createElement('a')
  link.href = url
  link.download = `评估报告_${event.name}_${new Date().toISOString().slice(0, 10)}.txt`
  link.click()
  URL.revokeObjectURL(url)

  ElMessage.success('评估报告已生成并下载')
}

// 录入案例库
const saveToCaseLibrary = () => {
  const event = currentEvent.value
  if (!event.evaluated) {
    ElMessage.warning('请先生成评估报告后再录入案例库')
    return
  }
  if (event.caseAdded) {
    ElMessage.warning('该事件已录入案例库，不可重复录入')
    return
  }
  event.caseAdded = true
  ElMessage.success('已成功录入案例库')
}

// 重新评估
const resetEvaluation = () => {
  ElMessageBox.confirm('确认重新评估？所有评分和评语将被清空。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    assessments.org.score = 0; assessments.org.comment = ''
    assessments.cap.score = 0; assessments.cap.comment = ''
    assessments.effect.score = 0; assessments.effect.comment = ''
    assessments.loss.score = 0; assessments.loss.comment = ''
    const event = currentEvent.value
    if (event.evaluated) {
      event.evaluated = false
      event.caseAdded = false
    }
    ElMessage.info('评估已重置')
  }).catch(() => {})
}

// 刷新事件列表
const handleRefresh = () => {
  ElMessage.success('事件列表已刷新')
}

// 初始化加载
loadAssessmentsToForm()

// 监听事件切换
watch(currentEventId, () => {
  loadAssessmentsToForm()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 16px;
}

.summary-layout {
  display: flex;
  gap: 16px;
  min-height: calc(100vh - 120px);
}

// 左侧面板
.left-panel {
  width: 30%;
  min-width: 320px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.event-list-card {
  :deep(.el-card__body) {
    padding: 12px;
  }
}

.event-list {
  max-height: 300px;
  overflow-y: auto;
}

.event-item {
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;

  &:hover {
    border-color: #c6e2ff;
    background: #ecf5ff;
  }

  &.selected {
    border-color: #409eff;
    background: #ecf5ff;
    box-shadow: 0 0 0 1px #409eff;
  }
}

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

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

.event-status {
  margin-top: 6px;
}

.event-detail-card {
  flex: 1;

  :deep(.el-card__body) {
    padding: 12px;
  }
}

.detail-form {
  :deep(.el-form-item__label) {
    font-size: 13px;
    color: #606266;
  }

  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    background: #f5f7fa;
    color: #606266;
  }
}

// 右侧面板
.right-panel {
  flex: 1;
  min-width: 0;
}

.panel-title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.panel-title {
  font-weight: 600;
  font-size: 15px;
}

// 评估维度
.assess-group {
  margin-bottom: 24px;
  padding-bottom: 24px;
  border-bottom: 1px solid #ebeef5;

  &:last-of-type {
    border-bottom: none;
  }
}

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

.assess-title {
  font-weight: 600;
  font-size: 15px;
  color: #303133;
}

// 操作按钮
.action-row {
  display: flex;
  gap: 12px;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}
</style>
