<!--应急总结评估-->
<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" v-if="events.length">
            <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="evaluatedIds.has(event.id)" type="success" size="small">已评估</el-tag>
                <el-tag v-else type="info" size="small">待评估</el-tag>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无已解除/已关闭事件" :image-size="80" />
          <el-button type="primary" plain :loading="loading" 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" v-if="currentEvent">
          <template #header>
            <div class="panel-title-row">
              <span class="panel-title">应急事件事后评估</span>
              <el-tag v-if="evaluatedIds.has(currentEvent.id)" 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>
        <el-empty v-else description="暂无已解除/已关闭事件，请先完成事件处置后进行评估" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getEventPage, getEventAssess, listEventAssess, saveEventAssess, deleteEventAssess } from '@/api/dispatch'

// 已解除/已关闭事件列表（可评估）
const events = ref([])
const loading = ref(false)
const currentEventId = ref(null)
// 已评估事件 id 集合
const evaluatedIds = ref(new Set())
// 当前事件评估记录（含案例库标记）
const currentAssess = ref(null)
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) || null
})

// 清空评估表单
const resetAssessments = () => {
  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 loadAssessmentsToForm = async () => {
  resetAssessments()
  const event = currentEvent.value
  currentAssess.value = null
  if (!event) return
  try {
    const res = await getEventAssess(event.id)
    currentAssess.value = res.data || null
    if (currentAssess.value) {
      assessments.org.score = Number(currentAssess.value.orgScore) || 0
      assessments.org.comment = currentAssess.value.orgComment || ''
      assessments.cap.score = Number(currentAssess.value.capScore) || 0
      assessments.cap.comment = currentAssess.value.capComment || ''
      assessments.effect.score = Number(currentAssess.value.effectScore) || 0
      assessments.effect.comment = currentAssess.value.effectComment || ''
      assessments.loss.score = Number(currentAssess.value.lossScore) || 0
      assessments.loss.comment = currentAssess.value.lossComment || ''
    }
  } catch (e) {
    currentAssess.value = null
  }
}

// 加载事件列表（已解除/已关闭）并批量标记已评估
const loadEvents = async () => {
  loading.value = true
  try {
    const res = await getEventPage(1, 200, { statusList: ['已解除', '已关闭'] })
    const rows = res.data?.records || res.data?.rows || res.records || res.rows || []
    events.value = (rows || []).map(e => ({
      id: e.id, name: e.eventName, time: e.happenTime, location: e.location,
      level: e.level, type: e.eventType, desc: e.description
    }))
    evaluatedIds.value = new Set()
    if (events.value.length) {
      const ass = await listEventAssess(events.value.map(e => e.id))
      evaluatedIds.value = new Set((ass.data || []).map(a => a.relEventId))
    }
    if (!currentEventId.value || !events.value.some(e => e.id === currentEventId.value)) {
      currentEventId.value = events.value.length ? events.value[0].id : null
    }
    await loadAssessmentsToForm()
  } finally {
    loading.value = false
  }
}

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

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

// 生成评估报告（保存评估到后端 + 下载报告）
const generateReport = async () => {
  const event = currentEvent.value
  if (!event) return
  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()

  // 保存评估到后端（自动计算综合分与等级）
  try {
    await saveEventAssess({
      eventId: event.id,
      orgScore: scores.org, orgComment: assessments.org.comment,
      capScore: scores.cap, capComment: assessments.cap.comment,
      effectScore: scores.effect, effectComment: assessments.effect.comment,
      lossScore: scores.loss, lossComment: assessments.loss.comment,
      caseFlag: currentAssess.value?.caseFlag || '0'
    })
    evaluatedIds.value.add(event.id)
    currentAssess.value = { ...(currentAssess.value || {}), caseFlag: currentAssess.value?.caseFlag || '0' }
  } catch (e) {
    ElMessage.error('评估保存失败，请重试')
    return
  }

  // 生成下载
  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 = async () => {
  const event = currentEvent.value
  if (!event) return
  if (!evaluatedIds.value.has(event.id)) {
    ElMessage.warning('请先生成评估报告后再录入案例库')
    return
  }
  if (currentAssess.value?.caseFlag === '1') {
    ElMessage.warning('该事件已录入案例库，不可重复录入')
    return
  }
  try {
    await saveEventAssess({ eventId: event.id, caseFlag: '1' })
    if (currentAssess.value) currentAssess.value.caseFlag = '1'
    ElMessage.success('已成功录入案例库')
  } catch (e) {
    ElMessage.error('录入失败，请重试')
  }
}

// 重新评估（删除后端评估记录并清空表单）
const resetEvaluation = () => {
  const event = currentEvent.value
  if (!event) return
  ElMessageBox.confirm('确认重新评估？当前评估记录将被删除，所有评分和评语将被清空。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteEventAssess(event.id)
      evaluatedIds.value.delete(event.id)
      currentAssess.value = null
      resetAssessments()
      ElMessage.info('评估已重置')
    } catch (e) {
      ElMessage.error('重置失败，请重试')
    }
  }).catch(() => {})
}

// 刷新事件列表
const handleRefresh = () => {
  loadEvents()
}

// 初始化加载
onMounted(() => {
  loadEvents()
})

// 监听事件切换
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>
