import { defineStore } from "pinia";
import { useWebSocketStore } from "@/stores/modules/webSocketStore";
import * as Constant from "@/common/constant/Constant";

export const useWebRTCStore = defineStore("webrtc", {
  state: () => ({
    // WebRTC 连接实例
    peerConnection: null,

    // ICE 候选信息
    iceCandidates: [],
    pendingIceCandidates: [], // 缓存未处理的候选

    // 连接状态
    connectionState: "disconnected",

    // 媒体流
    localStream: null, // 本地媒体流
    remoteStream: null, // 远端媒体流

    streamType: "audio", //"audio",

    // 视频元素引用
    localVideoElement: null,
    remoteVideoElement: null,

    // 媒体控制状态
    isVideoEnabled: true,
    isAudioEnabled: true,

    // 是否是听筒模式
    isEarpieceMode: false,

    // 通话类型
    callType: "audio", // 'audio' 或 'video'

    // 是否是发起方
    isCaller: false,

    // 配置项
    config: {
      iceServers: [
        { urls: "stun:stun.l.google.com:19302" },
        { urls: "stun:stun.xten.com" },
        { urls: "stun:stun1.l.google.com:19302" },
        { urls: "stun:stun2.l.google.com:19302" },
        { urls: "stun:stun3.l.google.com:19302" },
        { urls: "stun:stun4.l.google.com:19302" },
        { urls: "turn:8.216.131.56:3478",username:'admin',credential:'123456' },
        // 可以添加更多 STUN/TURN 服务器
      ],
    },

    imSate: {
      videoCallModal: false, // 视频通话模态框
      callName: "", // 通话对象名称
      fromUserUuid: "", // 通话对象 uuid
    },
  }),
  actions: {
    //
    bindRemoteAudio() {
      // video  && audio
      // 如果已经存在 audio 元素，先移除旧的
      const oldAudio = document.getElementById(`remote-audio`);
      if (oldAudio) {
        oldAudio.remove();
      }

      // 创建新的 <audio> 元素
      const audioElement = document.createElement("audio");
      audioElement.id = `remote-audio`;
      audioElement.autoplay = true; // 自动播放
      audioElement.muted = false; // 取消静音
      audioElement.controls = true; // 显示控制条（可选）
      audioElement.srcObject = this.remoteStream;

      // 添加到 DOM（可以放在任意位置，比如 body）
      document.body.appendChild(audioElement);

      // 设置听筒播放
      this.setAudioOutputToEarpiece(this.isEarpieceMode)
      console.log("✅ 远程音频已绑定到 <audio> 元素");
    },

    // 初始化 WebRTC 连接
    initConnection(isCaller, video) {
      this.cleanup();
      // 是否是呼叫者/被呼叫者
      this.isCaller = isCaller;
      this.streamType = video ? "video" : "audio";
      const wsStore = useWebSocketStore();
      try {
        // 创建RTC对象
        this.peerConnection = new RTCPeerConnection();

        // 监听 ICE 连接状态（关键修复！）
        this.peerConnection.oniceconnectionstatechange = () => {
          const state = this.peerConnection.iceConnectionState;
          // console.log('通讯ICE状态: ', this.peerConnection.iceConnectionState)
          if (state === "connected") {
            console.log("✅ P2P ICE连接成功！");
            // if (this.streamType == "audio") this.bindRemoteAudio();
          } else if (state === "failed") {
            console.error("❌ ICE 连接失败，尝试重启...");
            this.restartIce();
          }
        };

        // 监听 ICE 状态变化
        this.peerConnection.onconnectionstatechange = () => {
          // console.log('通讯状态: ', this.peerConnection.connectionState)
          this.connectionState = this.peerConnection.connectionState;
          if (this.connectionState === "connected") {
            console.log("✅ P2P 链接成功，可以开始语音通话！");
            if (this.streamType == "audio") this.bindRemoteAudio();
          }
        };

        // 设置事件监听: 对等方收到ice信息后，通过调用 addIceCandidate 将接收的候选者信息传递给浏览器的ICE代理
        this.peerConnection.onicecandidate = (event) => {
          // console.log('获取本机ice', event.candidate)
          if (event.candidate) {
            let candidate = {
              type: this.isCaller ? "offer_ice" : "answer_ice",
              iceCandidate: event.candidate,
            };
            wsStore.sendMessage({
              content: JSON.stringify(candidate),
              type: Constant.MESSAGE_TRANS_TYPE,
            });
            // 本地缓存ice
            this.iceCandidates.push(event.candidate);
          } else {
            console.log("✅ ICE 候选收集完成");
          }
        };
        
        // 当连接成功后，从里面获取语音视频流: 监听 ICE candidate:包含语音视频流
        this.peerConnection.ontrack = (event) => {
          // console.log('ontrack', event)
          // 添加远程媒体流
          if (!this.remoteStream) {
            this.remoteStream = new MediaStream();
          }
          // 添加远程媒体流
          event.streams[0].getTracks().forEach((track) => {
            this.remoteStream.addTrack(track);
          });
        };

        console.log("WebRTC 连接初始化成功");
      } catch (error) {
        console.error("初始化 WebRTC 连接失败:", error);
        this.cleanup();
        throw error;
      }
    },

    // 添加本地媒体流
    addLocalStream(stream) {
      if (!this.peerConnection) {
        throw new Error("WebRTC 连接未初始化");
      }
      // console.log('addLocalStream', stream)
      this.localStream = stream;
      stream.getTracks().forEach((track) => {
        this.peerConnection.addTrack(track, stream);
      });
    },

    // 创建 Offer
    async createOffer() {
      if (!this.peerConnection) {
        throw new Error("WebRTC 连接未初始化");
      }

      try {
        const offer = await this.peerConnection.createOffer();
        await this.peerConnection.setLocalDescription(offer);
        // console.log('createOffer', offer)
        return offer;
      } catch (error) {
        console.error("创建 Offer 失败:", error);
        throw error;
      }
    },

    // 创建 Answer
    async createAnswer() {
      if (!this.peerConnection) {
        throw new Error("WebRTC 连接未初始化");
      }

      try {
        const answer = await this.peerConnection.createAnswer();
        await this.peerConnection.setLocalDescription(answer);
        // console.log('createAnswer', answer)
        return answer;
      } catch (error) {
        console.error("创建 Answer 失败:", error);
        throw error;
      }
    },

    // 设置远程描述后处理缓存
    async setRemoteDescription(desc) {
      try {
        // console.log('setRemoteDescription', desc)
        await this.peerConnection.setRemoteDescription(desc);
        // 处理缓存的候选
        while (this.pendingIceCandidates.length > 0) {
          const candidate = this.pendingIceCandidates.shift();
          try {
            await this.peerConnection.addIceCandidate(candidate);
            console.log("✅ 成功添加缓存的 ICE:", candidate.candidate);
          } catch (err) {
            console.error("❌ 添加缓存 ICE 失败:", e);
          }
        }
      } catch (err) {
        console.error("❌ setRemoteDescription 失败:", err);
      }
    },


    // 添加 ICE 候选
    async addIceCandidate(candidate) {
      // console.log('addIceCandidate', candidate, this.peerConnection.remoteDescription, this.isCaller)
      if (!candidate) {
        console.warn("收到空的 ICE 候选");
        return;
      }

      // WebRTC 会发一个 { candidate: "" } 表示候选收集结束
      if (candidate.candidate === "") {
        console.log("ICE 候选收集完成");
        return;
      }

      // 如果 PeerConnection 还没创建，先缓存
      if (!this.peerConnection) {
        this.pendingIceCandidates.push(candidate);
        return;
      }

      // Answer 方必须等待远程描述
      if (!this.peerConnection.remoteDescription && !this.isCaller) {
        this.pendingIceCandidates.push(candidate);
        return
      }

      try {
        await this.peerConnection.addIceCandidate(candidate);
        console.log("✅ 成功添加 ICE 候选:", candidate.candidate);
      } catch (error) {
        console.error("❌ 添加 ICE 候选失败:", error);
        // 如果失败，也可以选择重新缓存，等下次 setRemoteDescription 再处理
        this.pendingIceCandidates.push(candidate);
        throw error;
      }
    },


    // 清理资源：挂断
    cleanup() {
      console.log("清理资源...");
      if (this.peerConnection) {
        this.peerConnection.restartIce();
        this.peerConnection.close();
        this.peerConnection = null;
      }

      if (this.localStream) {
        this.localStream.getTracks().forEach((track) => track.stop());
        this.localStream = null;
      }

      if (this.remoteStream) {
        this.remoteStream.getTracks().forEach((track) => track.stop());
        this.remoteStream = null;
      }

      this.iceCandidates = [];
      this.connectionState = "disconnected";
    },

    // 获取视频流
    async getUserMedia(config){
      if (this.localStream) {
        return new Promise((resolve)=>{
          resolve(this.localStream);
        });
      }
      return navigator.mediaDevices.getUserMedia(config).then((stream) => {
        // 初步显示本地视频流
        this.localStream = stream;
        return stream;
      });
    },

    // 切换音频输出设备 flag: true 听筒，false 扬声器
    async setAudioOutputToEarpiece(bool = false){
      if(!this.remoteStream){
        throw new Error("No remote stream available");
      }
      this.isEarpieceMode = bool;
      const Audio = document.getElementById(`remote-audio`);
      console.log("Audio:", Audio.setSinkId);
      // 通过音频元素获取输出设备列表
      const devices = await navigator.mediaDevices.enumerateDevices();
      console.log("Disabling audio track:", devices);
      // 获取音频输出设备列表
      const device = devices.filter(device=>device.kind === "audiooutput").find(device=> bool?(device.label.includes("扬声器") || device.label.includes("default")):(device.label.includes("听筒") || device.label.includes("Earpiece") || device.label.includes("Receiver")));
      console.log("听筒device:", device);
      if(device){
        return this.isEarpieceMode = await Audio.setSinkId(device.deviceId).then(()=> true).catch(e=>{
          console.error("切换失败:", e);
          return false;
        });
      }
      return this.isEarpieceMode = false;
    }

  },
});
