<template>
  <div class="app-container warning-query-page" v-loading="loading">
    <el-card shadow="never" class="page-card header-card">
      <div class="page-header">
        <div>
          <div class="page-title">预警信息管理</div>
          <div class="page-subtitle">支持预警查询、处置过程跟踪和可视化流程查询，掌握预警历史处置情况、GIS定位和电子存档信息</div>
        </div>
        <el-button type="primary" icon="Refresh" @click="reloadAll">刷新</el-button>
      </div>
    </el-card>

    <div class="summary-grid">
      <el-card shadow="hover" class="summary-card primary">
        <div class="summary-label">综合查询结果</div>
        <div class="summary-value">{{ total }}</div>
        <div class="summary-desc">当前筛选条件下的预警总数</div>
      </el-card>
      <el-card shadow="hover" class="summary-card warning">
        <div class="summary-label">处理中任务</div>
        <div class="summary-value">{{ processingTotal }}</div>
        <div class="summary-desc">正在执行处置的预警任务数量</div>
      </el-card>
      <el-card shadow="hover" class="summary-card success">
        <div class="summary-label">已完结任务</div>
        <div class="summary-value">{{ completedTotal }}</div>
        <div class="summary-desc">已完成处置的预警任务数量</div>
      </el-card>
    </div>

    <el-card shadow="never" class="page-card">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="预警名称">
          <el-input v-model="queryParams.warningName" placeholder="请输入预警名称" clearable style="width: 220px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="预警编号">
          <el-input v-model="queryParams.warningNo" placeholder="请输入预警编号" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="预警类型">
          <el-select v-model="queryParams.warningType" clearable placeholder="请选择预警类型" style="width: 180px">
            <el-option
              v-for="item in warningTypeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="预警级别">
          <el-select v-model="queryParams.warningLevel" clearable placeholder="请选择预警级别" style="width: 180px">
            <el-option
              v-for="item in warningLevelOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" clearable placeholder="请选择状态" style="width: 180px">
            <el-option label="已发布" value="RELEASED" />
            <el-option label="待处理" value="PENDING" />
            <el-option label="处理中" value="PROCESSING" />
            <el-option label="已处理" value="HANDLED" />
            <el-option label="已解除" value="CLOSED" />
            <el-option label="已退回" value="RETURNED" />
          </el-select>
        </el-form-item>
        <el-form-item label="预警位置">
          <el-input v-model="queryParams.location" placeholder="请输入预警位置" clearable style="width: 220px" />
        </el-form-item>
        <el-form-item label="发布人">
          <el-input v-model="queryParams.publisher" placeholder="请输入发布人" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="权属单位">
          <el-input v-model="queryParams.ownershipUnit" placeholder="请输入权属单位" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 360px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="page-card">
      <template #header>
        <div class="section-title">预警查询</div>
      </template>
      <el-table :data="warningList" @row-click="handleSelectWarning">
        <el-table-column label="序号" width="70" align="center">
          <template #default="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="预警名称" prop="warningName" min-width="180" show-overflow-tooltip />
        <el-table-column label="预警编号" prop="warningNo" width="170" />
        <el-table-column label="预警类型" prop="warningTypeText" width="120" />
        <el-table-column label="预警级别" width="110" align="center">
          <template #default="scope">
            <el-tag :type="getLevelTagType(scope.row.warningLevel)">
              {{ scope.row.warningLevelText }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="110" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="预警位置" prop="location" min-width="180" show-overflow-tooltip />
        <el-table-column label="发布人" prop="publisher" width="120" />
        <el-table-column label="权属单位" prop="ownershipUnit" width="160" show-overflow-tooltip />
        <el-table-column label="发布时间" prop="publishTime" width="180" />
        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template #default="scope">
            <el-button link type="primary" @click.stop="openDetail(scope.row)">详情</el-button>
            <el-button link type="success" @click.stop="handleSelectWarning(scope.row)">流程</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="loadWarnings"
      />
    </el-card>

    <el-row :gutter="16">
      <el-col :xs="24" :lg="12">
        <el-card shadow="never" class="page-card track-card">
          <template #header>
            <div class="section-title">处置过程跟踪</div>
          </template>
          <el-tabs v-model="trackTab" @tab-change="loadTrackList">
            <el-tab-pane :label="`进行中 (${processingTotal})`" name="processing" />
            <el-tab-pane :label="`已完成 (${completedTotal})`" name="completed" />
          </el-tabs>
          <el-table :data="trackList" height="360" @row-click="handleSelectWarningFromTrack">
            <el-table-column label="预警名称" prop="warningName" min-width="170" show-overflow-tooltip />
            <el-table-column label="预警类型" prop="warningTypeText" width="120" />
            <el-table-column label="预警级别" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getLevelTagType(scope.row.warningLevel)">
                  {{ scope.row.warningLevelText }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处置人" prop="handler" width="110" />
            <el-table-column label="状态" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getStatusTagType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="发布时间" prop="publishTime" width="170" />
          </el-table>
        </el-card>
      </el-col>

      <el-col :xs="24" :lg="12">
        <el-card shadow="never" class="page-card process-card">
          <template #header>
            <div class="section-title">可视化流程查询</div>
          </template>

          <el-empty v-if="!selectedWarningId" description="请选择一条预警查看流程路线图" />

          <template v-else>
            <div class="selected-info">
              <div class="selected-name">{{ processMeta.warningName || selectedWarningRow?.warningName || "-" }}</div>
              <div class="selected-meta">
                <span>编号：{{ processMeta.warningNo || selectedWarningRow?.warningNo || "-" }}</span>
                <span>状态：{{ getStatusText(processMeta.status || selectedWarningRow?.status) }}</span>
              </div>
            </div>

            <div class="process-stats">
              <div class="stat-box">
                <div class="stat-box-label">总处置数</div>
                <div class="stat-box-value">{{ processStatistics.totalDisposals || 0 }}</div>
              </div>
              <div class="stat-box">
                <div class="stat-box-label">当前状态</div>
                <div class="stat-box-value small">{{ getStatusText(processMeta.status || selectedWarningRow?.status) }}</div>
              </div>
            </div>

            <div class="process-roadmap">
              <div
                v-for="(node, index) in processNodes"
                :key="node.id || index"
                class="road-node"
                :class="node.status"
              >
                <div class="road-dot"></div>
                <div class="road-name">{{ node.name }}</div>
                <div class="road-time">{{ node.disposalTime || "" }}</div>
                <div class="road-user">{{ node.disposalUser || "" }}</div>
                <div v-if="index < processNodes.length - 1" class="road-line"></div>
              </div>
            </div>

            <el-divider content-position="left">流程记录</el-divider>
            <el-timeline>
              <el-timeline-item
                v-for="item in processList"
                :key="item.disposalId"
                :timestamp="item.createTime || '-'"
                :type="getTimelineType(item.disposalType)"
              >
                <div class="timeline-title">{{ getProcessTypeText(item.disposalType) }}</div>
                <div>{{ item.disposalContent || "-" }}</div>
                <div class="timeline-sub">处置人：{{ item.disposalUser || "-" }}</div>
              </el-timeline-item>
            </el-timeline>
          </template>
        </el-card>
      </el-col>
    </el-row>

    <el-drawer v-model="detailVisible" title="预警详情" size="820px" append-to-body direction="rtl" class="detail-drawer">
      <template v-if="detailData.basicInfo">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="预警名称">{{ detailBasic.warningName || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警编号">{{ detailBasic.warningNo || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警类型">{{ detailBasic.warningTypeText || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警级别">{{ detailBasic.warningLevelText || "-" }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ getStatusText(detailBasic.status) }}</el-descriptions-item>
          <el-descriptions-item label="发布人">{{ detailBasic.publisher || "-" }}</el-descriptions-item>
          <el-descriptions-item label="处置人">{{ detailBasic.handler || "-" }}</el-descriptions-item>
          <el-descriptions-item label="权属单位">{{ detailBasic.ownershipUnit || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警位置" :span="2">{{ detailBasic.location || "-" }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ detailBasic.publishTime || "-" }}</el-descriptions-item>
          <el-descriptions-item label="GIS定位">{{ detailGis.longitude || "-" }} / {{ detailGis.latitude || "-" }}</el-descriptions-item>
          <el-descriptions-item label="预警内容" :span="2">{{ detailBasic.warningContent || "-" }}</el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">流程处置信息</el-divider>
        <el-timeline v-if="(detailData.disposalHistory || []).length">
          <el-timeline-item
            v-for="(item, index) in detailData.disposalHistory"
            :key="index"
            :timestamp="item.createTime || item.disposalTime || '-'"
          >
            {{ item.disposalContent || item.content || "-" }}
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无流程处置信息" />

        <el-divider content-position="left">电子存档信息</el-divider>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="存档状态">{{ detailArchive.archiveStatus || detailArchive.status || "暂无电子存档" }}</el-descriptions-item>
          <el-descriptions-item label="存档编号">{{ detailArchive.archiveNo || "-" }}</el-descriptions-item>
          <el-descriptions-item label="存档说明">{{ detailArchive.remark || "-" }}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import {
  getAlertTypeDictionaryData,
  getWarningCompletedListData,
  getWarningDetailData,
  getWarningDiagramData,
  getWarningProcessData,
  getWarningProcessStatisticsData,
  getWarningProcessingListData,
  getdbyjlistData
} from "@/api/smxyjldczxt/yjxxfb/yjfb.js";

const loading = ref(false);
const warningList = ref([]);
const total = ref(0);
const warningTypeOptions = ref([]);
const warningLevelOptions = ref([]);

const processingList = ref([]);
const completedList = ref([]);
const processingTotal = ref(0);
const completedTotal = ref(0);
const trackTab = ref("processing");

const selectedWarningId = ref("");
const selectedWarningRow = ref(null);
const processList = ref([]);
const processStatistics = ref({});
const processDiagram = ref({});

const detailVisible = ref(false);
const detailData = ref({});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  warningName: "",
  warningNo: "",
  warningType: "",
  warningLevel: "",
  status: "",
  location: "",
  publisher: "",
  ownershipUnit: "",
  dateRange: []
});

const warningTypeLabelMap = computed(() => {
  return warningTypeOptions.value.reduce((acc, item) => {
    acc[item.dictValue] = item.dictLabel;
    return acc;
  }, {});
});

const warningLevelLabelMap = computed(() => {
  return warningLevelOptions.value.reduce((acc, item) => {
    acc[item.dictValue] = item.dictLabel;
    return acc;
  }, {});
});

const trackList = computed(() => (trackTab.value === "processing" ? processingList.value : completedList.value));
const processNodes = computed(() => processDiagram.value.nodes || []);
const processMeta = computed(() => ({
  warningName: processDiagram.value.warningName || "",
  warningNo: processDiagram.value.warningNo || "",
  status: processDiagram.value.status || ""
}));

const detailBasic = computed(() => {
  const basic = detailData.value.basicInfo || {};
  const warningType = basic.warningType || basic.warning_type || "";
  const warningLevel = basic.warningLevel || basic.warning_level || "";
  return {
    warningName: basic.warningName || basic.warning_name || "",
    warningNo: basic.warningNo || basic.warning_no || "",
    warningTypeText: warningTypeLabelMap.value[warningType] || warningType || "-",
    warningLevelText: warningLevelLabelMap.value[warningLevel] || warningLevel || "-",
    status: basic.status || "",
    publisher: basic.publisher || "",
    handler: basic.handler || "",
    ownershipUnit: basic.ownershipUnit || basic.ownership_unit || "",
    location: basic.location || "",
    publishTime: basic.publishTime || basic.publish_time || "",
    warningContent: basic.warningContent || basic.warning_content || ""
  };
});

const detailGis = computed(() => detailData.value.gisLocation || {});
const detailArchive = computed(() => detailData.value.electronicArchive || {});

function getLevelTagType(level) {
  return {
    "1": "danger",
    "2": "warning",
    "3": "success",
    "4": "info"
  }[level] || "info";
}

function getStatusText(status) {
  return {
    DRAFT: "草稿",
    RELEASED: "已发布",
    PENDING: "待处理",
    PROCESSING: "处理中",
    HANDLED: "已处理",
    CLOSED: "已解除",
    RETURNED: "已退回"
  }[status] || status || "-";
}

function getStatusTagType(status) {
  return {
    DRAFT: "info",
    RELEASED: "success",
    PENDING: "warning",
    PROCESSING: "warning",
    HANDLED: "success",
    CLOSED: "",
    RETURNED: "danger"
  }[status] || "";
}

function getProcessTypeText(type) {
  return {
    RELEASE: "发布预警",
    UPGRADE: "升级预警",
    RESOLVE: "解除预警",
    RETURN: "退回重办",
    SUPERVISION: "预警督办",
    INSTRUCTION: "领导批示"
  }[type] || type || "-";
}

function getTimelineType(type) {
  return {
    RELEASE: "primary",
    UPGRADE: "warning",
    RESOLVE: "success",
    RETURN: "danger",
    SUPERVISION: "primary",
    INSTRUCTION: "info"
  }[type] || "primary";
}

function normalizeWarningRow(item) {
  const warningType = item.warningType || item.warning_type || "";
  const warningLevel = item.warningLevel || item.warning_level || "";
  return {
    warningId: item.warningId || item.warning_id,
    warningName: item.warningName || item.warning_name || "",
    warningNo: item.warningNo || item.warning_no || "",
    warningType,
    warningTypeText: warningTypeLabelMap.value[warningType] || warningType || "-",
    warningLevel,
    warningLevelText: warningLevelLabelMap.value[warningLevel] || warningLevel || "-",
    status: item.status || "",
    location: item.location || "",
    publisher: item.publisher || "",
    ownershipUnit: item.ownershipUnit || item.ownership_unit || "",
    publishTime: item.publishTime || item.publish_time || "",
    handler: item.handler || ""
  };
}

async function loadDicts() {
  const [typeRes, levelRes] = await Promise.all([
    getAlertTypeDictionaryData({ dictType: "warning_type" }),
    getAlertTypeDictionaryData({ dictType: "warning_level" })
  ]);
  warningTypeOptions.value = typeRes.rows || [];
  warningLevelOptions.value = levelRes.rows || [];
}

async function loadWarnings() {
  loading.value = true;
  try {
    const res = await getdbyjlistData({
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize,
      warningName: queryParams.warningName || undefined,
      warningNo: queryParams.warningNo || undefined,
      warningType: queryParams.warningType || undefined,
      warningLevel: queryParams.warningLevel || undefined,
      status: queryParams.status || undefined,
      location: queryParams.location || undefined,
      publisher: queryParams.publisher || undefined,
      ownershipUnit: queryParams.ownershipUnit || undefined,
      startTime: queryParams.dateRange?.[0] || undefined,
      endTime: queryParams.dateRange?.[1] || undefined
    });
    warningList.value = (res.data?.records || []).map(normalizeWarningRow);
    total.value = res.data?.total || 0;
  } finally {
    loading.value = false;
  }
}

async function loadTrackList() {
  const params = {
    pageNum: 1,
    pageSize: 50,
    warningType: queryParams.warningType || undefined,
    warningLevel: queryParams.warningLevel || undefined,
    startTime: queryParams.dateRange?.[0] || undefined,
    endTime: queryParams.dateRange?.[1] || undefined
  };
  const [processingRes, completedRes] = await Promise.all([
    getWarningProcessingListData({
      pageNum: 1,
      pageSize: 50,
      warningType: params.warningType,
      warningLevel: params.warningLevel
    }),
    getWarningCompletedListData(params)
  ]);
  processingList.value = (processingRes.data?.records || []).map(normalizeWarningRow);
  processingTotal.value = processingRes.data?.total || 0;
  completedList.value = (completedRes.data?.records || []).map(normalizeWarningRow);
  completedTotal.value = completedRes.data?.total || 0;
}

async function loadProcessData(warningId) {
  if (!warningId) return;
  const [processRes, statisticsRes, diagramRes] = await Promise.all([
    getWarningProcessData(warningId),
    getWarningProcessStatisticsData(warningId),
    getWarningDiagramData(warningId)
  ]);
  processList.value = processRes.data || [];
  processStatistics.value = statisticsRes.data || {};
  processDiagram.value = diagramRes.data || {};
}

async function openDetail(row) {
  const res = await getWarningDetailData(row.warningId);
  detailData.value = res.data || {};
  detailVisible.value = true;
}

async function handleSelectWarning(row) {
  selectedWarningId.value = row.warningId;
  selectedWarningRow.value = row;
  await loadProcessData(row.warningId);
}

async function handleSelectWarningFromTrack(row) {
  await handleSelectWarning(row);
}

function handleQuery() {
  queryParams.pageNum = 1;
  reloadAll();
}

function resetQuery() {
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.warningName = "";
  queryParams.warningNo = "";
  queryParams.warningType = "";
  queryParams.warningLevel = "";
  queryParams.status = "";
  queryParams.location = "";
  queryParams.publisher = "";
  queryParams.ownershipUnit = "";
  queryParams.dateRange = [];
  reloadAll();
}

async function reloadAll() {
  await Promise.all([loadWarnings(), loadTrackList()]);
  if (warningList.value.length && !selectedWarningId.value) {
    await handleSelectWarning(warningList.value[0]);
  } else if (selectedWarningId.value) {
    await loadProcessData(selectedWarningId.value);
  }
}

onMounted(async () => {
  await loadDicts();
  await reloadAll();
});
</script>

<style scoped>
.warning-query-page {
  background: #f5f7fb;
}

.page-card {
  border-radius: 16px;
  margin-bottom: 16px;
}

.header-card {
  background: linear-gradient(135deg, #eff6ff, #f8fbff);
  border: 1px solid #dbeafe;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.page-title {
  font-size: 22px;
  font-weight: 700;
  color: #1e3a8a;
}

.page-subtitle {
  margin-top: 8px;
  font-size: 13px;
  color: #64748b;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.summary-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.summary-card {
  border: none;
  color: #fff;
}

.summary-card :deep(.el-card__body) {
  padding: 20px;
}

.summary-card.primary {
  background: linear-gradient(135deg, #2563eb, #5b93ff);
}

.summary-card.warning {
  background: linear-gradient(135deg, #d97706, #f7b955);
}

.summary-card.success {
  background: linear-gradient(135deg, #059669, #34d399);
}

.summary-label {
  font-size: 14px;
}

.summary-value {
  margin: 8px 0 10px;
  font-size: 30px;
  font-weight: 700;
}

.summary-desc {
  font-size: 12px;
  opacity: 0.9;
}

.track-card,
.process-card {
  min-height: 560px;
}

.selected-info {
  margin-bottom: 14px;
}

.selected-name {
  font-size: 16px;
  font-weight: 700;
  color: #111827;
}

.selected-meta {
  margin-top: 8px;
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
  font-size: 13px;
  color: #6b7280;
}

.process-stats {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.stat-box {
  padding: 14px 16px;
  border-radius: 12px;
  background: #f8fafc;
  border: 1px solid #edf2f7;
}

.stat-box-label {
  font-size: 13px;
  color: #64748b;
}

.stat-box-value {
  margin-top: 8px;
  font-size: 26px;
  font-weight: 700;
  color: #111827;
}

.stat-box-value.small {
  font-size: 20px;
}

.process-roadmap {
  display: flex;
  overflow-x: auto;
  padding: 10px 0 18px;
  margin-bottom: 8px;
}

.road-node {
  position: relative;
  min-width: 150px;
  padding-right: 28px;
  flex-shrink: 0;
}

.road-dot {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #94a3b8;
  border: 4px solid #e2e8f0;
}

.road-node.completed .road-dot {
  background: #10b981;
}

.road-node.active .road-dot {
  background: #f59e0b;
}

.road-node.waiting .road-dot {
  background: #cbd5e1;
}

.road-name {
  margin-top: 10px;
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.road-time,
.road-user,
.timeline-sub {
  margin-top: 4px;
  font-size: 12px;
  color: #6b7280;
}

.road-line {
  position: absolute;
  top: 8px;
  left: 24px;
  width: calc(100% - 32px);
  height: 2px;
  background: #dbeafe;
}

.timeline-title {
  font-weight: 600;
  color: #111827;
}

@media (max-width: 1200px) {
  .summary-grid {
    grid-template-columns: 1fr;
  }
}
</style>
