/*
 * Web IM 相关
 */

 //监听 C2C 消息通道的处理，方法在 receive_new_msg.js 文件中
var onC2cEventNotifys = {
   '96': (notify)=>{
     log.error("[TAG-WEBIM] onC2cEventNotifys->kickoff");
     showErrorMsg("您的帐号已在其他终端登录!");
   }
 }

var listeners = {
  "onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填
  "jsonpCallback": jsonpCallback, //IE9(含)以下浏览器用到的 jsonp 回调函数，
  "onMsgNotify": onMsgNotify, //监听新消息(私聊，普通群(非直播聊天室)消息，全员推送消息)事件，必填
  "onKickedEventCall": onKickedEventCall, //被其他登录实例踢下线
  "onC2cEventNotifys": onC2cEventNotifys//监听 C2C 系统消息通道
};

// 默认处理收文本消息
var onRecvTextMsg = function (text, time, acount, nick) {
  log.warn("[TAG-WEBIM] onRecvTextMsg->ignore text message");
}
// 默认处理收白板消息
var onRecvBoardMsg = function (data, sessionId, acount) {
  log.warn("[TAG-WEBIM] onRecvBoardMsg->ignore text message");
}
// 默认处理控制消息
var onRecvCtrlMsg = function (data, sessionId, acount) {
  log.warn("[TAG-WEBIM] onRecvCtrlMsg->ignore text message");
}
// 默认处理容器消息
var onRecvContainerMsg = function (data, sessionId, acount) {
  log.warn("[TAG-WEBIM] onRecvContainerMsg->ignore text message");
}

//监听连接状态回调变化事件
var onConnNotify = function (resp) {
  var info;
  switch (resp.ErrorCode) {
    case webim.CONNECTION_STATUS.ON:
      webim.Log.warn('建立连接成功: ' + resp.ErrorInfo);
      break;
    case webim.CONNECTION_STATUS.OFF:
      info = '连接已断开，无法收到新消息，请检查下您的网络是否正常: ' + resp.ErrorInfo;
      showAlertMsg("连接已断开: " + info);
      webim.Log.warn(info);
      break;
    case webim.CONNECTION_STATUS.RECONNECT:
      info = '连接状态恢复正常: ' + resp.ErrorInfo;
      showAlertMsg("连接状态恢复正常" + info);
      webim.Log.warn(info);
      break;
    default:
      webim.Log.error('未知连接状态: =' + resp.ErrorInfo);
      break;
  }
};

//位于 js/demo_base.js 中
//IE9(含)以下浏览器用到的 jsonp 回调函数
function jsonpCallback(rspData) {
  //设置 jsonp 返回的
  webim.setJsonpLastRspData(rspData);
}

//监听新消息事件
//newMsgList 为新消息数组，结构为[Msg]
function onMsgNotify(newMsgList) {
  //console.warn(newMsgList);
  var sess, newMsg;
  //获取所有聊天会话
  //log.info("[TAG-WEBIM] onMsgNotify->enter");
  // 被踢后不处理消息
  if (is_kicked_off)return;
  var sessMap = webim.MsgStore.sessMap();
  for (var j in newMsgList) {//遍历新消息
    newMsg = newMsgList[j];
    if (newMsg.getSession().id() == g_data.classInfo.chat_group_id) { //为当前聊天对象的消息
      var elems = newMsg.getElems();
      for (var i in elems) {
        var elem = elems[i];
        var content = elem.getContent();
        if (elem.getType() == webim.MSG_ELEMENT_TYPE.TEXT) {
          log.info("[TAG-WEBIM] onMsgNotify->new text message from: " + newMsg.getFromAccount());
          getUserNickName(newMsg.getFromAccount(), (nick) => { //获取昵称
            onRecvTextMsg(content.getText(), newMsg.getTime(), newMsg.getFromAccount(), nick);
          })
        } else {
          log.info("[TAG-WEBIM] onMsgNotify->ignore msg type: " + elem.getType());
        }
      }
    } else if (newMsg.getSession().id() == g_data.classInfo.cmd_group_id) { // 收到信令消息
      var elems = newMsg.getElems();
      for (var i in elems) {
        var elem = elems[i];
        var content = elem.getContent();
        if (elem.getType() == webim.MSG_ELEMENT_TYPE.CUSTOM) {//自定义消息
          if (content.getExt() == "TXWhiteBoardExt" && !newMsg.isSend) {
            log.info("[TAG-WEBIM] onMsgNotify MSG_ELEMENT_TYPE. WhiteBoard  " + content.getData() + " groupid " + newMsg.getSession().id() + " account " + newMsg.getFromAccount());
            onRecvBoardMsg(content.getData(), newMsg.getSession().id(), newMsg.getFromAccount());
          } else if (content.getExt() == "BCUSTOM") {

          } else if (content.getExt() == "CTRL") {//收到控制类消息
            log.info("[TAG-WEBIM] onMsgNotify MSG_ELEMENT_TYPE. CTRL: " + content.getData() + "  groupid  " + newMsg.getSession().id() + " account " + newMsg.getFromAccount());
            onRecvCtrlMsg(content.getData(), newMsg.getSession().id(), newMsg.getFromAccount());
          } else if (content.getExt() == "CONTAINER") {//收到容器类消息
            log.info("[TAG-WEBIM] [TAG-CONTAINER] onMsgNotify MSG_ELEMENT_TYPE. CONTAINER: " + content.getData() + "  groupid  " + newMsg.getSession().id() + " account " + newMsg.getFromAccount());
            onRecvContainerMsg(content.getData(), newMsg.getSession().id(), newMsg.getFromAccount());
          }
        }
      }
    } else {
      log.info("[TAG-WEBIM] onMsgNotify->ignore Msg from: " + newMsg.getSession().id());
    }
  }
}

