
const imsdk = require('bindings')("imsdk");
/*
 * Web IM 相关
 */
var im_init = false;

var return_cb = (func, ret) => {
}

var recvmsg_cb = (json_msg_array) => {
  var jsondata = JSON.parse(json_msg_array);
  log.info("[TAG-WEBIM] recv msg: " + json_msg_array);
  log.info(g_data.classInfo);
  for (var i in jsondata) {
    if (jsondata[i].message_conv_id === g_data.classInfo.chat_group_id) {
      var elems = jsondata[i].message_elem_array;
      for (var m in elems) {
        var elem = elems[m];
        var type = elem.elem_type;
        if (type == 0) {
          sendIpcMessage('IM:RecvTextMsg', elem.text_elem_content, jsondata[i].message_server_time, jsondata[i].message_sender);
        } else {
          log.info("[TAG-WEBIM] onMsgNotify->ignore msg type: " + type);
        }
      }
    } else if (jsondata[i].message_conv_id == g_data.classInfo.cmd_group_id) {
      var elems = jsondata[i].message_elem_array;
      for (var m in elems) {
        var elem = elems[m];
        var type = elem.elem_type;
        if (type == 3) {
          if (elem.custom_elem_ext == "TXWhiteBoardExt" && !jsondata[i].message_is_from_self) {
            log.info("IM:RecvBoardMsg  " + elem.custom_elem_data + " groupid " + jsondata[i].message_conv_id + " sender " + jsondata[i].message_sender)
            sendIpcMessage('IM:RecvBoardMsg', elem.custom_elem_data, jsondata[i].message_conv_id, jsondata[i].message_sender);
          } else if (elem.custom_elem_ext == "BCUSTOM") {
          } else if (elem.custom_elem_ext == "CTRL") {//收到控制类消息
            sendIpcMessage('IM:RecvCtrlMsg', elem.custom_elem_data, jsondata[i].message_conv_id, jsondata[i].message_sender);//递交给主进程
          }
        } else {
          log.info("[TAG-WEBIM] onMsgNotify->ignore msg type: " + type);
        }
      }
    } else {
      log.info("[TAG-WEBIM] onMsgNotify->ignore Msg from: " + jsondata[i].message_sender);
    }

  }
}

var grouptips_event_cb = (json_group_tip_array) => {
}

var conv_event_cb = (conv_event, json_conv_array) => {
}

var networkstatus_cb = (status, code, desc) => {
}

var kickedoff_cb = () => {
}

var usersig_expired_cb = () => {
}

var logout_cb = (code, desc, params) => {

}

var convlist_cb = (code, desc, params) => {

}

var createconv_cb = (code, desc, params) => {

}

var deleteconv_cb = (code, desc, params) => {

}

var sendmsg_cb = (code, desc, params) => {

}

var creategroup_cb = (code, desc, params) => {

}

var deletegroup_cb = (code, desc, params) => {

}

var joingroup_cb = (code, desc, params) => {

}

var quitgroup_cb = (code, desc, params) => {
}

function initIMSDK(log_path) {
  if (!im_init) {
    if (!log_path) {
      var row = {};
      row.sdk_config_log_file_path = log_path;
      var jsonStr = JSON.stringify(row);
      imsdk.TIMInit(g_data.sdkAppId, jsonStr);
    }
    else
    imsdk.TIMInit(g_data.sdkAppId, "");
    // var row = {};
    // row.set_config_is_log_output_console = false;
    // var jsonStr = JSON.stringify(row);
    // imsdk.TIMSetConfig(jsonStr, function (code, desc, params) {
    // });
    imsdk.TIMSetRecvNewMsgCallback(recvmsg_cb);
    // imsdk.TIMSetGroupTipsEventCallback(grouptips_event_cb);
    // imsdk.TIMSetConvEventCallback(conv_event_cb);
    // imsdk.TIMSetNetworkStatusListenerCallback(networkstatus_cb);
    // imsdk.TIMKickedOfflineCallback(kickedoff_cb);
    // imsdk.TIMUserSigExpiredCallback(usersig_expired_cb);
    // imsdk.TIMSetReturnCallback(return_cb);
    im_init = true;
  }
}

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

