<template>
  <div class="wrapper">
    <h2 class="card-title">今日报警信息</h2>
    <div class="alarm-tabs">
      <div 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{ active: activeTab === index }"
        @click="handleTabChange(index)"
      >
        {{ tab.name }}({{ tab.count }})
      </div>
    </div>
    
    <!-- SOS报警列表 -->
    <div v-show="activeTab === 0" class="list-container">
      <dl class="alarm-list">
        <dt class="list-header">
          <span>人员姓名</span>
          <span>定位卡号</span>
          <span>报警时间</span>
        </dt>
      </dl>
      <div class="scroll-wrapper" ref="sosScrollWrapper">
        <dl class="alarm-list">
          <template v-if="sosData.length > 0">
            <template v-for="(item, index) in sosData" :key="index">
              <dd class="list-item" :class="getItemClass(item)">
                <span>{{ item.realName }}</span>
                <span>{{ item.cardId }}</span>
                <span class="time-cell">
                  <div class="date-part">{{ item.alarmTime?.split(' ')[0] }}</div>
                  <div class="time-part">{{ item.alarmTime?.split(' ')[1] }}</div>
                </span>
              </dd>
            </template>
          </template>
          <!-- <template v-else>
            <dd class="no-data">暂无数据</dd>
          </template> -->
        </dl>
      </div>
    </div>
    
    <!-- 车辆报警列表 -->
    <div v-show="activeTab === 1" class="list-container">
      <dl class="alarm-list">
        <dt class="list-header">
          <span>车辆/司机名称</span>
          <span>车牌号</span>
          <span>报警类型</span>
          <span>报警时间</span>
        </dt>
      </dl>
      <div class="scroll-wrapper" ref="vehicleScrollWrapper">
        <dl class="alarm-list">
          <template v-if="vehicleData.length > 0">
            <template v-for="(item, index) in vehicleData" :key="index">
              <dd class="list-item" :class="getItemClass(item)">
                <span>{{ item.driver }}</span>
                <span>{{ item.licensePlate }}</span>
                <span>{{ item.alarmType }}</span>
                <span class="time-cell">
                  <div class="date-part">{{ item.alarmTime?.split(' ')[0] }}</div>
                  <div class="time-part">{{ item.alarmTime?.split(' ')[1] }}</div>
                </span>
              </dd>
            </template>
          </template>
          <!-- <template v-else>
            <dd class="no-data">暂无数据</dd>
          </template> -->
        </dl>
      </div>
    </div>
    
    <!-- 越界开采列表 -->
    <div v-show="activeTab === 2" class="list-container">
      <dl class="alarm-list">
        <dt class="list-header">
          <span>人员/车辆名称</span>
          <span>定位卡号/车牌号</span>
          <span>越界时间</span>
        </dt>
      </dl>
      <div class="scroll-wrapper" ref="boundaryScrollWrapper">
        <dl class="alarm-list">
          <template v-if="boundaryData.length > 0">
            <template v-for="(item, index) in boundaryData" :key="index">
              <dd class="list-item" :class="getItemClass(item)">
                <span>{{ item.driver }}</span>
                <span>{{ item.licensePlate }}</span>
                <span class="time-cell">
                  <div class="date-part">{{ item.boundaryTime?.split(' ')[0] }}</div>
                  <div class="time-part">{{ item.boundaryTime?.split(' ')[1] }}</div>
                </span>
              </dd>
            </template>
          </template>
          <!-- <template v-else>
            <dd class="no-data">暂无数据</dd>
          </template> -->
        </dl>
      </div>
    </div>
    
    <!-- 在线监测列表 -->
    <div v-show="activeTab === 3" class="list-container">
      <dl class="alarm-list">
        <dt class="list-header">
          <span>设备名称</span>
          <span>监测值</span>
          <span>报警级别</span>
          <span>报警时间</span>
        </dt>
      </dl>
      <div class="scroll-wrapper" ref="monitorScrollWrapper">
        <dl class="alarm-list">
          <template v-if="monitorData.length > 0">
            <template v-for="(item, index) in monitorData" :key="index">
              <dd class="list-item" :class="getItemClass(item)">
                <span>{{ item.equipname }}</span>
                <span>{{ item.value +''}}{{ item.unit }}</span>
                <span>{{ item.alarmlevel }}</span>
                <span class="time-cell">
                  <div class="date-part">{{ item.time?.split(' ')[0] }}</div>
                  <div class="time-part">{{ item.time?.split(' ')[1] }}</div>
                </span>
              </dd>
            </template>
          </template>
          <!-- <template v-else>
            <dd class="no-data">暂无数据</dd>
          </template> -->
        </dl>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, computed, watch, nextTick } from 'vue'
