<template>
  <div class="content-management-system">
    <!-- 查询条件区域 -->
    <el-card class="filter-card">
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="filter-form">
        <el-form-item label="内容ID">
          <el-input v-model="queryParams.contentId" placeholder="请输入内容ID" clearable />
        </el-form-item>

        <el-form-item label="内容类型">
          <el-select v-model="queryParams.contentType" placeholder="请选择内容类型" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="紧急通知" value="EMERGENCY" />
            <el-option label="日常通知" value="NORMAL" />
            <el-option label="背景音乐" value="MUSIC" />
            <el-option label="寻呼" value="PAGING" />
            <el-option label="演练" value="DRILL" />
          </el-select>
        </el-form-item>

        <el-form-item label="播放分区">
          <el-select v-model="queryParams.playZone" placeholder="请选择播放分区" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="全区" value="ZONE-ALL" />
            <el-option label="分区1" value="ZONE-001" />
            <el-option label="分区2" value="ZONE-002" />
            <el-option label="分区3" value="ZONE-003" />
            <el-option label="分区4" value="ZONE-004" />
          </el-select>
        </el-form-item>

        <el-form-item label="告警级别">
          <el-select v-model="queryParams.alarmLevel" placeholder="请选择告警级别" style="width: 180px;">
            <el-option label="全部" value="" />
            <el-option label="无告警" value="NONE" />
            <el-option label="低" value="LOW" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="高" value="HIGH" />
          </el-select>
        </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 class="data-table">
      <el-table :data="contentList" border v-loading="loading">
        <el-table-column label="内容ID" prop="contentId" align="center" width="120" />
        <el-table-column label="内容类型" prop="contentType" align="center" width="120">
          <template #default="scope">
            {{ getContentTypeName(scope.row.contentType) }}
          </template>
        </el-table-column>
        <el-table-column label="音频路径" prop="audioPath" align="left" min-width="200">
          <template #default="scope">
