/**
 * 当前会话内容
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import tim from '../../../utils/im/imInitialize';
import { message, Button, Avatar } from 'antd';
import './im.less';
import MessageSendBox from './MessageSendBox';
import TextElement from './Message/TextElement';
import ImageElement from './Message/ImageElement';
import SoundElement from './Message/SoundElement';
import FileElement from './Message/FileElement';
import GroupSystemNoticeElement from './Message/GroupSystemNoticeElement';
import CustomSoundElement from './Message/CustomSoundElement';
import { getFullDate } from '../../../utils/utils';
import Close from './Close';
import Record from '../Record';
@connect(state => ({
  isCompleted: state.im.isCompleted,
  nextReqMessageID: state.im.nextReqMessageID,
  currentUserProfile: state.im.currentUserProfile,
  currentMessageList: state.im.currentMessageList,
  currentConversation: state.im.currentConversation,
  ownName: state.user.currentUser.name,
  ownAvatar: state.user.currentUser.avatar
}))
export default class CurrentConversation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: props.visible,
      currentMessageList: this.props.currentMessageList, //这个不用渲染数据，只用来记录是否有新数据的传入
      // preScrollHeight: 0
      startRecord: false, //是否开始录音(用来判断显示录音的页面是否出现)
      sendSoundURL: null, //录完音要发送的录音路径
      sendSoundTime: null, //录完音的时长
      key: props.key,
      isSeeMore: false
    };
  }

  componentDidMount() {
    this.scrollMessageListToButtom();
  }
  componentWillReceiveProps(nextProps) {
    this.setState({
      currentMessageList: nextProps.currentMessageList,
      key: nextProps.key
    });
    // if (
    //   this.props.currentMessageList.length !==
    //   this.state.currentMessageList.length
    // ) {
    //   //当前的会话打开的时候就要进行已读上传
    //   tim.setMessageRead({
    //     conversationID: this.props.currentConversation.conversationID
    //   });
    //   this.scrollMessageListToButtom();
    // }
    if (
      nextProps.currentMessageList.length > this.state.currentMessageList.length
    ) {
      tim.setMessageRead({
        conversationID: this.props.currentConversation.conversationID
      });
      if (this.state.isSeeMore) {//是查看更多的时候，就不需要滑动到底部
        this.setState({
          isSeeMore: false
        });
      } else {
        this.scrollMessageListToButtom();
      }
    }
  }
  // 直接滚到底部
  scrollMessageListToButtom() {
    const that = this;
    let t2 = window.setInterval(function() {
      // console.log('每隔1秒钟执行一次');
      if (that.refs.messageList) {
        that.refs.messageList.scrollIntoView(true);
        window.clearInterval(t2);
      }
    }, 50);
  }
  //查看更多
  getMessageList() {
    if (this.props.isCompleted) {
      message.info('没有更多的历史消息了');
      return;
    }
    const { nextReqMessageID, currentMessageList } = this.props;
    tim
      .getMessageList({
        conversationID: this.props.currentConversation.conversationID,
        nextReqMessageID,
        count: 15
      })
      .then(imReponse => {
        this.setState({
          isSeeMore: true
        });
        // 更新messageID，续拉时要用到
        this.props.dispatch({
          type: 'im/updateCurrentConversationCont',
          payload: {
            nextReqMessageID: imReponse.data.nextReqMessageID,
            isCompleted: imReponse.data.isCompleted,
            currentMessageList: [
              ...imReponse.data.messageList,
              ...currentMessageList
            ] // 更新当前消息列表，从头部插入
          }
        });
      });
  }
  render() {
    let name = ''; //会话名称
    let avatar = ''; //会话头像
    if (this.props.currentConversation.type === 'C2C') {
      name = this.props.currentConversation.userProfile.nick;
      avatar = this.props.currentConversation.userProfile.avatar;
    } else if (this.props.currentConversation.type === 'GROUP') {
      name = this.props.currentConversation.groupProfile.name;
      avatar = require('../../../assets/images/prevention/group.png');
    }
    return (
      <div className="current-conversation-wrapper" key={this.state.key}>
        {// this.state.startRecord ? (
        this.state.startRecord && (
          <Record
            sendSound={(url, time) => {
              this.setState({
                sendSoundURL: url,
                sendSoundTime: time
              });
            }}
            startRecord={this.state.startRecord}
          />
        )
        }
        <div className="current-conversation">
          <div className="current-header">
            {avatar ? (
              <img src={avatar}></img>
            ) : (
              <div className="span-header">
                <span>
                  {name ? name.substring(name.length - 2, name.length) : ''}
                </span>
              </div>
            )}
            <div>
              <span
                className="conversation-name text-ellipsis"
                style={{ maxWidth: '60%' }}
              >
                {name}
              </span>
            </div>
            <Close
              closeClick={() => {
                //重置当前打开的会话消息
                this.props.dispatch({
                  type: `im/updateCurrentConversation`,
                  payload: {}
                });
                this.props.closeClick();
              }}
            />
          </div>
          <div className="content">
            <div className="message-list">
              <div
                type="text"
                style={{
                  textAlign: 'center',
                  color: '#409EFF',
                  cursor: 'pointer',
                  display: this.props.isCompleted ? 'none' : 'block'
                }}
                onClick={() => {
                  this.getMessageList();
                }}
              >
                查看更多
              </div>
              {this.props.currentMessageList.map((item, index) => {
                const isMine = item.flow === 'out';
                let content = null; //对话内容
                //选择对话的类型
                if (item.type === 'TIMTextElem') {
                  content = (
                    <TextElement
                      isMine={item.flow === 'out'}
                      payload={item.payload}
                      index={index}
                    />
                  );
                } else if (item.type === 'TIMImageElem') {
                  //图片
                  content = (
                    <ImageElement payload={item.payload} index={index} />
                  );
                } else if (item.type === 'TIMSoundElem') {
                  //移动端发过来语音
                  content = (
                    <SoundElement payload={item.payload} index={index} />
                  );
                } else if (item.type === 'TIMCustomElem') {
                  //web端发过去自定义语音
                  content = (
                    <CustomSoundElement payload={item.payload} index={index} />
                  );
                } else if (item.type === 'TIMFileElem') {
                  //文件
                  content = (
                    <FileElement payload={item.payload} index={index} />
                  );
                } else if (item.type === 'TIMGroupSystemNoticeElem') {
                  //系统消息
                  content = (
                    <GroupSystemNoticeElement
                      payload={item.payload}
                      index={index}
                    />
                  );
                }
                let form = '';
                let formName = '';
                let inform = '';
                //群消息的情况（谁谁创建了群组之类的消息）
                if (
                  this.props.currentConversation.type === 'GROUP' &&
                  item.type === 'TIMCustomElem' &&
                  item.elements[0].content.data === 'group_create'
                ) {
                  inform = item.elements[0].content.extension;
                  return (
                    <div
                      className="message-wrapper position-center"
                      key={index}
                    >
                      {inform}
                    </div>
                  );
                } else {
                  //个人对话的情况
                  if (isMine) {
                    //如果是自己发的消息
                    // form = this.props.currentUserProfile.avatar;
                    // formName = this.props.currentUserProfile.nick;
                    form = this.props.ownAvatar;
                    formName = this.props.ownName;
                  } else {
                    //接收的消息
                    form =
                      item.avatar ||
                      (this.props.currentConversation.userProfile &&
                        this.props.currentConversation.userProfile.avatar);
                    formName =
                      item.nick ||
                      (this.props.currentConversation.userProfile &&
                        this.props.currentConversation.userProfile.nick);
                    // form=this.props.currentConversation.userProfile.nick
                    // formName =
                    //   this.props.currentConversation.userProfile &&
                    //   this.props.currentConversation.userProfile.nick;
                  }
                  return (
                    <div
                      className={
                        isMine
                          ? 'message-wrapper position-right'
                          : 'message-wrapper position-left'
                      }
                      key={index}
                    >
                      {isMine ? (
                        <div
                          className="from"
                          style={{
                            textAlign: 'right',
                            color: 'gray',
                            fontSize: '14px'
                          }}
                        >
                          {content}
                          {form ? (
                            <img src={form}></img>
                          ) : (
                            <div className="img-span">
                              {/* 取后面两位显示 */}
                              <span>
                                {formName
                                  ? formName.substring(
                                      formName.length - 2,
                                      formName.length
                                    )
                                  : ''}
                              </span>
                            </div>
                          )}
                        </div>
                      ) : (
                        <div
                          className="from"
                          style={{
                            textAlign: 'left',
                            color: 'gray',
                            fontSize: '14px'
                          }}
                        >
                          {form ? (
                            <img src={form}></img>
                          ) : (
                            <span className="img-span">
                              {formName
                                ? formName.substring(
                                    formName.length - 2,
                                    formName.length
                                  )
                                : ''}
                            </span>
                          )}
                          {content}
                        </div>
                      )}
                    </div>
                  );
                }
              })}
              <div
                style={{ float: 'left', clear: 'both' }}
                ref="messageList"
              ></div>
            </div>
          </div>
          <MessageSendBox
            startRecord={value => {
              this.setState({
                startRecord: value
              });
            }}
            messageSendSoundURL={this.state.sendSoundURL}
            messageSendSoundTime={this.state.sendSoundTime}
          />
        </div>
      </div>
    );
  }
}