import { getSosList, getCarAlarmList, getFenceLogList, getOnlineAlarmList } from '@/api/index-dp';
import {
  useMessage
} from 'naive-ui';

const message = useMessage();

// 激活的tab索引
const activeTab = ref(0)

// 滚动相关的引用
const sosScrollWrapper = ref(null)
const vehicleScrollWrapper = ref(null)
const boundaryScrollWrapper = ref(null)
const monitorScrollWrapper = ref(null)

// 滚动定时器
let scrollTimer = null

// SOS报警数据
const sosData = ref([])

// 车辆报警数据
const vehicleData = ref([])

// 越界开采数据
const boundaryData = ref([])

// 在线监测数据
const monitorData = ref([])

const fetchSosData = async () => {
  const response = await getSosList();
  console.log(response, 'SOS报警列表')
  
  if (response.data.code == 200) {
    sosData.value = response.data.data || []
  } else {
    message.error(response.data.msg)
  }
}

const fetchvehicleData = async () => {
  const response = await getCarAlarmList();
  if (response.data.code == 200) {
    vehicleData.value = response.data.data
  } else {
    message.error(response.data.msg)
  }
}

const fetchFenceData = async () => {
  const response = await getFenceLogList();
  if (response.data.code == 200) {
    boundaryData.value = response.data.data
  } else {
    message.error(response.data.msg)
  }
}

const fetchMonitorData = async () => {
  const response = await getOnlineAlarmList();
  if (response.data.code == 200) {
    console.log(response.data.data, '在线监测列表')
    monitorData.value = response.data.data
  } else {
    message.error(response.data.msg)
  }
}

// 定义tabs 使用computed使其具有响应性
const tabs = computed(() => [
  { name: 'SOS报警', count: sosData.value.length },
  { name: '车辆报警', count: vehicleData.value.length },
  { name: '越界开采', count: boundaryData.value.length }, 
  { name: '在线监测', count: monitorData.value.length }
])

// 根据status获取对应的class
const getItemClass = (item) => {
  if (item.alarmlevel === '橙色预警') {
    return 'status-chengse'
  } else if (item.alarmlevel === '蓝色预警') {
    return 'status-lanse'
  } else if (item.alarmlevel === '黄色预警') {
    return 'status-huangse'
  } else if (item.alarmlevel === '红色预警') {
    return 'status-hongse'
  }
  return ''
}

// 初始化滚动
const initScroll = () => {
  // 清除之前的定时器
  if (scrollTimer) {
    clearInterval(scrollTimer)
    scrollTimer = null
  }
  
  // 获取当前激活的滚动容器
  let wrapper = null
  switch(activeTab.value) {
    case 0:
      wrapper = sosScrollWrapper.value
      break
    case 1:
      wrapper = vehicleScrollWrapper.value
      break
    case 2:
      wrapper = boundaryScrollWrapper.value
      break
    case 3:
      wrapper = monitorScrollWrapper.value
      break
  }
  
  // 如果没有数据或容器不存在，则不启动滚动
  if (!wrapper || wrapper.scrollHeight <= wrapper.clientHeight) {
    console.log("不满足滚动条件：wrapper存在?", !!wrapper, "scrollHeight:", wrapper ? wrapper.scrollHeight : "N/A", "clientHeight:", wrapper ? wrapper.clientHeight : "N/A")
    return
  }
  
  console.log("开始滚动，容器:", wrapper, "scrollHeight:", wrapper.scrollHeight, "clientHeight:", wrapper.clientHeight)
  
  // 设置初始滚动方向为向下
  let direction = 1
  const step = 1
  
  // 启动自动滚动
  scrollTimer = setInterval(() => {
    // 确保元素仍然存在
    if (!wrapper) {
      clearInterval(scrollTimer)
      return
    }
    
    // 计算新的滚动位置
    const newScrollTop = wrapper.scrollTop + (step * direction)
    
    // 判断是否到达顶部或底部
    if (newScrollTop <= 0) {
      // 到达顶部，改变方向向下
      direction = 1
      wrapper.scrollTop = 1
    } else if (newScrollTop >= wrapper.scrollHeight - wrapper.clientHeight) {
      // 到达底部，改变方向向上
      direction = -1
      wrapper.scrollTop = wrapper.scrollHeight - wrapper.clientHeight - 1
    } else {
      // 正常滚动
      wrapper.scrollTop = newScrollTop
    }
  }, 50)
}

