import ConferenceInfo from "@/wfc/av/model/conferenceInfo";
import conferenceApi from "@/api/conferenceApi";
import avenginekitproxy from "@/wfc/av/engine/avenginekitproxy";
import conferenceManager from "@/ui/voip/conference/conferenceManager";
import ConferenceInviteMessageContent from "@/wfc/av/messages/conferenceInviteMessageContent";
import Message from "@/wfc/messages/message";
import wfc from "@/wfc/client/wfc";
import ForwardType from "@/ui/main/conversation/message/forward/ForwardType";
import store from "@/store.js";
import TalkingCallback from "@/wfc/ptt/client/talkingCallback";
import pttClient from "@/wfc/ptt/client/pttClient";
import { Notification } from "element-ui";

/**
 * 创建会议
 * @param options {object}
 * @param options.title {string}
 * @param options.audience {boolean} [audience=true] - 其他人加入会议时，是否默认为观众；true，默认为观众；false，默认为互动者
 * @param options.allowTurnOnMic {boolean} [allowTurnOnMic=true] - 允许参与者自主开启摄像头和麦克风
 * @param options.advance {boolean} [advance=false] 大规模会议（参会人数大于50人）
 * @returns {Promise<ConferenceInfo>}
 */
export async function createConference({ title = "指挥调度", audience = true, allowTurnOnMic = true, advance = false }) {
  let info = new ConferenceInfo();
  info.conferenceTitle = title;
  info.pin = "" + Math.ceil((1 + Math.random() * 100000) / 10);
  info.owner = conferenceManager.selfUserId;
  const endTime = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000 + 1 * 60 * 60 * 1000)
    .toISOString()
    .split(".")[0];
  info.startTime = Math.ceil(new Date().getTime() / 1000);
  info.endTime = Math.ceil(new Date(endTime).getTime() / 1000);
  info.audience = audience;
  info.allowSwitchMode = allowTurnOnMic;
  info.advance = advance;
  console.log("createConference", info);
  info.conferenceId = await conferenceApi.createConference(info);
  return info;
}

/**
 * 创建并加入会议
 * @param createOpts {object}
 * @param {boolean} audioOnly 是否仅仅开启音频; true，音频会议；false，视频会议
 * @param muteAudio {boolean} [muteAudio=false] - 是否是静音加入会议
 * @param muteVideo {boolean} [muteVideo=false] - 是否是关闭摄像头加入会议
 * @param extra {string}
 */
export async function createAndJoinConference(createOpts, audioOnly, muteAudio, muteVideo, extra) {
  return createConference(createOpts)
    .then((info) => {
      console.log("createAndJoin conference", info);
      avenginekitproxy.startConference(
        info.conferenceId,
        audioOnly,
        info.pin,
        info.owner,
        info.conferenceTitle,
        "",
        info.audience,
        info.advance,
        false,
        null,
        null,
        muteAudio,
        muteVideo
      );
      return new Promise((resolve) => resolve({ ...info, extra }));
    })
    .catch((err) => {
      Notification({
        title: "创建会议失败",
        text: err.message,
        type: "error",
      });
    });
}

/**
 * 创建并加进会议室，立即邀请参会人
 * @param createOpts {object} - 创建会议参数
 * @param createOpts.title {string}
 * @param createOpts.audience {boolean} [audience=true] - 其他人加入会议时，是否默认为观众；true，默认为观众；false，默认为互动者
 * @param createOpts.allowTurnOnMic {boolean} [allowTurnOnMic=true] - 允许参与者自主开启摄像头和麦克风
 * @param createOpts.advance {boolean} [advance=false] 大规模会议（参会人数大于50人）
 * @param audioOnly {boolean} 是否仅仅开启音频; true，音频会议；false，视频会议
 * @param muteAudio {boolean} [muteAudio=false] - 是否是静音加入会议
 * @param muteVideo {boolean} [muteVideo=false] - 是否是关闭摄像头加入会议
 * @param users {{uid: string, displayName: string}[]} - 参会人
 * @param userGroupName {string} - 如果有值发群会议，无值则为单人会议
 * @param extra
 */
export function createJoinAndInviteConference(createOpts, audioOnly, muteAudio, muteVideo, users, userGroupName, extra) {
  // 创建并加入会议
  createAndJoinConference(createOpts, audioOnly, muteAudio, muteVideo, extra).then((info) => {
    console.log(info);
    // 发送参会邀请消息
    const inviteMessageContent = new ConferenceInviteMessageContent(
      info.conferenceId,
      conferenceManager.conferenceInfo.owner,
      info.conferenceTitle,
      "",
      info.startTime,
      info.audioOnly,
      false,
      info.advance,
      info.pin
    );
    inviteMessageContent.extra = info.extra;
    console.log("invite", inviteMessageContent);
    const messagePayload = inviteMessageContent.encode();
    const messageContent = Message.messageContentFromMessagePayload(messagePayload, wfc.getUserId());
    const message = new Message(null, messageContent);
    store.forwardByCreateConversation(ForwardType.NORMAL, users, [message], "", userGroupName);
  });
}

/**
 * 创建单人音视频
 * @param users {{uid: string,displayName: string}[]} - 被调度人信息
 * @param audioOnly 是否仅仅开启音频; true，音频会议；false，视频会议
 */
export function startVideoCall(users, audioOnly) {
  store.createConversation(
    users,
    (conversation) => {
      avenginekitproxy.startCall(conversation, audioOnly, [conversation.target]);
    },
    null,
    ""
  );
}

/**
 * 开始/结束对讲
 * @param conversation
 * @param request
 */
export function requestPttTalk(conversation, request) {
  if (request) {
    let talkingCallback = new TalkingCallback();
    talkingCallback.onStartTalking = (conversation) => {
      console.log("onStartTalking", conversation);
      Notification({
        message: "请开始说话",
        type: "info",
      });
    };
    talkingCallback.onRequestFail = (conversation, reason) => {
      Notification({
        message: "对讲请求失败: " + reason,
        type: "error",
      });
    };
    pttClient.requestTalk(conversation, talkingCallback);
  } else {
    pttClient.releaseTalk(conversation);
  }
}
