import { useWebRTCStore } from "@/stores/modules/webrtcStore";
import { MSG_TYPE, MSG_TYPE_MAP } from "@/common/constant/msgType";
import * as Constant from "@/common/constant/Constant";

// 发送消息处理
export const setMessageHook = (message, state) => {
  // 文本消息
  if (message.contentType == MSG_TYPE.TEXT) {
    state.messages.push({
      ...message,
      toUsername: message.friendUsername,
    });
  }

  // 音频消息
  if (message.contentType === MSG_TYPE.AUDIO) {
    const blob = new Blob([message.file], { type: message.fileSuffix });
    const url = URL.createObjectURL(blob);

    state.messages.push({
      ...message,
      toUsername: message.to,
      localUrl: url,
    });
  }

  // 图片
  if (message.contentType === MSG_TYPE.IMAGE) {
    const blob = new Blob([message.file], { type: message.fileSuffix });
    const url = URL.createObjectURL(blob);
    state.messages.push({
      ...message,
      toUsername: message.to,
      localUrl: url,
    });
  }
};

// 接收到消息处理
export const handleMessageHook = (message, state) => {
  // 文本消息
  message.avatar = state.toUserInfo.avatar;
  if (message.contentType === MSG_TYPE.TEXT) {
    state.messages.push({
      ...message,
      toUsername: message.to,
    });
  }
  // 音频消息
  if (message.contentType === MSG_TYPE.AUDIO) {
    const audioBlob = new Blob([message.file], {
      type: `audio/${message.fileSuffix}`,
    });
    // 生成可播放的 ObjectURL
    const audioUrl = URL.createObjectURL(audioBlob);
    state.messages.push({
      ...message,
      file: audioUrl,
      toUsername: message.to,
    });
  }

  // 图片
  if (message.contentType === MSG_TYPE.IMAGE) {
    const blob = new Blob([message.file], { type: message.fileSuffix });
    const url = URL.createObjectURL(blob);
    state.messages.push({
      ...message,
      file: url,
      toUsername: message.to,
    });
  }
  // 音频在线：拨号
  if (
    message.contentType === Constant.DIAL_AUDIO_ONLINE ||
    message.contentType === Constant.DIAL_VIDEO_ONLINE
  ) {
    console.log("收到播号")
    const rtcStore = useWebRTCStore();
    rtcStore.imSate = {
      videoCallModal: true,
      callName: message.fromUsername,
      fromUserUuid: message.from, 
      callAvatar: message.avatar
    };
    return
  }
  // 音频在线：取消
  if (
    message.contentType === Constant.CANCELL_AUDIO_ONLINE ||
    message.contentType === Constant.CANCELL_VIDEO_ONLINE
  ) {
    console.log("音频在线：取消")
    const rtcStore = useWebRTCStore();
    rtcStore.imSate.videoCallModal = false; 
    return;
  }
  // 音频在线：拒接
  if (
    message.contentType === Constant.REJECT_AUDIO_ONLINE ||
    message.contentType === Constant.REJECT_VIDEO_ONLINE
  ) {
    console.log("音频在线：拒接")
    const rtcStore = useWebRTCStore();
    rtcStore.imSate.videoCallModal = false;
    return;
  }
  // 音频在线：接听
  if (
    message.contentType === Constant.ACCEPT_VIDEO_ONLINE ||
    message.contentType === Constant.ACCEPT_AUDIO_ONLINE
  ) {
     console.log("音频在线：接听")
    const video = message.contentType == Constant.ACCEPT_AUDIO_ONLINE
    startAudioOnline(video, state);
    return;
  }
  // 音频通话
  if (message.type === Constant.MESSAGE_TRANS_TYPE) {
    if (
      message.contentType >= Constant.DIAL_MEDIA_START &&
      message.contentType <= Constant.DIAL_MEDIA_END
    ) {
      console.log("音频通话")
      // 媒体通话处理
      // dealMediaCall(message);
      return;
    }
    const rtcStore = useWebRTCStore();
    const { type, sdp, iceCandidate } = JSON.parse(message.content);
    // 接收answer:设置对端sdp
    if (type === "answer") {
      const answerSdp = new RTCSessionDescription({ type, sdp });
      rtcStore.setRemoteDescription(answerSdp);
    }
    // 处理 ICE 候选（统一处理offer_ice和answer_ice）
    if (type.endsWith("_ice")) {
      const candidate = new RTCIceCandidate(iceCandidate);
      rtcStore
        .addIceCandidate(candidate)
        .catch((error) => console.error("添加ICE候选失败:", error));
      return;
    }

    // 响应对端offer
    if (type === "offer") {
      // 检查媒体权限是否开启
      // let preview = null;

      if (!rtcStore.peerConnection) {
        rtcStore.initConnection(false); // false表示是Answer方
      }

      let video = false;
      if (message.contentType === Constant.VIDEO_ONLINE) {
        // preview = document.getElementById("localVideoReceiver");
        video = true;
        // // 屏幕共享
      }

      if (message.contentType === Constant.AUDIO_ONLINE) {
        // preview = document.getElementById("audioPhone");
        // 音频电话
      }

      navigator.mediaDevices
        .getUserMedia({ audio: true, video: video })
        .then((stream) => {
          rtcStore.addLocalStream(stream);
          const offer = new RTCSessionDescription({ type, sdp });
          return rtcStore.setRemoteDescription(offer);
        })
        .then(() => rtcStore.createAnswer())
        .then((answer) => {
          state.sendMessage({
            content: JSON.stringify(answer),
            type: Constant.MESSAGE_TRANS_TYPE,
            messageType: message.contentType,
          });
        });
    }
  }
};


// 消息回调
const messageCallback = (contentType, state)=>{
 state.sendMessage({
    contentType, // 消息内容类型
    content: "callback", // 
    type: Constant.MESSAGE_TRANS_TYPE,
  });
}

// 创建呼叫:开启语音电话
const startAudioOnline = (video, state) => { 
  const rtcStore = useWebRTCStore();
  // 初始化webrtc连接
  rtcStore.initConnection(true);

  navigator.mediaDevices
    .getUserMedia({ audio: true, video: video })
    .then((stream) => {
      rtcStore.addLocalStream(stream);
      return rtcStore.createOffer();
    })
    .then((offer) => {
      // 发送offer
      state.sendMessage({
        contentType: Constant.AUDIO_ONLINE, // 消息内容类型
        content: JSON.stringify(offer),
        type: Constant.MESSAGE_TRANS_TYPE,
      });
    })
    .catch((error) => {
      console.error("发起呼叫失败:", error);
    });
};