// 当tab切换时重新初始化滚动
const handleTabChange = (index) => {
  activeTab.value = index
  // 延迟执行以确保DOM更新完成
  nextTick(() => {
    initScroll()
  })
}

// 监听数据变化，重新初始化滚动
watch([sosData, vehicleData, boundaryData, monitorData], () => {
  nextTick(() => {
    initScroll()
  })
})

// 组件挂载时初始化滚动
onMounted(() => {
  fetchSosData()
  fetchvehicleData()
  fetchFenceData()
  fetchMonitorData()
})

// 组件卸载前清除定时器
onBeforeUnmount(() => {
  if (scrollTimer) {
    clearInterval(scrollTimer)
  }
})
</script>

<style scoped lang="scss">
.wrapper {
  overflow: visible;
  width: 4.6rem;
  height: 3rem;
  position: relative;
  padding: 0.15rem;
  background-size: contain;
  width: 100%;
  margin-top: 0.3rem;
  background-image: url("@/assets/jinrun/module-bg.png");
  background-size: cover;
  background-repeat: no-repeat;
  margin-top: .26rem;
  
  .card-title {
    position: absolute;
    left: 0.25rem;
    top: -0.15rem;
    font-weight: 500;
    font-size: 0.2rem;
    color: #ffffff;
    text-shadow: 0rem 0rem 0rem rgba(5, 38, 68, 0.5);
  }
}

.alarm-tabs {
  width: 4.5rem;
  display: flex;
  gap: 0.05rem;
  margin-top: 0.18rem;
  margin-bottom: 0.15rem;
  flex-wrap: wrap;
  color: #fff;
}

.tab-item {
  padding: 0.05rem 0.1rem;
  background: transparent;
  cursor: pointer;
  position: relative;
  font-weight: 400;
  font-size: 0.16rem;
  color: #88DBBD;
  padding-right: 0rem;
  
  &.active {
    color: #05FFA4;
    
    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 80%;
      height: 0.02rem;
      background-color: #36a2eb;
    }
  }
}

.list-container {
  height: 2.2rem;
  overflow: hidden;
  margin-top: .2rem;
}

.alarm-list {
  margin: 0;
  padding: 0;
}

.list-header {
  display: flex;
  justify-content: space-between;
  padding: 0.1rem;
  // background: rgba(10, 25, 71, 0.8);
  background-image: url("@/assets/jinrun/table-header-bg.png");
  background-repeat: no-repeat;
  
  span {
    font-weight: 500;
    font-size: 0.14rem;
    color: #36F3FF;
    flex: 1;
    text-align: center;
    
    &:first-child {
      text-align: left;
    }
    
    &:last-child {
      text-align: right;
    }
  }
}

.scroll-wrapper {
  height: calc(100% - 0.45rem); /* 减去header的高度 */
  overflow-y: auto;
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE 10+ */
  
  &::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
}

.list-item {
  display: flex;
  justify-content: space-between;
  padding: 0.1rem;
  margin-bottom: 0.05rem;
  margin-top: .13rem;
  background-color: #2a496d78;
  
  span {
    font-size: 0.14rem;
    color: #fff;
    flex: 1;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    align-items: center;
    justify-content: center;
    &:first-child {
        justify-content: start;
    }
    &:nth-child(2){
      overflow: visible;
    }
    &:last-child {
      text-align: right;
    }
  }
  
  .time-cell {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    line-height: 1.2;
    
    .date-part, .time-part {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
    }
    .time-part{
      padding-right: .1rem;
    }
  }
  
  &.status-chengse {
    span {
      color: #FF852B;
    }
  }
  
  &.status-lanse {
    span {
      color: #28CAFF;
    }
  }
  
  &.status-huangse {
    span {
      color: #FFD118;
    }
  }
  
  &.status-hongse {
    span {
      color: #FF2C2C;
    }
  }
}

.no-data {
  text-align: center;
  color: #fff;
  padding: 0.2rem;
  background: rgba(10, 25, 71, 0.3);
  border-radius: 0.05rem;
  margin: 0.1rem;
}
</style>