<template>
  <div class="content">
    <div class="bg"></div>
    <div class="backBtn">
      <el-button @click="toIndex" class="toIndex">返回首页</el-button>
    </div>
    <div class="logo"></div>
    <div class="time">
      <div class="time1">{{ time.time }}</div>
      <div style="display: inline-block">
        <div class="time2">{{ time.week }}</div>
        <div class="time3">{{ time.date }}</div>
      </div>
    </div>
    <div class="title">RFID中间件监控平台</div>
    <div class="title1">告警统计</div>
    <div class="topTitle" style="left: 13%">设备数量:</div>
    <div class="topTitle" style="left: 37.5%">在线数量:</div>
    <div class="topTitle" style="left: 62%">离线数量:</div>
    <div class="topTitle" style="left: 86.5%">告警数量:</div>
    <div class="topNum" style="left: 17%; color: #127feb">{{ Object.keys(deviceData).length }}</div>
    <div class="topNum" style="left: 41.5%; color: #49e1f5">{{ Object.values(deviceData).filter((e) => e.status).length }}</div>
    <div class="topNum" style="left: 66%; color: #d8ee30">{{ Object.values(deviceData).filter((e) => !e.status).length }}</div>
    <div class="topNum" style="left: 90.5%; color: #901f43">{{ 0 }}</div>
    <!--    <div class="topNum" style="left: 17%; color: #127feb">{{ overview.deviceTotal }}</div>-->
    <!--    <div class="topNum" style="left: 41.5%; color: #49e1f5">{{ overview.onlineCount }}</div>-->
    <!--    <div class="topNum" style="left: 66%; color: #d8ee30">{{ overview.offlineCount }}</div>-->
    <!--    <div class="topNum" style="left: 90.5%; color: #901f43">{{ overview.alarmCount }}</div>-->
    <div class="menu">
      <el-menu active-text-color="#ffd04b" background-color="#062852" class="el-menu-vertical-demo" default-active="2" text-color="#fff">
        <template v-for="(i, index) in treeData" :key="i.id">
          <!--          <MenuItem :data="i" />-->
          <el-sub-menu :index="index">
            <template #title>
              <span>{{ i.locationAlias }}</span>
            </template>
            <el-menu-item @click="scrollToId(ii.id)" v-for="ii in i.children">{{ ii.locationAlias }}</el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </div>
    <div class="scrollTable">
      <div class="th" :style="{ backgroundImage: `url(${thbg})` }">
        <div class="td" style="width: 25%">时间</div>
        <div class="td" style="width: 15%">设备名称</div>
        <div class="td" style="width: 25%">位置</div>
        <!--        <div class="td" style="width: 10%">等级</div>-->
        <div class="td" style="width: 35%">告警行为</div>
      </div>
      <vue3ScrollSeamless
        ref="scrollSeamlessRef"
        :classOptions="classOptions"
        :dataList="tableData"
        style="overflow: hidden; height: calc(100% - 3.5vw); margin-top: 0.2vw"
      >
        <div
          v-for="(item, index) in tableData"
          :key="index"
          class="tr"
          style="margin-top: 8px; line-height: 2.4vw"
          :style="{ backgroundImage: `url(${trbg})` }"
        >
          <div class="td" style="width: 25%; line-height: 2.4vw">{{ item.alarmTime }}</div>
          <div class="td" style="width: 15%; line-height: 2vw">{{ item.deviceName }}</div>
          <div class="td" style="width: 25%; line-height: 2vw; font-size: 0.6vw">{{ item.location || '' }}</div>
          <!--          <div class="td" style="width: 10%; line-height: 2vw">{{ item.alarmLevel }}</div>-->
          <div class="td" style="width: 35%; line-height: 2vw">{{ item.alarmAction }}</div>
        </div>
      </vue3ScrollSeamless>
    </div>
    <div class="center" ref="scrollNodeRef" @mouseenter="mouseenter" @mouseleave="mouseleave">
      <div v-masonry style="width: 100%; text-align: center" ref="masonryRef">
        <TreeItem v-masonry-tile :data="i" v-for="i in centerData" :key="i.id" :deviceData="deviceData" :copy="false" />
      </div>
      <div v-masonry style="width: 100%; height: 100%">
        <TreeItem v-masonry-tile :data="i" v-for="i in centerData" :key="i.id" :deviceData="deviceData" :copy="true" />
      </div>
    </div>
  </div>
