CoreLayout.js 8.4 KB
import React,{ Component, PropTypes } from 'react'; 
import ReactDOM from 'react-dom'; 
import { connect } from 'react-redux';   
import MaskProgress from '../components/widget/mask/MaskProgress';
import {addNewMessage,changeIMShow,choiceMessage,addMyMessage,loadStoreMessage} from '../redux/actions/workIMAction'; 
import { getRongCloudToken,getUserInfo} from '../utils/workIMUtil'
import * as types from '../redux/constants/ActionTypes';   
import store from 'store2';

class CoreLayout extends Component {
  constructor(props) {
    super(props); 
    this.initRongClund=this.initRongClund.bind(this); 
    this.handlNewMessage =  this.handlNewMessage.bind(this);
    this.state={
      initIM:false
    } 
  } 
  static propTypes = {
    children: React.PropTypes.element
  }   
  componentDidMount(){
    const {token,user}=this.props;
    if(token&&user&&user.id){
      this.initRongClund(token,user);
    }
  } 
  componentWillReceiveProps(nextProps){ 
      const {token,user}=nextProps; 
      const {initIM} = this.state; 
      if(token&&user&&user.id&&!initIM){
        this.initRongClund(token,user);
        this.setState({
          initIM:true
        })
      }  
  }
  componentWillUnmount() {  
  } 
  handlNewMessage(message){
    const {dispatch,userMap,selecedUser,user}=this.props;
    const {senderUserId,content:{content=''},sentTime}=message; 
    getUserInfo(senderUserId).then(data => {  
        let count=0;
        if(userMap[senderUserId]){
            count=userMap[senderUserId].messages.length;
            if(senderUserId==selecedUser){
                count=0;
            }else{
                count=userMap[senderUserId].count?userMap[senderUserId].count+1:1;
            }
            userMap[senderUserId].messages.push({
                content,
                sentTime,
                senderUserId,
                name:data.name,
                type:'user'
            })
        }else{  
            if(senderUserId==selecedUser){
                count=0;
            }else{
                count=count+1;
            }
            userMap[senderUserId]=message;
            userMap[senderUserId].messages=[{
                content,
                sentTime,
                senderUserId,
                name:data.name, 
                type:'user'
            }]
        }
        userMap[senderUserId].name=data.name;
        userMap[senderUserId].mobile=data.mobile; 
        userMap[senderUserId].count=count;
        dispatch({
            type        : types.LOAD_USER_MAP,
            userMap     : Object.assign({},userMap)
        });
        if(senderUserId==selecedUser){
            dispatch({
                type            : types.CHANGE_MESSAGES, 
                messages        : userMap[senderUserId].messages.concat([])
            });
        } 
        dispatch(changeIMShow(true));
        store(user.id, Object.assign({},userMap));
    })
    .catch(err => { throw err; });  
  }
  initRongClund(token,user){
    const {appid,dispatch}=this.props,self=this; 
    if(!RongIMLib){
      return 
    }
    RongIMLib.RongIMClient.init(appid);
    // 设置连接监听状态 ( status 标识当前连接状态 )
    // 连接状态监听器
    RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
          switch (status) {
              case RongIMLib.ConnectionStatus.CONNECTED:
                  console.log('链接成功');
                  break;
              case RongIMLib.ConnectionStatus.CONNECTING:
                  console.log('正在链接');
                  break;
              case RongIMLib.ConnectionStatus.DISCONNECTED:
                  console.log('断开连接');
                  break;
              case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                  console.log('其他设备登录');
                  break;
                case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                  console.log('域名不正确');
                  break;
              case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                console.log('网络不可用');
                break;
              }
        }
    }); 
     // 消息监听器
    RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: function (message) { 
            // 判断消息类型
            switch(message.messageType){
                case RongIMClient.MessageType.TextMessage:
                  self.handlNewMessage(message) 
                    // message.content.content => 消息内容
                    break;
                case RongIMClient.MessageType.VoiceMessage:
                    // 对声音进行预加载                
                    // message.content.content 格式为 AMR 格式的 base64 码
                    break;
                case RongIMClient.MessageType.ImageMessage:
                   // message.content.content => 图片缩略图 base64。
                   // message.content.imageUri => 原图 URL。
                   break;
                case RongIMClient.MessageType.DiscussionNotificationMessage:
                   // message.content.extension => 讨论组中的人员。
                   break;
                case RongIMClient.MessageType.LocationMessage:
                   // message.content.latiude => 纬度。
                   // message.content.longitude => 经度。
                   // message.content.content => 位置图片 base64。
                   break;
                case RongIMClient.MessageType.RichContentMessage:
                   // message.content.content => 文本消息内容。
                   // message.content.imageUri => 图片 base64。
                   // message.content.url => 原图 URL。
                   break;
                case RongIMClient.MessageType.InformationNotificationMessage:
                    // do something...
                   break;
                case RongIMClient.MessageType.ContactNotificationMessage:
                    // do something...
                   break;
                case RongIMClient.MessageType.ProfileNotificationMessage:
                    // do something...
                   break;
                case RongIMClient.MessageType.CommandNotificationMessage:
                    // do something...
                   break;
                case RongIMClient.MessageType.CommandMessage:
                    // do something...
                   break;
                case RongIMClient.MessageType.UnknownMessage:
                    // do something...
                   break;
                default:
                    // do something...
            }
        }
    }); 
    RongIMClient.connect(token, {
          onSuccess: function(userId) {
            console.log("Connect successfully." + userId);
          },
          onTokenIncorrect: function() {
            console.log('token无效');
          },
          onError:function(errorCode){
                var info = '';
                switch (errorCode) {
                  case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                  case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                  case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                  case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                  case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
                }
                console.log(errorCode);
          }
    });
    dispatch(loadStoreMessage(user.id)); 
  }  
  render () { 
    const {maskShow,maskShowTitle}=this.props;
    return ( 
      <div className='view-container'>
        {this.props.children} 
        <MaskProgress show={maskShow} title={maskShowTitle}></MaskProgress>
      </div> 
    )
  }
}


const mapStateToProps = (state) => {    
  const {setting:{maskShow,maskShowTitle}}=state;
  const { workIM:{appid,token,userMap,messages,showChat,selecedUser}} = state;
  const { authed:{userInfo={}}} = state;
  const {user,tenant} = userInfo;
  return { 
    maskShow,
    maskShowTitle,
    appid, 
    token,
    userMap,
    showChat,
    messages,
    selecedUser,
    user,
    tenant 
  };
}
 
export default connect(mapStateToProps)(CoreLayout)