<script setup lang="ts">
import { ref, onMounted } from "vue";
import ClipBox from "@components/ClipBox/index.vue";
import useMultipleWebSockets from "../../../../service/socket/socket.ts"
import useSockets from "../../../../hooks/useSockets.ts";


const { sockets, connectionStatus, connected } = useSockets();
declare global {
  interface Window {
    tableData?: any;
    socketUrl?: any;
  }
}

const tableData = ref<{ name: string; ip: string, status: string }[]>([]);
const addCocoPiVisible = ref(false);
const editCocoPiVisible = ref(false);
const CocoPiData = ref<any>({});
const socketUrl = ref<string[]>([])
const problem = ref("")
const codeRef = ref<any>(null)

onMounted(async () => {
  getData()
})

const getData = async () => {
  tableData.value = JSON.parse(localStorage.getItem('tableData') || '[]').map((item: any) => {
    item.status = "disConnected"
    item.socketData = "无数据"
    return item
  })
  if (tableData.value.length > 0) {
    socketUrl.value = JSON.parse(localStorage.getItem('socketUrl') || '[]')
    initConnections(socketUrl.value)
  }
};
const initConnections = async (urls: any) => {
  await Promise.all(urls.map((url: any) => connected(url).then(res => {
    (res as WebSocket).onmessage = (e: any) => {
      tableData.value.map((i: any) => {
        if (`wss://${i.ip}:5678/` === `${(res as WebSocket).url}`) {
          i.socketData = e.data;
          i.status = 'connected';
        }
      })
    };
  }).catch(err => {
    tableData.value.map((i: any) => {
      if (`wss://${i.ip}:5678/` === err.currentTarget.url) {
        i.socketData = "无数据";
        i.status = 'disConnected';
      }
    })
  })));
};
const onSubmit = async () => {
  if (!CocoPiData.value.name || !CocoPiData.value.ip) {
    alert("请填写完整信息");
    return;
  } else if (socketUrl.value.includes(`wss://${CocoPiData.value.ip}:5678`)) {
    alert("该设备IP已添加，请勿重复添加");
    return;
  }

  const { sockets, send, sendData, status } = await useMultipleWebSockets([`wss://${CocoPiData.value.ip}:5678`])
  setTimeout(() => {
    if (status[`wss://${CocoPiData.value.ip}:5678`] === "connected") {
      let obj = {
        name: CocoPiData.value.name,
        ip: CocoPiData.value.ip,
        status: "connected",
        socketData: sendData[`wss://${CocoPiData.value.ip}:5678`],
        send: send
      }
      tableData.value.push(obj)
      socketUrl.value.push(`wss://${CocoPiData.value.ip}:5678`)
      addCocoPiVisible.value = false
      localStorage.setItem("tableData", JSON.stringify(tableData.value))
      localStorage.setItem("socketUrl", JSON.stringify(socketUrl.value))
      CocoPiData.value = {}
    } else {
      alert("请检查IP是否正确或者网络是否正常")
    }
  }, 1000)
}

const detectionIP = () => {
  console.log("检测ip", CocoPiData.value.ip);
  if (!CocoPiData.value.ip) {
    alert("请填写ip");
    return;
  }
  window.open(`https://${CocoPiData.value.ip}:5678/`);
}

const handleEdit = (data: any) => {
  editCocoPiVisible.value = true
  console.log("handleEdit", data);
}

const handleDelete = (data: any) => {
  console.log("handleDelete", data);
}


function insert_operating_record(rawData: string) {
  // 事件流数据通常以 "data: " 开头，以 "\n\n" 分隔事件
  const events = rawData.split('\n\n').filter(Boolean);

  events.forEach(event => {
    // 移除 "data: " 前缀并解析JSON（如果是JSON数据）
    if (event.startsWith('data: ')) {
      const data = event.substring(6).trim();
      try {
        const parsedData = JSON.parse(data);
        console.log('Parsed event:', parsedData);
        // 在这里处理解析后的数据
      } catch (e) {
        console.log('Raw event data:', data);
      }
    }
  });
}

const copyCode = () => {
  // sockets.value['wss://192.168.232.46:5678'].send(`echo close > /root/socket.txt`)
  
  let data = problem.value
  console.log(data)
  sockets.value['wss://192.168.232.46:5678'].send(`echo ${data} > /root/socket.txt`)
};

