import TIM from "tim-js-sdk";
import TIMUploadPlugin from "tim-upload-plugin";

function receiveMessageType(messageType) {
  switch (messageType) {
    case TIM.TYPES.MSG_TEXT:
      return "text";
    case TIM.TYPES.MSG_IMAGE:
      return "image";
    case TIM.TYPES.MSG_AUDIO:
      return "audio";
    case TIM.TYPES.MSG_VIDEO:
      return "video";
    case TIM.TYPES.MSG_FILE:
      return "file";
    case TIM.TYPES.MSG_CUSTOM:
      return "custom";
    case TIM.TYPES.MSG_MERGER:
    case TIM.TYPES.MSG_LOCATION:
    case TIM.TYPES.MSG_GRP_TIP:
    case TIM.TYPES.MSG_GRP_SYS_NOTICE:
  }
}
function messageType(param) {
  let message = null;
  let type =
    param.message.type == "PRIVATE" ? "CONV_C2C" : "CONV_" + param.message.type;

  if (param.messageType == "text") {
    message = this.tims.createTextMessage({
      to: param.message.id,
      conversationType: TIM.TYPES[type],
      payload: {
        text: param.message.content,
      },
    });
  } else if (param.messageType == "image") {
    message = this.tims.createImageMessage({
      to: param.message.id,
      conversationType: TIM.TYPES[type],
      payload: {
        file: param.message.content,
      },
      onProgress: function (event) {
        console.log("file uploading:", event);
      },
    });
  } else if (param.messageType == "audio") {
    message = this.tims.createAudioMessage({
      to: param.message.id,
      conversationType: TIM.TYPES[type],
      payload: {
        file: param.message.content,
      },
    });
  } else if (param.messageType == "video") {
    message = this.tims.createVideoMessage({
      to: param.message.id,
      conversationType: TIM.TYPES[type],
      payload: {
        file: param.message.content, // 或者用event.target
      },
      onProgress: function (event) {
        console.log("file uploading:", event);
      },
    });
  } else if (param.messageType == "file") {
    message = this.tims.createFileMessage({
      to: param.message.id,
      conversationType: TIM.TYPES[type],
      payload: {
        file: param.message.content,
      },
      onProgress: function (event) {
        console.log("file uploading:", event);
      },
    });
  } else if (param.messageType == "custom") {
    message = this.tims.createCustomMessage({
      to: param.message.id,
      priority: TIM.TYPES['MSG_PRIORITY_HIGH'],
      conversationType: TIM.TYPES[type],
      payload: param.message.payload,
    });
  }
  return message;
}

class TIM2 {
  constructor(options) {
    this.SDKAppID = options.SDKAppID || "";
    this.userID = options.userID;
    this.userSig = options.userSig;
    this.tims = null;
    this.subscribeGroups = [];
    this.ready = false;
    this.create();
  }

  create() {
    if (!this.tims) {
      this.tims = TIM.create({ SDKAppID: this.SDKAppID });
      this.tims.setLogLevel(1);
      this.tims.registerPlugin({ "tim-upload-plugin": TIMUploadPlugin });
      let onSdkReady = (event) => {
        this.ready = true;
        console.log(event);
      };
      this.tims.on(TIM.EVENT.SDK_READY, onSdkReady);
      let onSdkNotReady = function (event) {
        // 如果想使用发送消息等功能，接入侧需驱动 SDK 进入 ready 状态，重新调用 login 接口即可，如下所示：
        // tim.login({userID: 'your userID', userSig: 'your userSig'});
      };
      this.tims.on(TIM.EVENT.SDK_NOT_READY, onSdkNotReady);

      let onMessageModified = function (event) {
        console.log(event);
        // event.data - 存储被第三方回调修改过的 Message 对象的数组 - [Message]
      };
      this.tims.on(TIM.EVENT.MESSAGE_MODIFIED, onMessageModified);
      // this.tims
    }
    return this.tims;
  }

  async connect() {
    await this.tims.login({
      userID: this.userID,
      userSig: this.userSig,
    });
    if (!this.ready) {
      await new Promise((resolve, reject) => {
        const timer = setInterval(() => {
          if (this.ready) {
            clearInterval(timer);
            resolve()
          }
        }, 50);
      })
    }
  }

  disconnect() {
    this.tims.destroy();
  }

