<!--应急预案选择-->
<template>
  <div class="app-container">
    <div class="plan-layout">
      <!-- 左侧条件面板 -->
      <div class="left-panel">
        <!-- 突发事件条件设定 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Setting /></el-icon>
              <span>突发事件条件设定</span>
            </div>
          </template>
          <el-form label-position="top" size="default">
            <el-form-item label="事件类型">
              <el-select v-model="form.eventType" placeholder="请选择事件类型" style="width:100%">
                <el-option v-for="item in eventTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="事件级别">
              <el-select v-model="form.eventLevel" placeholder="请选择事件级别" style="width:100%">
                <el-option v-for="item in eventLevelOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="发生区域">
              <el-select v-model="form.eventRegion" placeholder="请选择发生区域" style="width:100%">
                <el-option v-for="item in eventRegionOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item label="事故责任单位">
              <el-select v-model="form.responsibleUnit" placeholder="请选择责任单位" style="width:100%">
                <el-option v-for="item in unitOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 预案匹配规则 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><InfoFilled /></el-icon>
              <span>预案匹配规则</span>
            </div>
          </template>
          <div class="rule-desc">
            <p>根据事件类型、级别、区域、责任单位进行数字预案库权重匹配：</p>
            <div class="rule-weights">
              <div class="weight-item">
                <span class="weight-label">事件类型</span>
                <el-progress :percentage="40" :stroke-width="14" :format="() => '40%'" color="#409EFF" />
              </div>
              <div class="weight-item">
                <span class="weight-label">事件级别</span>
                <el-progress :percentage="25" :stroke-width="14" :format="() => '25%'" color="#67C23A" />
              </div>
              <div class="weight-item">
                <span class="weight-label">发生区域</span>
                <el-progress :percentage="20" :stroke-width="14" :format="() => '20%'" color="#E6A23C" />
              </div>
              <div class="weight-item">
                <span class="weight-label">责任单位</span>
                <el-progress :percentage="15" :stroke-width="14" :format="() => '15%'" color="#F56C6C" />
              </div>
            </div>
            <p class="rule-tip">系统根据加权相似度搜寻最佳匹配预案</p>
          </div>
          <el-button type="primary" style="width:100%;margin-top:12px" @click="manualMatch">
            <el-icon><Search /></el-icon> 立即匹配预案
          </el-button>
        </el-card>

        <!-- 最近匹配记录 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Clock /></el-icon>
              <span>最近匹配记录</span>
            </div>
          </template>
          <div class="history-list">
            <div v-for="item in matchHistory" :key="item.id" class="history-item">
              <div class="history-date">{{ item.date }}</div>
              <div class="history-desc">{{ item.desc }} → {{ item.planName }}</div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧结果面板 -->
      <div class="right-panel">
        <!-- 一键快速查找 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Promotion /></el-icon>
              <span>常见专题预案 · 一键快速查找</span>
            </div>
          </template>
          <div class="topic-row">
            <el-button
              v-for="topic in topics"
              :key="topic.value"
              :type="activeTopic === topic.value ? 'primary' : 'default'"
              round
              @click="matchByTopic(topic.value)"
            >
              {{ topic.label }}
            </el-button>
          </div>
          <div class="topic-tip">支持一键选择，系统自动定位匹配数字预案库中的专题预案</div>
        </el-card>

        <!-- 匹配结果 -->
        <el-card shadow="never" class="panel-card">
          <template #header>
            <div class="card-title">
              <el-icon><Document /></el-icon>
              <span>数字预案库 · 匹配结果</span>
              <el-tag v-if="matchResults.length > 0" type="success" size="small" style="margin-left:8px">
                匹配到 {{ matchResults.length }} 个预案
              </el-tag>
              <el-tag v-else type="info" size="small" style="margin-left:8px">待匹配</el-tag>
            </div>
          </template>
          <div v-if="matchResults.length === 0" class="empty-state">
            <el-empty description="请设置突发事件条件，点击「立即匹配预案」或选择专题预案" />
          </div>
          <div v-else class="plan-list">
            <div
              v-for="plan in matchResults"
              :key="plan.id"
              class="plan-item"
              :class="{ selected: selectedPlan?.id === plan.id }"
              @click="selectPlan(plan)"
            >
              <div class="plan-head">
                <span class="plan-name">{{ plan.name }}</span>
                <el-tag :type="plan.matchScore >= 90 ? 'danger' : plan.matchScore >= 70 ? 'warning' : 'info'" size="small">
                  匹配度 {{ plan.matchScore }}%
                </el-tag>
              </div>
              <div class="plan-tags">
                <el-tag size="small" type="primary">{{ plan.type }}</el-tag>
                <el-tag size="small" type="warning">{{ plan.level }}</el-tag>
                <el-tag size="small">{{ plan.region }}</el-tag>
                <el-tag size="small" type="success">{{ plan.unit }}</el-tag>
              </div>
              <div class="plan-summary">{{ plan.summary }}</div>
            </div>
          </div>
        </el-card>

        <!-- 当前选定预案详情 -->
        <el-card shadow="never" class="panel-card detail-card">
          <template #header>
            <div class="card-title">
              <el-icon><Checked /></el-icon>
              <span>当前选定预案详情</span>
              <el-button
                v-if="selectedPlan"
                type="primary"
                size="small"
                style="margin-left:auto"
                @click="applyPlan"
              >
                应用预案
              </el-button>
            </div>
          </template>
          <div v-if="selectedPlan" class="detail-content">
            <el-descriptions :column="2" border size="small">
              <el-descriptions-item label="预案名称">{{ selectedPlan.name }}</el-descriptions-item>
              <el-descriptions-item label="匹配度">
                <el-tag :type="selectedPlan.matchScore >= 90 ? 'danger' : 'warning'" size="small">
                  {{ selectedPlan.matchScore }}%
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="事件类型">{{ selectedPlan.type }}</el-descriptions-item>
              <el-descriptions-item label="事件级别">{{ selectedPlan.level }}</el-descriptions-item>
              <el-descriptions-item label="发生区域">{{ selectedPlan.region }}</el-descriptions-item>
              <el-descriptions-item label="责任单位">{{ selectedPlan.unit }}</el-descriptions-item>
            </el-descriptions>
            <div class="detail-summary">
              <div class="summary-label">预案内容概要</div>
              <div class="summary-text">{{ selectedPlan.content }}</div>
            </div>
          </div>
          <div v-else class="empty-detail">
            <el-empty description="未选择具体预案，点击上方匹配结果中的预案可查看详情" :image-size="60" />
          </div>
        </el-card>
      </div>
    </div>

    <!-- 应用预案确认弹窗 -->
    <el-dialog v-model="applyDialogVisible" title="应用预案确认" width="480px" append-to-body>
      <div v-if="selectedPlan" style="line-height:2">
        <p><strong>预案名称：</strong>{{ selectedPlan.name }}</p>
        <p><strong>匹配度：</strong>{{ selectedPlan.matchScore }}%</p>
        <p><strong>事件类型：</strong>{{ selectedPlan.type }} | <strong>级别：</strong>{{ selectedPlan.level }}</p>
        <p><strong>区域：</strong>{{ selectedPlan.region }} | <strong>责任单位：</strong>{{ selectedPlan.unit }}</p>
        <el-divider />
        <p>预案内容将分发至应急指挥中心及相应处置单位，确定应用此预案？</p>
      </div>
      <template #footer>
        <el-button @click="applyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmApply">确认应用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { Setting, InfoFilled, Clock, Promotion, Document, Checked, Search } from '@element-plus/icons-vue'