function onKickedEventCall() {
  log.error("[TAG-WEBIM] onKickedEventCall->enter");
  showErrorMsg("您的帐号已在其他地方登录!");
}

// 登录WebIMSDK
function loginWebIm(userId, userSig, callback) {
  g_data.userId = userId;
  g_data.userSig = userSig;
  log.info("[TAG-WEBIM] loginWebIm->start login userId:" + userId+", sdkappid: "+g_data.sdkAppId);
  webim.login({
    sdkAppID: g_data.sdkAppId,
    accountType: "" + g_data.sdkAppId,
    identifier: g_data.userId,
    userSig: g_data.userSig
  }, listeners, {},
    function (resp) {
      log.info("[TAG-WEBIM] login success: " + g_data.userId);
      callback(0, "");
    },
    function (err) {
      log.info("[TAG-WEBIM] login failed: " + err.ErrorInfo);
      callback(-1, err.ErrorInfo);
      //alert(err.ErrorInfo);
    })
}

// 注销webIM
function logoutWebIm(callback){
  webim.logout((rsp)=>{
    callback(true);
  }, (err)=>{
    callback(false);
  })
}

// 获取我的群组
function getGroupList(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(data);
    },
    function (err) {
      showAlertMsg(err.ErrorInfo);
    }
  )
}

// 创建Im群组
function createGroup(groupId, callback) {
  var globalData = require('electron').remote.getGlobal('data');
  var options = {
    'GroupId': groupId,
    'Owner_Account': g_data.userId,
    'Type': 'ChatRoom',
    'Name': groupId,
    'MemberList': []
  };
  log.info("[TAG-WEBIM] createGroup->start create group:" + groupId)
  webim.createGroup(
    options,
    function (resp) {
      callback(0, resp);
      log.info("[TAG-WEBIM] create Group success");
    },
    function (err) {
      callback(err.ErrorCode, err.ErrorInfo);
    }
  )
}

// 加入IM群组
function joinGroup(groupId, callback) {
  var options = {
    'GroupId': groupId
  };
  log.info("[TAG-WEBIM] joinGroup->start join group:" + groupId)
  webim.applyJoinGroup(
    options,
    function (resp) {
      callback(0, resp);
      log.info("[TAG-WEBIM] join Group [" + groupId + "] success");
    },
    function (err) {
      log.info("[TAG-WEBIM] join Group [" + groupId + "] fail: " + err.ErrorCode + ", " + err.ErrorInfo);
      callback(err.ErrorCode, err.ErrorInfo);
    }
  )
}

// 发送自定义消息
function sendCustomMessage(groupId, data, ext) {
  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, g_data.userId, 0, "");
  var customObj = new webim.Msg.Elem.Custom(data, "", ext);
  msg.addCustom(customObj);
  webim.sendMsg(msg, (rsp) => {
    log.info("[TAG-WEBIM] sendCustomMessage->groupId:" + groupId + ", rsp: " + rsp);
  });
}

// 发送文本消息
function sendTextMessage(groupId, text) {
  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, g_data.userId, 0, "");
  var textObj = new webim.Msg.Elem.Text(text);
  msg.addText(textObj);
  webim.sendMsg(msg, (rsp) => {
    log.info("[TAG-WEBIM] sendTextMessage->groupId:" + groupId + ", rsp: " + rsp);
  });
}

// 设置文本消息处理回调
function setRecvTextMsgListener(listener) {
  onRecvTextMsg = listener;
}
// 设置白板消息处理回调
function setRecvBoardMsgListener(listener) {
  onRecvBoardMsg = listener;
}
// 设置控制消息处理回调
function setRecvCtrlMsgListener(listener) {
  onRecvCtrlMsg = listener;
}

// 设置控制消息处理回调
function setRecvContainerMsgListener(listener) {
  onRecvContainerMsg = listener;
}