  async createGroup(param) {
    console.log('createGroup :>> ', param);
    const params = {
      type: TIM.TYPES[param.type],
      name: param.name,
      // groupID: param.groupID,
      memberList: param.memberList,
    };
    this.subscribeGroups.push(param.groupID);
    return await this.tims.createGroup(params);
  }

  async getGroupList(callback) {
    let promise = this.tims.getGroupList();
    return promise
      .then(function (imResponse) {
        console.log('getGroupList :>> ', imResponse);
        let arr = [];
        let list = imResponse.data.groupList;
        for (let k in list) {
          if (list[k]) {
            let obj = {
              type: list[k].type,
              groupId: list[k].groupID,
              data: { avatar: list[k].avatar, name: list[k].name },
              unread: list[k].muteAllMembers, //未读消息条数
              lastMessage: {
                type: receiveMessageType(list[k].lastMessage.type),
                timestamp: list[k].lastMessage.lastTime,
                senderId: list[k].lastMessage.fromAccount,
                senderData: { avatar: "", nickname: "" },
                payload: { text: list[k].lastMessage.payload.extension },
              },
            };
            arr.push(obj);
          }
        }
        // callback(arr);
        return arr;
      })
      .catch(function (imError) {
        console.warn("getGroupList error:", imError); // 获取群组列表失败的相关信息
      });
  }

  async joinGroup(param) {
    await this.tims.joinGroup({
      groupID: param.groupID,
      type: TIM.TYPES[param.type],
    });
    this.subscribeGroups.push(param.groupID);
  }

  async leaveGroup(groupId) {
    await this.tims.quitGroup(groupId);
    this.subscribeGroups.splice(
      this.subscribeGroups.findIndex((t) => t === groupId),
      1
    );
  }

  async dismissGroup(groupId) {
    await this.tims.dismissGroup(groupId);
    this.subscribeGroups.splice(
      this.subscribeGroups.findIndex((t) => t === groupId),
      1
    );
  }

  async sendMessage(message) {
    return await this.tims.sendMessage(messageType.call(this, message));
  }

  async markMessageRead(param) {
    let converID = "";
    if (param.type == "private") {
      converID = `C2C${param.id}`;
    } else if (param.type == "group") {
      converID = `GROUP${param.id}`;
    } else {
      converID = "@TIM#SYSTEM";
    }
    return await this.tims.setMessageRead({ conversationID: converID });
  }

  async revokeMessage(message) {
    return await this.tims.revokeMessage(message);
  }

  async resendMessage(message) {
    return await this.tims.resendMessage(message);
  }

  async deleteMessage(message) {
    return await this.tims.deleteMessage(message);
  }

  async getMessageList(param, callback) {
    let converID = "";
    if (param.type == "private") {
      converID = `C2C${param.id}`;
    } else if (param.type == "group") {
      converID = `GROUP${param.id}`;
    } else {
      converID = "@TIM#SYSTEM";
    }
    let imResponse = await this.tims.getMessageList({
      conversationID: converID,
      count: 15,
    });
    let arr = [];
    let list = imResponse.data.messageList;
    for (let k in list) {
      if (list[k]) {
        let obj = {
          messageId: list[k].ID,
          type: list[k].type,
          timestamp: list[k].time,
          senderId: list[k].from,
          senderData: {
            avatar: list.memberList[k].avatar,
            nickname: "",
          }, //发送者Data，仅限群聊消息
          payload: list[k].payload,
          groupId: list[k].groupId || "",
        };
        arr.push(obj);
      }
    }
    return arr;
  }

  async subscribeGroup(groups, callback) {
    this.subscribeGroups.push(...groups);
    // let onMessageReceived = function
    this.tims.on(TIM.EVENT.MESSAGE_RECEIVED, (event) => {
      let arr = [];
      console.log("onMessageReceived :>> ", event, this.subscribeGroups);
      for (let k in event.data) {
        if (event.data[k] && this.subscribeGroups.includes(event.data[k].to)) {
          let obj = {
            messageId: event.data[k].ID,
            type: receiveMessageType(event.data[k].type),
            timestamp: event.data[k].time,
            senderId: event.data[k].from,
            senderData: {
              avatar: event.data[k].avatar,
              nickname: event.data[k].nameCard,
            }, //发送者Data，仅限群聊消息
            payload: event.data[k].payload,
            groupId: event.data[k].to || "",
          };
          arr.push(obj);
        }
      }
      callback(arr);
      // event.data - 存储 Message 对象的数组 - [Message]
    });
  }
}

export default TIM2;