import { matchPlan, matchPlanByTopic, getPlanMatchHistory, applyPlan as applyPlanApi } from '@/api/dispatch'

// 下拉选项（排水/供水/燃气 三类规划）
const eventTypeOptions = ['排水', '供水', '燃气']
const eventLevelOptions = ['一般(IV级)', '较大(III级)', '重大(II级)', '特别重大(I级)']
const eventRegionOptions = ['城南', '城北', '太常']
const unitOptions = ['供水局', '燃气公司', '排水公司']

// 表单
const form = reactive({
  eventType: '排水',
  eventLevel: '较大(III级)',
  eventRegion: '城南',
  responsibleUnit: '排水公司'
})

// 数字预案库由后端接口维护（dis_plan_library 表）

// 专题列表（对应三大类）
const topics = ref([
  { label: '排水专题', value: '排水专题' },
  { label: '供水专题', value: '供水专题' },
  { label: '燃气专题', value: '燃气专题' }
])

// 最近匹配记录（接口加载）
const matchHistory = ref([])

// 状态
const matchResults = ref([])
const selectedPlan = ref(null)
const activeTopic = ref('')
const applyDialogVisible = ref(false)

// 后端匹配结果 → 页面展示字段映射
const toDisplayPlan = (vo) => ({
  id: vo.id,
  name: vo.planName,
  type: vo.eventType,
  level: vo.eventLevel,
  region: vo.eventRegion,
  unit: vo.responsibleUnit,
  topic: vo.topic,
  summary: vo.planSummary,
  content: vo.planContent,
  matchScore: vo.matchScore
})

