<template>
  <div class="ai-analysis-home">
    <!-- 顶部搜索块 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="场站">
          <el-select v-model="searchForm.stationId" placeholder="全部" clearable style="width: 220px;">
            <el-option label="全部" value=""></el-option>
            <!-- 这里需要动态加载场站数据 -->
            <el-option 
              v-for="station in stationList" 
              :key="station.stationId" 
              :label="station.stationName" 
              :value="station.stationId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 四个卡片 -->
    <div class="cards-section">
      <div class="card-item">
        <div class="card-icon ai-monitor">
          <img :src="aiMonitorIcon" alt="AI监控图标" />
        </div>
        <div class="card-title">AI监控场站</div>
        <div class="card-value">{{ detectStatistics.stationCount || 0 }}个</div>
        <div class="card-percentage">占所有场站<span>{{ detectStatistics.stationRatio || 0 }}%</span></div>
      </div>
      <div class="card-item">
        <div class="card-icon camera">
          <img :src="cameraIcon" alt="摄像头图标" />
        </div>
        <div class="card-title">AI监控数量</div>
        <div class="card-value">{{ detectStatistics.cameraCount || 0 }}个</div>
        <div class="card-percentage">占所有设备<span>100%</span></div>
      </div>
      <div class="card-item">
        <div class="card-icon monitor-type">
          <img :src="monitorTypeIcon" alt="监测类型图标" />
        </div>
        <div class="card-title">监测类型数量</div>
        <div class="card-value">{{ detectStatistics.alertTypes || 0 }}个</div>
        <div class="card-percentage">覆盖所有类型</div>
      </div>
      <div class="card-item">
        <div class="card-icon ai-alert">
          <img :src="aiAlertIcon" alt="AI预警图标" />
        </div>
        <div class="card-title">AI预警总数</div>
        <div class="card-value">{{ warningStatistics.alertCount || 0 }}个</div>
        <div class="card-percentage">涉及预警类型<span>{{ warningStatistics.alertTypeCount || 0 }}个</span></div>
      </div>
    </div>

    <!-- 左右模块 -->
    <div class="main-section">
      <!-- 预警类型模块 -->
      <div class="left-module">
        <div class="module-title">预警类型</div>
        <div class="warning-types-list">
          <div 
            v-for="warning in warningStatistics" 
            :key="warning.alertType"
            class="warning-type-item"
          >
            <div class="warning-type-name">{{ warning.alertTypeName }}</div>
            <div class="warning-type-stats">
              <div class="warning-type-count">当前有 {{ warning.count || 0 }} 个预警未读</div>
              <div class="warning-type-month-count">本月共发生 {{ warning.monthCount || 0 }} 次</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 未处理预警记录模块 -->
      <div class="right-module">
        <div class="module-header">
          <div class="module-title" style="margin-bottom: 0;">未处理预警记录</div>
          <div class="view-all" @click="viewAllAlerts">查看全部</div>
        </div>
        <div class="alert-records-list">
          <div 
            v-for="alert in alertRecords" 
            :key="alert.alertId"
            class="alert-record-item">
            <div class="alert-image">
              <img :src="alert.snapshotPathUrl[0] || 'https://ts1.tc.mm.bing.net/th/id/R-C.8bbf769b39bb26eefb9b6de51c23851d?rik=crTnc5i8A%2b8p7A&riu=http%3a%2f%2fpicview.iituku.com%2fcontentm%2fzhuanji%2fimg%2f202207%2f09%2fe7196ac159f7cf2b.jpg%2fnu&ehk=DYPLVpoNAXLj5qzwgR5vHf9DladFh%2b34s4UcuP3Kn6E%3d&risl=&pid=ImgRaw&r=0'" alt="预警图片" />
            </div>
            <div class="alert-info">
              <div class="alert-title-row">
                <span class="alert-title">{{ alert.alertTypeName || '预警' }}</span>
                <span class="alert-time">{{ formatDate(alert.alertTime) }}</span>
              </div>
              <div class="alert-station-row">
                <span class="alert-station">{{ alert.stationName || '未知场站' }}</span>
              </div>
            </div>
            <div class="alert-arrow"  @click="viewAlertDetail(alert.alertId)">
              <img :src="angleRightIcon" alt="箭头图标" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { getDetectStatistics, getWarningStatistics, getSecurityAlertList } from '#/api/aiAnalysis/aiAnalysis';