<!--            <el-link :href="scope.row.audioPath" type="primary" target="_blank">查看</el-link>-->
            <span>{{ scope.row.audioPath }}</span>
          </template>
        </el-table-column>
        <el-table-column label="播放分区" prop="playZones" align="center">
          <template #default="scope">
            {{ formatZones(scope.row.playZones) }}
          </template>
        </el-table-column>
        <el-table-column label="播放进度" prop="progress" align="center" width="120">
          <template #default="scope">
            <el-progress :percentage="parseInt(scope.row.progress)" :color="getProgressColor(scope.row.progress)" />
          </template>
        </el-table-column>
        <el-table-column label="分区状态" prop="zoneStatusMatrix" align="center" width="150">
          <template #default="scope">
            <span>{{ scope.row.zoneStatusMatrix.split('/')[0] }}台设备</span>
            <span v-if="parseInt(scope.row.zoneStatusMatrix.split('/')[1]) > 0" class="text-danger ml-2">
              {{ scope.row.zoneStatusMatrix.split('/')[1] }}台故障
            </span>
          </template>
        </el-table-column>
        <el-table-column label="告警级别" prop="alarmLevel" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getAlarmLevelType(scope.row.alarmLevel)">{{ getAlarmLevelName(scope.row.alarmLevel) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="触发时间" prop="triggerTime" align="center" width="180" />
        <el-table-column label="CPU负载" prop="cpuLoad" align="right" width="100">
          <template #default="scope">
            <span>{{ scope.row.cpuLoad }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="网络延迟" prop="networkLatency" align="right" width="100">
          <template #default="scope">
            <span>{{ scope.row.networkLatency }}ms</span>
          </template>
        </el-table-column>
        <el-table-column label="存储空间" prop="storageUsage" align="right" width="100">
          <template #default="scope">
            <span>{{ scope.row.storageUsage }}%</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import {getBroadcastDataGenerator} from "@/api/publicBroadcasting/publicBroadcasting";

// 查询参数
const queryParams = reactive({
  contentId: '',
  contentType: '',
  playZone: '',
  alarmLevel: '',
  pageNum: 1,
  pageSize: 10,
  interfaceName: "广播内容与状态看板"
});

// 表格数据
const contentList = ref([]);
const total = ref(0);
const loading = ref(false);
const detailDialogVisible = ref(false);
const detailContent = ref({});

// 获取数据列表
const getList = async () => {
  loading.value = true;
  try {
    let response = await getBroadcastDataGenerator(queryParams);

    // 处理返回数据
    let filteredData = [];

    // 内容ID过滤
    if (queryParams.contentId) {
      filteredData = filteredData.filter(item =>
          (item.contentId || '').includes(queryParams.contentId) // 新增空值处理
      );
    }

    // 内容类型过滤
    if (queryParams.contentType) {
      filteredData = filteredData.filter(item =>
          item.contentType === queryParams.contentType
      );
    }

    // 播放分区过滤（关键修复点）
    if (queryParams.playZone) {
      filteredData = filteredData.filter(item => {
        // 处理 playZones 可能为 undefined/null/数组的情况
        const playZones = item.playZones || ''; // 设默认空字符串
        const targetZone = queryParams.playZone;

        // 如果是数组，转为字符串
        if (Array.isArray(playZones)) {
          return playZones.includes(targetZone);
        } else {
          return playZones.includes(targetZone);
        }
      });
    }

    // 告警级别过滤
    if (queryParams.alarmLevel) {
      filteredData = filteredData.filter(item =>
          item.alarmLevel === queryParams.alarmLevel
      );
    }

    // 处理分页
    if (response.data && response.data.list) {
      // 使用后端分页数据
      contentList.value = [];
      total.value = 0;
    } else {
      // 手动分页（模拟数据）
      total.value = filteredData.length;
      const start = (queryParams.pageNum - 1) * queryParams.pageSize;
      const end = start + queryParams.pageSize;
      contentList.value = filteredData.slice(start, end);
    }
  } catch (error) {
    console.error('获取内容列表失败', error);
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleQuery = () => {
  queryParams.pageNum = 1; // 重置页码
  getList();
};

// 重置方法
const resetQuery = () => {
  queryParams.contentId = '';
  queryParams.contentType = '';
  queryParams.playZone = '';
  queryParams.alarmLevel = '';
  handleQuery();
};

// 分页事件处理
const handlePageChange = (newPage) => {
  queryParams.pageNum = newPage;
  getList();
};

const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize;
  queryParams.pageNum = 1; // 重置页码
  getList();
};

// 格式化分区显示
const formatZones = (zones) => {
  if (!zones) return '-';
  if (zones === 'ZONE-ALL') return '全区';

  const zoneMap = {
    'ZONE-001': '分区1',
    'ZONE-002': '分区2',
    'ZONE-003': '分区3',
    'ZONE-004': '分区4'
  };

  return zones.split(',').map(zone => zoneMap[zone] || zone).join('、');
};

// 获取内容类型名称
const getContentTypeName = (type) => {
  const typeMap = {
    'EMERGENCY': '紧急通知',
    'NORMAL': '日常通知',
    'MUSIC': '背景音乐',
    'PAGING': '寻呼',
    'DRILL': '演练'
  };
  return typeMap[type] || type;
};

// 获取告警级别名称
const getAlarmLevelName = (level) => {
  const levelMap = {
    'NONE': '无告警',
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高'
  };
  return levelMap[level] || level;
};

// 获取告警级别标签类型
const getAlarmLevelType = (level) => {
  const typeMap = {
    'NONE': 'success',
    'LOW': 'info',
    'MEDIUM': 'warning',
    'HIGH': 'danger'
  };
  return typeMap[level] || '';
};

// 获取进度条颜色
const getProgressColor = (progress) => {
  const value = parseInt(progress);
  if (value === 100) return '#52c41a'; // 完成
  if (value === 0) return '#f5222d'; // 未开始
  return '#1890ff'; // 进行中
};

// 查看详情
const showDetail = (row) => {
  detailContent.value = row;
  detailDialogVisible.value = true;
};


// 初始化加载
getList();
</script>

<style scoped>
.filter-card {
  margin-bottom: 20px;
}

.data-table {
  min-height: 400px;
}

.text-danger {
  color: #f5222d;
}

.ml-2 {
  margin-left: 8px;
}
</style>
