<template>
  <div
    class="desktop-view-wrapper"
    :class="{ 'is-collapsed': isCollapsed, 'has-stream': !!stream }"
  >
    <div class="collapse-header" v-if="stream" @click="toggleCollapse">
      <span>远程桌面{{ isCollapsed ? "(已收起)" : "" }}</span>
      <a-button type="link">
        <template #icon>
          <UpOutlined v-if="!isCollapsed" />
          <DownOutlined v-else />
        </template>
      </a-button>
    </div>
    <div class="desktop-view" :class="{ 'is-fullscreen': isFullscreen }">
      <div class="video-container" ref="videoContainer">
        <video ref="videoRef" autoplay playsinline></video>
        <div class="controls" v-if="stream">
          <a-button
            type="primary"
            ghost
            :icon="isFullscreen ? 'fullscreen-exit' : 'fullscreen'"
            @click="toggleFullscreen"
          >
            {{ isFullscreen ? "退出全屏" : "全屏" }}
          </a-button>
        </div>
        <div v-if="!stream" class="no-signal">
          <a-empty description="等待远程桌面共享..." />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from "vue";
import { peer } from "../utils/peer";
import { message } from "ant-design-vue";
import { UpOutlined, DownOutlined } from "@ant-design/icons-vue";

const props = defineProps<{
  peerId: string;
}>();

interface StreamEvent extends CustomEvent {
  detail: {
    stream: MediaStream;
    type: "desktop" | "call";
    peerId: string;
  };
}

interface MediaEndedEvent extends CustomEvent {
  detail: {
    type: "desktop" | "call";
    peerId: string;
  };
}

const videoRef = ref<HTMLVideoElement | null>(null);
const videoContainer = ref<HTMLElement | null>(null);
const stream = ref<MediaStream | null>(null);
const isFullscreen = ref(false);
const isCollapsed = ref(false);

// 切换收起/展开状态
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 处理远程流
const handleStream = (event: StreamEvent) => {
  const { stream: remoteStream, type } = event.detail;
  if (props.peerId !== event.detail.peerId) return;
  if (type === "desktop" && videoRef.value) {
    stream.value = remoteStream;
    videoRef.value.srcObject = remoteStream;
    isCollapsed.value = false; // 收到流时自动展开
  }
};

// 处理媒体结束
const handleMediaEnded = (event: MediaEndedEvent) => {
  const { type } = event.detail;
  if (props.peerId !== event.detail.peerId) return;
  if (type === "desktop") {
    stream.value = null;
    if (videoRef.value) {
      videoRef.value.srcObject = null;
    }
    message.info("远程桌面共享已结束");
  }
};

// 切换全屏
const toggleFullscreen = async () => {
  if (!videoContainer.value) return;

  try {
    if (!isFullscreen.value) {
      if (videoContainer.value.requestFullscreen) {
        await videoContainer.value.requestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        await document.exitFullscreen();
      }
    }
  } catch (err) {
    message.error("切换全屏失败");
  }
};

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement;
};

onMounted(() => {
  peer.on("stream", handleStream as EventListener);
  peer.on("media-ended", handleMediaEnded as EventListener);
  document.addEventListener("fullscreenchange", handleFullscreenChange);
});

onUnmounted(() => {
  peer.off("stream", handleStream as EventListener);
  peer.off("media-ended", handleMediaEnded as EventListener);
  document.removeEventListener("fullscreenchange", handleFullscreenChange);

  // 清理视频流
  if (stream.value) {
    stream.value.getTracks().forEach((track) => track.stop());
  }
});
</script>

<style scoped>
.desktop-view-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #000;
  transition: all 0.3s ease;
  height: 0;
  overflow: hidden;
}

.desktop-view-wrapper.has-stream {
  height: 300px;
}

.desktop-view-wrapper.is-collapsed {
  height: 40px !important;
}

.collapse-header {
  height: 40px;
  background: #1a1a1a;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  cursor: pointer;
  user-select: none;
}

.collapse-header:hover {
  background: #2a2a2a;
}

.desktop-view {
  width: 100%;
  height: calc(100% - 40px);
  background: #000;
  position: relative;
}

.video-container {
  width: 100%;
  height: 100%;
  position: relative;
}

video {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.controls {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  opacity: 0;
  transition: opacity 0.3s;
}

.video-container:hover .controls {
  opacity: 1;
}

.no-signal {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
}

.is-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
}

:deep(.ant-empty-description) {
  color: #fff;
}

:deep(.anticon) {
  vertical-align: 0;
}
</style>