import { selectAllSysStation } from '#/api/system/infoEntry/stationInfo/stationInfo';
import type { DetectStatisticsModel, WarningStatisticsModel, SecurityAlertModel } from '#/api/aiAnalysis/model';
import aiMonitorIcon from '#/assets/icon/ai-monitor.png';
import cameraIcon from '#/assets/icon/camera.png';
import monitorTypeIcon from '#/assets/icon/monitor-type.png';
import aiAlertIcon from '#/assets/icon/ai-alert.png'; 
import angleRightIcon from '#/assets/icon/angle-right-circle.png';
// 路由
const router = useRouter();

// 搜索表单
const searchForm = ref({
  stationId: ''
});

// 场站列表
const stationList = ref<any[]>([]);

// 检测统计数据
const detectStatistics = ref<DetectStatisticsModel>({});

// 预警分类统计数据
const warningStatistics = ref<WarningStatisticsModel[]>([]);

// 预警记录数据
const alertRecords = ref<(SecurityAlertModel & { alertTypeName?: string })[]>([]);

// 处理查询
const handleQuery = async () => {
  await fetchData();
};

// 处理重置
const handleReset = async () => {
  searchForm.value.stationId = '';
  await fetchData();
};

// 格式化日期
const formatDate = (dateStr?: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleString('zh-CN');
};

// 查看全部预警
const viewAllAlerts = () => {
  // 跳转到预警记录列表页面
  router.push('/aiAnalysis/warning');

};

// 查看预警详情
const viewAlertDetail = (alertId?: number) => {
  if (alertId) {
    router.push({
      name: 'WarningDetail',
      params: { alertId: alertId },
    }); 
  }
};

// 获取预警类型名称
const getAlertTypeName = (alertType?: string) => {
  const typeMap: Record<string, string> = {
    'fire': '火焰',
    'smoke': '烟雾',
    'fire_danger': '火灾',
    'intrusion': '入侵'
  };
  return typeMap[alertType || ''] || alertType;
};

// 获取场站列表
const fetchStationList = async () => {
  try {
    const resp = await selectAllSysStation();
    const data = resp || [];
    if (Array.isArray(data)) {
      stationList.value = data.map((item: any) => ({
        stationId: item.id,
        stationName: item.stationName
      }));
    }
  } catch (error) {
    console.error('获取场站列表失败:', error);
  }
};

