<template>
  <div class="ue-wrapper">
    <div class="connect-status" v-show="connectStatus!=='连接成功'">连接状态：{{ connectStatus }}</div>
    <div ref="videoContainerRef" class="video-container"></div>
    <dialog id="login-dialog" data-bs-theme="dark">
      <h2 class="mb-3 fs-6">登录以获取场景资源</h2>
      <form :model="form" v-on:submit="handleLogin">
        <div class="mb-3">
          <label htmlFor="userName" class="form-label">用户名</label>
          <input v-model="form.userName" id="userName" type="text" class="form-control" />
        </div>
        <div class="mb-3">
          <label htmlFor="password" class="form-label">密码</label>
          <input v-model="form.password" id="password" type="password" class="form-control" />
        </div>
        <div class="text-center">
          <button type="submit" class="btn btn-primary">登录</button>
        </div>
      </form>
      <div v-if="loginMsg" class="mt-3 text-danger">{{ loginMsg }}</div>
    </dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, getCurrentInstance } from 'vue'
import axios from 'axios';

const { proxy } = getCurrentInstance()

const connectStatus = ref("未连接"); // State to store the input content

const peerStreamRef = ref(null)
// 用来存储视频容器的引用
const videoContainerRef = ref(null);

// 关闭场景的函数
const closeScene = () => {
  if (videoContainerRef.value) {
    videoContainerRef.value.removeChild(peerStreamRef.value);
    console.log("Scene closed");
  }
};

// 连接场景
const wsConnect = (sceneId, view_mode, token) => {
  // 确保 videoContainerRef 指向一个有效的容器
  if (videoContainerRef.value) {
    // 清空容器
    videoContainerRef.value.innerHTML = '';
    // 创建 PeerStream 元素
    peerStreamRef.value = document.createElement('video', { is: 'peer-stream' });
    peerStreamRef.value.dataset.sceneId = sceneId;
    peerStreamRef.value.dataset.viewMode = view_mode;
    peerStreamRef.value.dataset.token = token;
    peerStreamRef.value.style.width = '100%';
    videoContainerRef.value.appendChild(peerStreamRef.value);

    //场景事件
    peerStreamRef.value.addEventListener("playing", () => {
      connectStatus.value = ("连接成功");
      proxy.$bus.emit('ueConnected')
    });
    peerStreamRef.value.addEventListener("disConnected", () => connectStatus.value = ("连接断开"));
    peerStreamRef.value.addEventListener("message", (e) => {
      const message = JSON.parse(e.detail);
      console.log("收到消息：", message)
      // connectStatus.value = ("收到消息：" + message);
    });
  }
}

const sendDataChannelCommand = (command) => {
  if (peerStreamRef.value) {
    // console.error((peerStreamRef.value), (peerStreamRef.value).dc);
    // Call the send method on the custom peer-stream element
    (peerStreamRef.value).emitMessage((JSON.parse(command)));
    console.log('Sending command:', command);
  }
}

const form = ref({
  userName: 'admin',
  password: 'citygis1613'
})

const loginMsg = ref('')

function handleLogin(e) {
  e.preventDefault();
  console.log(form.value)
  const baseUrl = 'http://10.1.161.53:3000'
  axios.post(`${baseUrl}/auth/login`, form.value)
  .then(response => {
    if (response.status === 201) {
      localStorage.setItem('token', response.data.access_token);
      // 获取场景列表
      axios({
        method: 'get',
        url: baseUrl + '/scenePermission',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      }).then(res => {
        if(res.data) {
          const targetScene = res.data.find(row => row.name === "低空经济")
          if(!targetScene) {
            loginMsg.value = '未发现场景资源'
            return
          }
          wsConnect(targetScene.scene_id, targetScene.permission, localStorage.getItem('token'));
          // 添加全局调用监听
          proxy.$bus.on('callUE', (command) => {
            sendDataChannelCommand(command)
          })
          // 关闭弹窗和页面loading
          const dialog = document.getElementById('login-dialog')
          dialog.close()
          proxy.$bus.emit('toggleLoading', false)
        }
      })
    } else {
      loginMsg.value = '登录失败'
    }
  })
  .catch((e) => {
    console.log(e)
    loginMsg.value = '登录失败'
  })
}

onMounted(() => {
  const script = document.createElement('script');
  script.src = '/src/utils/peer-stream.js'; // 自定义元素文件的路径
  script.async = true;
  script.onload = () => {
    console.log('PeerStream custom element script loaded');
  };
  document.body.appendChild(script);
  const dialog = document.getElementById('login-dialog')
  dialog.showModal()

  // setTimeout(() => {
  //   proxy.$bus.emit('toggleLoading', false)
  // }, 1000);
})

</script>

<style lang="scss" scoped>
.ue-wrapper {
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .connect-status {
    position: absolute;
    top: 50%;
    width: 100%;
    text-align: center;
    z-index: 200
  }

  .video-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  #login-dialog {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    padding: 30px 40px;
    border: 2px solid #003e58;
    border-radius: 15px;
    color: #888;
  }
}
</style>