</template>
<script setup lang="jsx">
import { ElMessageBox } from 'element-plus';
import thbg from '@/assets/chart/thbg.png';
import trbg from '@/assets/chart/trbg.png';
import TreeItem from './treeItem.vue';
import { vue3ScrollSeamless } from 'vue3-scroll-seamless';
import { parseTime } from '@/utils/ruoyi.js';
import { useRouter } from 'vue-router';

const router = useRouter();
const toIndex = () => {
  router.push('/index');
};

import { getRealtimeStats, getLocationTree, getSuccessRateTrends, getDeviceLatestRecords } from '@/api/rfid/dashboard';

let timer = null;

function findParentsWithLocationType3(arr) {
  const result = [];

  function traverse(items) {
    for (const item of items) {
      let hasChildWith3 = false;

      if (item.children && Array.isArray(item.children)) {
        for (const child of item.children) {
          if (child.locationType === '3') {
            hasChildWith3 = true;
          }
        }
        traverse(item.children);
      }

      if (hasChildWith3) {
        result.push(item);
        item.children.forEach((v) => {
          deviceData.value[v.deviceName] = {
            code: '',
            status: v.onlineStatus === '1',
            time: parseTime(new Date(), '{m}-{d} {h}:{i}')
          };
        });
      }
    }
  }

  traverse(arr);
  return result;
}

const timeFun = () => {
  const now = new Date();

  const pad = (n) => String(n).padStart(2, '0');
  const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;

  const weekMap = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const week = weekMap[now.getDay()];

  const date = `${now.getFullYear()}.${pad(now.getMonth() + 1)}.${pad(now.getDate())}`;

  return {
    time,
    week,
    date
  };
};

const mouseenter = () => {
  hover.value = true;
  if (timer) {
    clearTimeout(timer);
  }
  timer = null;
};
const mouseleave = () => {
  setTimeout(() => {
    hover.value = false;
    scrollNodeRef.value.scrollTop -= 1;
  }, 100);
};

const overview = ref({});
const classOptions = ref({
  limitMoveNum: 1,
  step: 1,
  hover: true
});
setInterval(() => {
  time.value = timeFun();
}, 1000);
const time = ref(timeFun());
const masonryRef = ref(null);
const scrollSeamlessRef = ref(null);
const scrollNodeRef = ref(null);
const hover = ref(false);
const tableData = ref([]);
const treeData = ref();
const centerData = ref([]);
const deviceData = ref({});

const MenuItem = defineComponent({
  name: 'MenuItem',
  props: {
    data: {
      type: Object,
      required: true
    }
  },
  setup(props) {
    const { data } = props;
    return () =>
      data.children?.length > 0 ? (
        <ElSubMenu
          index={`${data.id}`}
          v-slots={{
            title: () => <span>{data.locationAlias}</span>
          }}
        >
          {data.children.map((item, index) => {
            return <MenuItem data={item} />;
          })}
        </ElSubMenu>
      ) : (
        <el-menu-item onClick={() => scrollToId(data.id)} index={`${data.id}`}>
          {data.locationAlias}
        </el-menu-item>
      );
  }
});

function scrollToBottom(scrollNode, speed = 1) {
  if (!scrollNode) return;

  function step() {
    const maxScroll = scrollNode.scrollHeight - scrollNode.clientHeight;
    if (!hover.value && scrollNode.scrollTop < maxScroll) {
      let top = Math.min(scrollNode.scrollTop + speed, maxScroll);
      if (top > masonryRef.value.clientHeight) {
        top -= masonryRef.value.clientHeight;
      }
      scrollNode.scrollTop = top;
    }
    requestAnimationFrame(step);
  }

  requestAnimationFrame(step);
}