// 加载最近匹配记录
const loadHistory = async () => {
  try {
    const res = await getPlanMatchHistory(10)
    matchHistory.value = (res.data || []).map(r => ({
      id: r.id,
      date: (r.createTime || '').substring(0, 10),
      desc: r.recordDesc,
      planName: r.planName
    }))
  } catch (e) {
    ElMessage.error('加载最近匹配记录失败')
  }
}

// 专题匹配
const matchByTopic = async (topicName) => {
  activeTopic.value = topicName
  try {
    const res = await matchPlanByTopic({ topic: topicName })
    const matched = (res.data || []).map(toDisplayPlan)
    matchResults.value = matched
    selectedPlan.value = matched.length > 0 ? matched[0] : null
    loadHistory()
  } catch (e) {
    ElMessage.error('专题匹配失败')
  }
}

// 手动匹配
const manualMatch = async () => {
  activeTopic.value = ''
  try {
    const res = await matchPlan({ ...form })
    const matched = (res.data || []).map(toDisplayPlan)
    matchResults.value = matched
    selectedPlan.value = matched.length > 0 ? matched[0] : null
    loadHistory()
  } catch (e) {
    ElMessage.error('预案匹配失败')
  }
}

// 选择预案
const selectPlan = (plan) => {
  selectedPlan.value = plan
}

// 应用预案（打开确认弹窗）
const applyPlan = () => {
  if (!selectedPlan.value) {
    ElMessage.warning('请先选择一个预案')
    return
  }
  applyDialogVisible.value = true
}

const confirmApply = async () => {
  applyDialogVisible.value = false
  try {
    await applyPlanApi({
      ...form,
      planId: selectedPlan.value.id,
      planName: selectedPlan.value.name,
      matchScore: selectedPlan.value.matchScore
    })
    ElMessage.success(`已启动预案: ${selectedPlan.value.name}，预案内容将分发至应急指挥中心及相应处置单位。`)
    loadHistory()
  } catch (e) {
    ElMessage.error('预案应用失败')
  }
}

// 初始化：仅加载最近匹配记录，不自动匹配（只有点击「立即匹配预案」才生成记录）
const init = async () => {
  await loadHistory()
}
init()
</script>

<style scoped>
.app-container {
  padding: 16px;
  background: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.plan-layout {
  display: flex;
  gap: 16px;
  height: 100%;
}

.left-panel {
  width: 30%;
  min-width: 320px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-width: 0;
}

.panel-card {
  border-radius: 8px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.card-title .el-icon {
  color: #409EFF;
  font-size: 16px;
}

/* 匹配规则 */
.rule-desc {
  font-size: 13px;
  color: #606266;
  line-height: 1.8;
}

.rule-weights {
  margin: 10px 0;
}

.weight-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 6px;
}

.weight-label {
  width: 70px;
  font-size: 12px;
  color: #909399;
  flex-shrink: 0;
}

.weight-item .el-progress {
  flex: 1;
}

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

/* 最近匹配记录 */
.history-list {
  max-height: 160px;
  overflow-y: auto;
}

.history-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 12px;
  color: #606266;
}

.history-item:last-child {
  border-bottom: none;
}

.history-date {
  color: #909399;
  font-size: 11px;
}

.history-desc {
  margin-top: 2px;
  color: #303133;
}

/* 专题按钮 */
.topic-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.topic-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
  text-align: center;
}

/* 预案列表 */
.plan-list {
  max-height: 360px;
  overflow-y: auto;
}

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

.plan-item:hover {
  border-color: #409EFF;
  background: #ecf5ff;
}

.plan-item.selected {
  border-color: #409EFF;
  background: #ecf5ff;
  border-left: 3px solid #409EFF;
}

.plan-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.plan-name {
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.plan-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  margin-bottom: 6px;
}

.plan-summary {
  font-size: 12px;
  color: #909399;
  line-height: 1.6;
}

/* 详情区域 */
.detail-content {
  font-size: 13px;
}

.detail-summary {
  margin-top: 12px;
}

.summary-label {
  font-weight: 600;
  color: #303133;
  margin-bottom: 6px;
  font-size: 13px;
}

.summary-text {
  font-size: 13px;
  color: #606266;
  line-height: 1.8;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.empty-state {
  padding: 20px 0;
}

.empty-detail {
  padding: 10px 0;
}
</style>
