import tim from "@/tim";
import TIM from "tim-js-sdk";
import store from "@/store/index";

function getOptions(form) {
  let options = {
    ...form,
    memberList: form.memberList.map((x) => {
      return { userID: x.tenantImUserId + "" };
    }),
  };
  if ([TIM.TYPES.GRP_WORK, TIM.TYPES.GRP_AVCHATROOM].includes(form.type)) {
    delete options.joinOption;
  }
  return options;
}
export const createGroup = (form) => {
  tim
    .createGroup(getOptions(form))
    .then((imResponse) => {
      store.commit("showMessage", {
        message: `群组：【${imResponse.data.group.name}】创建成功`,
        type: "success",
      });
      const { group } = imResponse.data;
      tim.getConversationProfile(`GROUP${group.groupID}`).then(({ data }) => {
        console.log(data);
        store.commit("updateCurrentConversation", data.conversation);
        store.dispatch("checkoutConversation", data.conversation.conversationID);
        const { conversationID } = data.conversation;
        store.dispatch("getMessageList", conversationID);
      });
      store.commit("updateCreateGroupModelVisible", false);
    })
    .catch((error) => {
      store.commit("showMessage", {
        type: "error",
        message: error.message,
      });
    });
  return Promise.resolve();
};

export const character = (info) => {
  tim.getConversationProfile(`C2C${info.tenantImUserId}`).then(({ data }) => {
    console.log("getConversationProfile---", data);
    store.commit("updateCurrentConversation", {
      ...data.conversation,
      ...{
        info,
      },
    });
    const { conversationID } = data.conversation;
    store.dispatch("getMessageList", conversationID);
  });
};
