<template>
    <div class="wrapper">
      <h2 class="card-title">在线监测实时数据</h2>
        <!-- SOS报警列表 -->

        <div 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="tableData.length > 0">
                        <template v-for="(item, index) in tableData" :key="index">
                            <dd class="list-item" :class="getItemClass(item)">
                                <span>{{ item.sensorname }}</span>
                                <span class="value-cell">
                                    <div class="xy-value">{{ getXYValue(item.value) }}</div>
                                    <div class="z-value">{{ getZValue(item.value) }}{{ item.danwei }}</div>
                                </span>
                                <span class="time-cell">
                                    <div class="date-part">{{ item.time.split(' ')[0] }}</div>
                                    <div class="time-part">{{ item.time.split(' ')[1] }}</div>
                                </span>
                                <span>{{ item.state == 1 ? '报警' : '正常' }}</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, nextTick } from 'vue'
import { getOnlineData } from '@/api/index-dp';

import {
 useMessage
} from 'naive-ui';

const message = useMessage();

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

// 滚动定时器
let scrollTimer = null

// 根据status获取对应的class
const getItemClass = (item) => {
  if (item.state == 1) {
    return 'status-hongse'
  }
  return ''
}

// 提取x和y值
const getXYValue = (value) => {
  // 从 "x:0.047  y:0.047  z:0.047  mm" 中提取 "x:0.047  y:0.047"
  const parts = value.split('  '); // 注意是两个空格
  return parts.length >= 2 ? `${parts[0]}  ${parts[1]}` : value;
}

// 提取z值
const getZValue = (value) => {
  // 从 "x:0.047  y:0.047  z:0.047  mm" 中提取 "z:0.047  mm"
  const parts = value.split('  '); // 注意是两个空格
  return parts.length >= 3 ? `${parts[2]}  ${parts[3] || ''}` : '';
}

const columns = ref([
  { title: '设备名称', key: 'name', align: 'left' },
  { title: '监测值', key: 'value', align: 'center' },
  { title: '监测时间', key: 'time', align: 'center' },
  { title: '状态', key: 'status', align: 'center' },
]);

const tableData = ref([]);

// 初始化滚动
const initScroll = () => {
  // 清除之前的定时器
  if (scrollTimer) {
    clearInterval(scrollTimer)
    scrollTimer = null
  }
  
  const wrapper = vehicleScrollWrapper.value
  
  // 如果没有数据或容器不存在，则不启动滚动
  if (!wrapper || !tableData.value.length || wrapper.scrollHeight <= wrapper.clientHeight) {
    console.log("不满足滚动条件：wrapper存在?", !!wrapper, "数据长度:", tableData.value.length, "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)
}

const fetchData = async () => {
  const response = await getOnlineData();
  if (response.data.code == 200) {
    tableData.value = response.data.data
    
    // 数据更新后，等待DOM更新再初始化滚动
    nextTick(() => {
      initScroll()
    })
  } else {
    message.error(response.data.msg)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData();
});

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

<style scoped lang="scss">
.wrapper {
  overflow: visible;
  width: 4.6rem;
  height: 3rem;
  position: relative;
  padding: 0.15rem;
  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);
  }
}

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

.alarm-list {
  margin: 0;
}

.list-header {
  display: flex;
  justify-content: space-between;
  padding: 0.1rem;
  background-image: url("@/assets/jinrun/table-header-bg.png");
    /* margin-bottom: 0.05rem; */
    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: center;
        flex: .5;
    }
  }
}

.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;
  background-color: #2a496d78;
      margin-top: .13rem;
  
  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;
    &:first-child {
      // text-align: left;
    justify-content: start;

    }
    
    &:last-child {
      // text-align: right;
       flex: .5;
    justify-content: center;

    }
  }
  
  .value-cell {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    line-height: 1.2;
    
    .xy-value, .z-value {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      width: 100%;
    }
  }
  
  .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%;
    }
  }
  
  &.status-chengse {
    span {
      color: #FF852B;
    }
  }
  
  &.status-lanse {
    span {
      color: #28CAFF;
    }
  }
  
  &.status-huangse {
    span {
      color: #FFD118;
    }
  }

  &.status-hongse {
    span {
      color: #FF852B;
    }
  }
}

.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>