<template>
  <el-row>
    <el-col :span="6">
      <ul>
        <li v-for="item in deviceList" :key="item.id">
          <span>{{ item.name }}</span>
          <span>{{ item.status }}</span>
          <span>{{ item.type }}</span>
          <el-switch v-model="item.on" @change="handleDeviceChange(item)" />
        </li>
      </ul>
    </el-col>
    <el-col :span="18">
      <el-table :data="messageList" style="width: 100%">
        <el-table-column prop="time" label="时间" width="180" />
        <el-table-column prop="message" label="消息" width="180" />
        <el-table-column prop="device" label="设备" width="180" />
        <el-table-column prop="type" label="类型" width="180" />
        <el-table-column prop="recordType" label="记录类型" width="180" />
      </el-table>
    </el-col>
  </el-row>
</template>

<script>
export default {
  data() {
    return {
      deviceList: [],
      messageList: [],
      socket: null,
    };
  },
  mounted() {
    this.initSocket();
  },
  methods: {
    initSocket() {
      this.socket = new WebSocket("ws://localhost:8080");
      this.socket.onopen = () => {
        console.log("Socket 连接已建立");
      };
      this.socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        if (data.type === "deviceList") {
          this.deviceList = data.devices;
        } else if (data.type === "scanMessage") {
          this.messageList.push(data.message);
        }
      };
      this.socket.onclose = () => {
        console.log("Socket 连接已关闭");
      };
    },
    handleDeviceChange(item) {
      this.socket.send(
        JSON.stringify({
          type: "toggleDevice",
          deviceId: item.id,
          status: item.on,
        })
      );
    },
  },
};
</script>

<style>
ul {
  list-style: none;
  padding: 0;
}
li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #eee;
}
</style>