//监听连接状态回调变化事件
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;
      alert("连接状态恢复正常" + 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;
  //获取所有聊天会话
  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) {
          //  debugger;
          //  sendIpcMessage('IM:RecvTextMsg', content.getText(), webim.Tool.formatTimeStamp(newMsg.getTime()),newMsg.getFromAccount());
          sendIpcMessage('IM:RecvTextMsg', content.getText(), newMsg.getTime(), newMsg.getFromAccount());
        } 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("IM:RecvBoardMsg  " + content.getData() + " groupid " + newMsg.getSession().id() + " sender " + newMsg.getFromAccount())
            sendIpcMessage('IM:RecvBoardMsg', content.getData(), newMsg.getSession().id(), newMsg.getFromAccount());
          } else if (content.getExt() == "BCUSTOM") {
          } else if (content.getExt() == "CTRL") {//收到控制类消息
            sendIpcMessage('IM:RecvCtrlMsg', content.getData(), newMsg.getSession().id(), newMsg.getFromAccount());//递交给主进程
          }
        }
      }
    } else {
      log.info("[TAG-WEBIM] onMsgNotify->ignore Msg from: " + newMsg.getSession().id());
    }
  }
}

function onKickedEventCall() {
}

//监听 C2C 消息通道的处理，方法在 receive_new_msg.js 文件中
function onC2cEventNotifys(msg) {
}

// 登录WebIMSDK
function loginWebIm(userId, userSig, callback) {
  g_data.userId = userId;
  g_data.userSig = userSig;
  log.info("[TAG-WEBIM] loginWebIm->start login sig:" + userSig);
  imsdk.TIMLogin(g_data.userId, g_data.userSig, function (code, desc, params) {
    if (code === 0) {
      log.info("[TAG-WEBIM] login success: " + g_data.userId);
      callback(0, "");

    } else {
      log.info("[TAG-WEBIM] login failed: " + desc);
      callback(-1, desc);
      showAlertMsg(desc);
    }
  });
}

// 获取我的群组
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);
    }
  )
}


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);
    }
  )
}

function joinGroup(groupId, callback) {
  log.info("[TAG-WEBIM] joinGroup->start join group:" + groupId);
  imsdk.TIMGroupJoin(groupId, "", function (code, desc, param) {
    if (code === 0) {
      callback(0, desc);
      log.info("[TAG-WEBIM] join Group [" + groupId + "] success");
    } else {
      log.info("[TAG-WEBIM] join Group [" + groupId + "] fail: " + code + ", " + desc);
      callback(code, desc);
    }
  });
}

function sendCustomMessage(groupId, data, ext) {
  let elemArray = [];
  let elem = {};
  elem.elem_type = 3;
  elem.custom_elem_data = data;
  elem.custom_elem_ext = ext;
  elemArray.push(elem);
  let msg = {};
  msg.message_elem_array = elemArray;
  sendMessage(groupId, JSON.stringify(msg));
}

function sendTextMessage(groupId, text) {
  log.info("[TAG-WEBIM] txt " + text);
  let elemArray = [];
  let elem = {};
  elem.elem_type = 0;
  elem.text_elem_content = text;
  elemArray.push(elem);
  let msg = {};
  msg.message_elem_array = elemArray;
  sendMessage(groupId, JSON.stringify(msg));
  sendIpcMessage('IM:RecvTextMsg', text, Math.floor(Date.now() / 1000), g_data.userId);
}

function sendMessage(groupId, content) {
  imsdk.TIMMsgSendNewMsg(groupId, 2, content, (code, desc, param) => {    
    if (code != 0) {
      log.warn("[TAG-WEBIM] sendMessage->groupId:" + groupId + ", code: " + code + " param " + param);
    }
  });
}