const scrollToId = (id) => {
  const container = scrollNodeRef.value;
  if (!container) return;

  const target = container.querySelector(`#tree${id}`);
  if (target) {
    const containerTop = container.getBoundingClientRect().top;
    const targetTop = target.getBoundingClientRect().top;

    const scrollOffset = targetTop - containerTop + container.scrollTop;

    container.scrollTo({
      top: scrollOffset,
      behavior: 'smooth' // 平滑滚动
    });
    hover.value = true;
    if (timer) {
      clearTimeout(timer);
    }
    timer = null;
    timer = setTimeout(() => {
      hover.value = false;
    }, 5000);
  }
};
const getData = () => {
  getRealtimeStats().then((res) => {
    overview.value = res.data?.overview || {};
    tableData.value = res.data?.alarmStats || [];
  });
};

let data = {
  'objid': 1993874716645003264,
  'deviceId': 1,
  'readStatus': '1',
  'epcStr': '       SW004',
  'alarmFlag': '0',
  'alarmLevel': '�',
  'alarmType': '�',
  'alarmAction': '',
  'recordTime': '2025-11-27T10:49:11.25084+08:00',
  'dataType': 2,
  'deviceStatus': 1
};
let data1 = {
  'objid': 1993880261934321664,
  'deviceId': 1,
  'readStatus': '0',
  'epcStr': '',
  'alarmFlag': '1',
  'alarmLevel': '�',
  'alarmType': '�',
  'alarmAction': '未获取到标签信息',
  'recordTime': '2025-11-27T11:11:13.314071+08:00',
  'dataType': 2,
  'deviceStatus': 1
};
let data2 = {
  'objid': 0,
  'deviceId': 1,
  'readStatus': '�',
  'epcStr': null,
  'alarmFlag': '1',
  'alarmLevel': '�',
  'alarmType': '�',
  'alarmAction': '链接断开',
  'recordTime': '2025-11-27T10:54:18.600795+08:00',
  'dataType': 1,
  'deviceStatus': 2
};
const getSocket = () => {
  const socket = new WebSocket(import.meta.env.VITE_WEBSOCKET_ADDRESS);

  socket.addEventListener('open', () => {
    console.log('✅ WebSocket 连接成功');
  });

  socket.addEventListener('message', (event) => {
    let data = JSON.parse(event.data);
    let list = data.Readers || [];
    list.forEach((item) => {
      if (item.ConnectionStatus !== 1) {
        ElMessageBox.alert(`设备${item.Id}离线`, '离线报警', {
          type: 'warning',
          confirmButtonText: '确定'
        }).catch(() => undefined);
        tableData.value.push({
          alarmTime: parseTime(new Date(), '{m}-{d} {h}:{i}'),
          deviceName: item.Id,
          location: '',
          alarmAction: '设备离线'
        });
      }

      deviceData.value[item.Id] = {
        status: item.ConnectionStatus === 1,
        time: parseTime(new Date(), '{m}-{d} {h}:{i}')
      };
    });
    scrollToId(list?.[0]?.Id);
  });

  socket.addEventListener('close', () => {
    setTimeout(() => {
      getSocket();
    }, 1000);
  });

  socket.addEventListener('error', (error) => {
    // console.error('⚠️ WebSocket 出错:', error);
  });
};
let timer1 = null;
onMounted(() => {
  getData();
  nextTick(() => {
    scrollToBottom(scrollNodeRef.value, 1);
  });

  getLocationTree().then((res) => {
    treeData.value = res.data;
    centerData.value = findParentsWithLocationType3(res.data);
  });
  getDeviceLatestRecords().then((res) => {
    res.data.forEach((item) => {
      if (deviceData.value[item.deviceName]) {
        deviceData.value[item.deviceName].code = item.latestBarcode;
      }
    });
  });
  getSocket();
  timer1 = setInterval(() => {
    getData();
  }, 1000 * 30);
});
onBeforeMount(() => {
  if (timer1) {
    clearInterval(timer1);
    timer1 = null;
  }
});
</script>
<style scoped lang="less">
.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-family: 'Source Han Sans', 'Noto Sans CJK SC', '思源黑体', sans-serif;

  .bg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('@/assets/chart/bg.jpg');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }

  .logo {
    position: absolute;
    top: 5%;
    left: 5%;
    width: 8vw;
    height: 1.91474vw;
    background-image: url('@/assets/chart/highwayLogo.png');
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }

  .time {
    position: absolute;
    top: 5%;
    right: 5%;
    color: #78caf6;
    font-family: 'CSD-Block-Bold';

    .time1 {
      display: inline-block;
      white-space: nowrap;
      line-height: 2vw;
      font-size: 1.6vw;
      margin-right: 8px;
      vertical-align: top;
      font-family: 'CSD-Block-Bold';
      font-feature-settings: 'tnum';
    }

    .time2 {
      white-space: nowrap;
      line-height: 1vw;
      font-size: 0.8vw;
      font-family: 'CSD-Block-Bold';
    }

    .time3 {
      white-space: nowrap;
      font-size: 0.9vw;
      line-height: 1vw;
      font-family: 'CSD-Block-Bold';
    }
  }

  .title {
    position: absolute;
    top: 2vw;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 2.1vw;
    font-weight: 700;
    letter-spacing: 0.2vw;
    color: #7ae7f8;
    background: linear-gradient(to bottom, #ffffff 0%, #7ae7f8 100%);
    background-clip: text;
    color: transparent;
  }

  .title1 {
    position: absolute;
    top: 27.9%;
    left: 76.5%;
    transform: translateY(-50%);
    font-size: 1vw;
    font-weight: 700;
    letter-spacing: 0.2vw;
    color: #7ae7f8;
  }

  .title2 {
    position: absolute;
    top: 61.5%;
    left: 76.5%;
    transform: translateY(-50%);
    font-size: 1vw;
    font-weight: 700;
    letter-spacing: 0.2vw;
    color: #7ae7f8;
  }

  .topTitle {
    position: absolute;
    top: 16.7%;
    transform: translate(-50%, -50%);
    color: #eee;
    font-size: 1.4vw;
    letter-spacing: 0.2vw;
  }

  .topNum {
    position: absolute;
    top: 16.7%;
    transform: translateY(-50%);
    color: #eee;
    font-size: 1.5vw;
    letter-spacing: 0.2vw;
  }

  .menu {
    position: absolute;
    top: 24%;
    left: 2.8%;
    width: 14.7%;
    height: 69.5%;
    overflow: auto;
    border-top-left-radius: 1.3vw;
    border-top-right-radius: 1.3vw;

    &::-webkit-scrollbar {
      display: none;
    }
  }

  .scrollTable {
    position: absolute;
    top: 30.7%;
    left: 75.6%;
    width: 20.6%;
    height: 62.5%;
  }

  .th {
    height: 3.3vw;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    font-size: 0.9vw;
  }

  .tr {
    height: 2.4vw;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    font-size: 0.8vw;
  }

  .td {
    display: inline-block;
    line-height: 3.3vw;
    color: #fff;
    text-align: center;
    white-space: nowrap;
  }

  .center {
    position: absolute;
    top: 24.5%;
    left: 19.6%;
    width: 53%;
    height: 69%;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    overflow-y: auto;
    transition: all 1s;

    &::-webkit-scrollbar {
      display: none;
    }
  }
}

.backBtn {
  position: absolute;
  right: 0;
  top: 0;
  width: 5%;
  height: 5%;

  &:hover .toIndex {
    display: inline-block;
  }

  .toIndex {
    display: none;
    position: absolute;
    right: 0;
    top: 0;
  }
}

/deep/ .el-menu {
  border: none;
}

/deep/ .el-sub-menu {
  border-bottom: 1px solid #061b3d;
}
</style>