// 获取数据
const fetchData = async () => {
  try {
    // 获取检测统计数据
    const detectRes = await getDetectStatistics();
    console.log('detectRes', detectRes);
    if (detectRes) {
      detectStatistics.value = detectRes || {};
    }

    // 获取预警分类统计数据
    const warningRes = await getWarningStatistics();
    console.log('warningRes', warningRes);
    if (warningRes) {
      warningStatistics.value = warningRes || [];
    }

    // 获取未处理预警记录
    const alertRes = await getSecurityAlertList({
      status: 'unhandled',
      stationId: searchForm.value.stationId,
      pageSize: 5
    });
    console.log('alertRes', alertRes);
    if (alertRes) {
      const alerts = alertRes || [];

      // 添加预警类型名称
      alertRecords.value = alerts.rows || [];
      alertRecords.value = alertRecords.value.map((alert: SecurityAlertModel) => ({
        ...alert,
        alertTypeName: getAlertTypeName(alert.alertType)
      }));
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

// 初始化
onMounted(async () => {
  // 获取场站列表
  await fetchStationList();
  await fetchData();
});
</script>

<style scoped>
.ai-analysis-home {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 搜索块 */
.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 12px;
  box-shadow: 0 2px 4px rgba(63, 50, 50, 0.1);
  
  :deep(.el-form-item) {
    margin-bottom: 0;
  }
}

/* 四个卡片 */
.cards-section {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-bottom: 12px;
}

.card-item {
  background-color: #fff;
  padding: 25px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(63, 50, 50, 0.1);
  text-align: left;
  transition: transform 0.3s ease;
}

.card-item:hover {
  transform: translateY(-5px);
}

.card-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background-color: #f0f9ff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #3b82f6;
  margin-bottom: 24px;
}
.card-icon img {
  width: 24px;
  height: 24px;
}
.card-icon.ai-monitor {
  background-color: #B5E4CA;
  color: #10b981;
}

.card-icon.camera {
  background-color: #BEDAFF;
  color: #f59e0b;
}

.card-icon.monitor-type {
  background-color: #FFE4BA;
  color: #ef4444;
}

.card-icon.ai-alert {
  background-color: #FDCDC5;
  color: #8b5cf6;
}

.card-title {
  color: var(--arco-e-668--light-text-color-text-2, #4E5969);
  font-family: "Alibaba PuHuiTi 2.0";
  font-size: 18px;
  font-style: normal;
  font-weight: 600;
  line-height: 16px; /* 88.889% */
  letter-spacing: -0.18px;
}

.card-value {
  color: var(--, #31373D);
  font-family: "Alibaba PuHuiTi 2.0";
  font-size: 48px;
  font-style: normal;
  font-weight: 600;
  line-height: 48px; /* 100% */
  letter-spacing: -1.44px;
  padding: 8px;
}

.card-percentage {
  color: #6F767E;
  font-family: "Alibaba PuHuiTi 2.0";
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 16px; /* 114.286% */
  letter-spacing: -0.14px;
}

.card-percentage span {
  color: var(--, #38B865);
  font-family: "Alibaba PuHuiTi 2.0";
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 16px;
  letter-spacing: -0.14px;
}
/* 主模块 */
.main-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.module-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 24px 0px;
  border-left: 4px solid #215ACD;
  padding-left: 20px;
}
/* 预警类型模块 */
.left-module {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 500px;
  display: flex;
  flex-direction: column;
}

.warning-types-list {
  flex: 1;
  overflow-y: auto;
}

.warning-type-item {
  display: flex;
  background-color: #F7F9FA;
  justify-content: space-between;
  align-items: center;
  padding: 25px;
  margin: 0 24px 12px 24px;
}

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

.warning-type-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.warning-type-stats {
  text-align: right;
  font-size: 12px;
  color: #666;
}

.warning-type-count {
  color: var(---B, #215ACD);
  font-family: "PingFang SC";
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 14px; /* 100% */
  letter-spacing: 0.56px;
}

.warning-type-month-count {
  color: var(--, #31373D);
  text-align: right;
  font-family: "PingFang SC";
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 14px; /* 100% */
  letter-spacing: 0.56px;
  margin-top: 8px;
}

.right-module {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  height: 500px;
  display: flex;
  flex-direction: column;
}

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

.view-all {
  font-size: 14px;
  color: #215ACD;
  cursor: pointer;
  margin-top: 24px;
  margin-right: 35px;
}

.view-all:hover {
  text-decoration: underline;
}

.alert-records-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex: 1;
  overflow-y: auto;
  margin: 0 24px;
}

.alert-record-item {
  display: flex;
  align-items: center;
  padding: 5px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.alert-record-item:hover {
  /* border-color: #3b82f6;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.1); */
}

.alert-image {
  width: 48px;
  height: 48px;
  margin-right: 12px;
  border-radius: 4px;
  overflow: hidden;
  margin: 20px 8px 20px 24px;
}

.alert-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.alert-info {
  flex: 1;
}

.alert-title-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.alert-title {
  color: var(--, #EB5E12);
  font-family: "PingFang SC";
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 14px; /* 100% */
  letter-spacing: 0.56px;
}

.alert-time {
  color: var(--, #31373D);
  font-family: "PingFang SC";
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 14px; /* 100% */
  letter-spacing: 0.56px;
  margin-left: 10px;
}

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

.alert-station {
  color: var(--, #31373D);
  font-family: "PingFang SC";
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 14px; /* 100% */
  letter-spacing: 0.56px;

}

.alert-status {
  font-size: 12px;
  color: #ef4444;
  font-weight: 500;
}

.alert-arrow {
  width: 24px;
  height: 24px;
  margin-right: 24px;
}

/* 滚动条样式 */
.warning-types-list::-webkit-scrollbar,
.alert-records-list::-webkit-scrollbar {
  width: 6px;
}

.warning-types-list::-webkit-scrollbar-track,
.alert-records-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.warning-types-list::-webkit-scrollbar-thumb,
.alert-records-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.warning-types-list::-webkit-scrollbar-thumb:hover,
.alert-records-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .cards-section {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .main-section {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .cards-section {
    grid-template-columns: 1fr;
  }
  
  .search-section {
    padding: 16px;
  }
  
  .card-item {
    padding: 16px;
  }
  
  .right-module {
    padding: 16px;
  }
}
</style>
