const log = require('electron-xlog');

var onC2cEventNotifys = {
  '96': (notify)=>{
    module.exports.onKickedEventCall();
    this.log("[TAG-WEBIM] onC2cEventNotifys->kickoff");
  }
}

module.exports = {
    isIMLogin: false,
    userId: '',

    listeners: {},

    onC2cEventNotifys: {
        '96': (notify)=>{
            this.log("[TAG-WEBIM] onC2cEventNotifys->kickoff");
            this.notifyEvent(-1, '您的帐号已在其他终端登录!');
        }
    },    
    inner_listeners: {
        "onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填
        "jsonpCallback": jsonpCallback, //IE9(含)以下浏览器用到的 jsonp 回调函数，
        "onMsgNotify": onMsgNotify, //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
        "onKickedEventCall": onKickedEventCall, //被其他登录实例踢下线
        "onC2cEventNotifys": onC2cEventNotifys//监听 C2C 系统消息通道
    },
    /** 对外接口 */
    init: function(onErrorCallback){
        this.listeners.onError = onErrorCallback;
    },
    setMsgRecvListener: function(listener){
        this.listeners.onMsgRecv = listener;
    },
    /** 登录相关 */
    login: function(sdkAppId, userId, userSig, callback){
        webim.login({
                sdkAppID: sdkAppId,
                accountType: ""+sdkAppId,
                identifier: userId,
                userSig: userSig
            }, this.inner_listeners, {isLogOn: false}, 
            (rsp)=>{
                this.isIMLogin = true;
                this.userId = userId;
                this.log("[TAG-WEBIM] login->success: "+userId);
                callback(0, "");
            },
            (err)=>{
                this.log("[TAG-WEBIM] login->failed: "+err.ErrorInfo);
                callback(err.ErrorCode, err.ErrorInfo);
            })
    },
    logout: function(callback){
        webim.logout((rsp)=>{
            this.isIMLogin = false;
            callback(true);
        }, (err)=>{
            callback(false);
        })
    },
    /** 群组相关 */
    createGroup: function(groupId, callback) {
        var options = {
          'GroupId': groupId,
          'Owner_Account': this.userId,
          'Type': 'ChatRoom',
          'Name': groupId,
          'MemberList': []
        };
        this.log("[TAG-WEBIM] createGroup->start create group:" + groupId)
        webim.createGroup(
          options,
          function (resp) {
            callback(0, resp);
          },
          function (error) {
            log.error("[TAG-WEBIM] createGroup->fail: "+error.ErrorCode+"|"+error.ErrorInfo);
            callback(error.ErrorCode, error.ErrorInfo);
          }
        )
    },
    joinGroup: function(groupId, callback) {
        var options = {
          'GroupId': groupId
        };
        this.log("[TAG-WEBIM] joinGroup->start join group:" + groupId)
        webim.applyJoinGroup(
          options,
          function (resp) {
            callback(0, resp);            
          },
          function (error) {
            log.error("[TAG-WEBIM] joinGroup->fail: "+error.ErrorCode+"|"+error.ErrorInfo);
            callback(error.ErrorCode, error.ErrorInfo);
          }
        )
    },    
    getGroupList: function(callback) {
        var options = {
          'Member_Account': g_data.userId,
          'Limit': 20,
          'Offset': 0,
          'GroupBaseInfoFilter': [
            'Type',
            'Name',
            'Introduction',
            'Notification',
            'FaceUrl',
            'CreateTime',
            'Owner_Account',
            'LastInfoTime',
            'LastMsgTime',
            'NextMsgSeq',
            'MemberNum',
            'MaxMemberNum',
            'ApplyJoinOption',
            'ShutUpAllMember'
          ],
          'SelfInfoFilter': [
            'Role',
            'JoinTime',
            'MsgFlag',
            'UnreadMsgNum'
          ]
        };
        webim.getJoinedGroupListHigh(
          options,
          function (rsp) {
            if (!rsp.GroupIdList || rsp.GroupIdList.length == 0) {
              //alert('您目前还没有加入任何群组');
              return;
            }
            var data = [];
            for (var i = 0; i < rsp.GroupIdList.length; i++) {
              var group_id = rsp.GroupIdList[i].GroupId;
              var name = webim.Tool.formatText2Html(rsp.GroupIdList[i].Name);
              var type_en = rsp.GroupIdList[i].Type;
              var type = webim.Tool.groupTypeEn2Ch(rsp.GroupIdList[i].Type);
              var role_en = rsp.GroupIdList[i].SelfInfo.Role;
              var role = webim.Tool.groupRoleEn2Ch(rsp.GroupIdList[i].SelfInfo.Role);
              var msg_flag = webim.Tool.groupMsgFlagEn2Ch(rsp.GroupIdList[i].SelfInfo.MsgFlag);
              var msg_flag_en = rsp.GroupIdList[i].SelfInfo.MsgFlag;
              var join_time = webim.Tool.formatTimeStamp(rsp.GroupIdList[i].SelfInfo.JoinTime);
              var member_num = rsp.GroupIdList[i].MemberNum;
              var notification = webim.Tool.formatText2Html(rsp.GroupIdList[i].Notification);
              var introduction = webim.Tool.formatText2Html(rsp.GroupIdList[i].introduction);
              var ShutUpAllMember = rsp.GroupIdList[i].ShutUpAllMember;
              data.push({
                'GroupId': group_id,
                'Name': name,
                'TypeEn': type_en,
                'Type': type,
                'RoleEn': role_en,
                'Role': role,
                'MsgFlagEn': msg_flag_en,
                'MsgFlag': msg_flag,
                'MemberNum': member_num,
                'Notification': notification,
                'Introduction': introduction,
                'JoinTime': join_time,
                'ShutUpAllMember': ShutUpAllMember
              });
            }
            callback(ret, data);
          },
          function (err) {
            callback(false, err.ErrorInfo);
          }
        )
    },
    /** 消息相关 */
    sendTextMessage: function(groupId, text, callback=null) {
        if (!text || text.length==0) callback && callback();
        var session = new webim.Session(webim.SESSION_TYPE.GROUP, groupId, groupId, "", Math.round(new Date().getTime() / 1000));
        var msg = new webim.Msg(session, true, -1, -1, -1, this.userId, 0, "");
        var textObj = new webim.Msg.Elem.Text(text);
        msg.addText(textObj);
        webim.sendMsg(msg, (rsp) => {
          this.log("[TAG-WEBIM] sendTextMessage->groupId:" + groupId + ", rsp: " + rsp.ErrorCode+"|"+rsp.ErrorInfo);
          if (null != callback) callback();
        });
    },
    sendCustomMessage: function(groupId, data, ext, callback=null) {
      if (!data || data.length==0) callback && callback();
        var session = new webim.Session(webim.SESSION_TYPE.GROUP, groupId, groupId, "", Math.round(new Date().getTime() / 1000));
        var msg = new webim.Msg(session, true, -1, -1, -1, this.userId, 0, "");
        var customObj = new webim.Msg.Elem.Custom(data, "", ext);
        msg.addCustom(customObj);
        webim.sendMsg(msg, (rsp) => {
          rsp.ErrorCode!=0 && this.log("[TAG-WEBIM] sendCustomMessage->groupId:" + groupId + ", rsp: " + rsp.ErrorCode+"|"+rsp.ErrorInfo);
          if (null != callback) callback();
        });
    },

    /** 测试 */
    log: function(msg){
        log.info(msg);
    },
    err: function(msg){
        log.error(msg);
    },

    /** 内部接口 */
    notifyEvent: function(code, msg){
        if (this.listeners.hasOwnProperty('onError')){
            this.listeners.onError(code, msg);
        }
    },
    onKickedEventCall: function(){
      this.log("[TAG-WEBIM] onKickedEventCall->您的帐号已在其他地方登录");
      this.notifyEvent(-2, '您的帐号已在其他地方登录!');
    },
    onMsgNotify: function(newMsgList) {
        //console.warn(newMsgList);
        var sess, newMsg;

        // 被踢后不处理消息
        if (!this.isIMLogin)return;
        //获取所有聊天会话
        var sessMap = webim.MsgStore.sessMap();
        for (var j in newMsgList) {//遍历新消息
            newMsg = newMsgList[j];
            var elems = newMsg.getElems();
            for (var i in elems) {
                var elem = elems[i];
                if (this.listeners.hasOwnProperty('onMsgRecv')){
                    this.listeners.onMsgRecv(newMsg.getSession().id(), newMsg.getFromAccount(), elem, newMsg.getTime());
                }
            }
        }
    },
    onConnNotify: function (resp) {
        var info;
        switch (resp.ErrorCode) {
          case webim.CONNECTION_STATUS.ON:
            this.log('[TAG-WEBIM] 建立连接成功: ' + resp.ErrorInfo);
            webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
            break;
          case webim.CONNECTION_STATUS.OFF:
            info = '连接已断开，无法收到新消息，请检查下您的网络是否正常: ' + resp.ErrorInfo;
            this.log("[TAG-WEBIM] "+info);
            this.notifyEvent(1, "连接已断开: " + info);
            webim.Log.warn(info);
            break;
          case webim.CONNECTION_STATUS.RECONNECT:
            info = '连接状态恢复正常: ' + resp.ErrorInfo;
            this.log('[TAG-WEBIM] 连接状态恢复正常: ' + info);
            this.notifyEvent(2, "连接状态恢复正常" + info);
            webim.Log.warn(info);
            break;
          default:
              this.log('[TAG-WEBIM] 未知连接状态: ' + resp.ErrorInfo);
            webim.Log.error('未知连接状态: =' + resp.ErrorInfo);
            break;
        }
    },
}

/** 外部事件监听(liteav不支持子方法) */
function onMsgNotify(newMsgList) {
  module.exports.onMsgNotify(newMsgList);
}
function onConnNotify(resp){
  module.exports.onConnNotify(resp);
}
function jsonpCallback(rspData){
  webim.setJsonpLastRspData(rspData);
}
function onKickedEventCall(){
  module.exports.onKickedEventCall();
}