const clearAlldevice = () => { 
  tableData.value = []
  localStorage.setItem("tableData", JSON.stringify([]))
  localStorage.setItem("socketUrl", JSON.stringify([]))
};
</script>

<template>
  <ClipBox title="硬件信息">
    <div class="realtime-content">
      <div style="text-align: right;padding:0 0 10px 0;">
        <el-button @click="clearAlldevice" type="danger">清除设备</el-button>
        <el-button @click="addCocoPiVisible = true" type="primary">添加硬件</el-button>
      </div>
      <el-table :data="tableData" style="width: 100%;">
        <!-- <el-table-column label="序号" width="80" props="index">
        </el-table-column> -->
        <el-table-column label="名字" prop="name" width="80">
        </el-table-column>
        <el-table-column label="IP" prop="ip" width="130">
        </el-table-column>
        <el-table-column label="连接状态" prop="status" width="120">
        </el-table-column>
        <el-table-column label="数据" prop="socketData" >
          
        </el-table-column>
        <el-table-column label="操作" width="140">
          <template v-slot="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">操作</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="addCocoPiVisible" title="添加硬件" style="max-width: 600px;">
      <el-form :data="CocoPiData" label-width="auto">
        <el-form-item label="硬件名称：">
          <el-input v-model="CocoPiData.name" placeholder="请输入硬件名称"></el-input>
        </el-form-item>
        <el-form-item label="硬件ip：">
          <el-input v-model="CocoPiData.ip" placeholder="请输入硬件IP地址" style="width: 200px;"></el-input>
          <el-button @click="detectionIP">检测ip 服务是否启动</el-button>
        </el-form-item>
        <!-- <el-form-item label="地图位置：">
          <el-input v-model="CocoPiData.port" placeholder="请输入硬件端口" type="number"></el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" @click="onSubmit">Create</el-button>
          <el-button>Cancel</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog v-model="editCocoPiVisible" title="操作" width="600">
      <!-- <el-select>
        <el-option label="" value=""></el-option>
        <el-option label="" value=""></el-option>
      </el-select> -->
      <el-input style="width: 60%;" v-model="problem" aria-placeholder="请输入功能" placeholder="请输入功能"></el-input>
      <!-- <el-button @click="onCodeSubmit">发送指令</el-button> -->
      <br /><br />
      <!-- <span>内容显示：</span> -->
        <el-button @click="copyCode">发送指令</el-button>
    </el-dialog>
  </ClipBox>
</template>

<style scoped lang="less">
@import "@assets/styles/common.less";

:deep(.clip-content) {
  position: relative;
  display: flex;
  justify-content: space-between;
  z-index: 3;
  width: 100%;
}

.realtime-content {
  width: 100%;
  flex: 1;
  background: #fff;
  border-radius: 15px;
  padding: 15px;
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;

  ul {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10 * @px2vw;
    list-style: none;
    box-shadow: 0 0 10 * @px2vw #00ecff7f inset;
    .borderInnerShadowBox();
  }

  li {
    margin: 0;
    filter: drop-shadow(0 0 0.8px #156dae) drop-shadow(0 0 0 #156dae) drop-shadow(0 0 0 #156dae) drop-shadow(0 0 0 #156dae) drop-shadow(0 0 0 #156dae);

    span {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 26 * @px2vw;
      height: 35 * @px2vw;
      mask: radial-gradient(circle at 0, transparent 6 * @px2vw, #fff 0),
        radial-gradient(circle at right, transparent 6 * @px2vw, #fff 0);
      mask-size: 50%;
      mask-position: 0, 100%;
      mask-repeat: no-repeat;
      background: #24489f;
      font-size: 28 * @px2vw;
      font-family: 方正兰亭粗黑, fantasy;
    }
  }

  &::before {
    content: attr(data-title);
    display: block;
    margin: 6 * @px2vw 0;
    font-size: 20 * @px2vw;
    color: #00ecff;
    text-align: center;
  }

  &+& {
    margin-left: 20 * @px2vw;
  }
}

.code-show {
  max-height: 500px;
  overflow-y: auto;
  min-height: 100px;
  border: 1px solid #ddd;
  border-radius: 5px;
}
</style>
