/**
 * 会话列表
 */
import React, { Component } from 'react';
import { connect } from 'dva';
import { Pagination, Drawer, Badge, message, Row, Popover, Avatar,Col } from 'antd';
import { getDate, getTime, isToday } from '../../../utils/utils';
import './im.less';
import tim from '../../../utils/im/imInitialize';
import TIM from 'tim-js-sdk';
import CurrentConversation from './CurrentConversation';
import eventCenter from "@common/events"; // 引入 EventEmitter'
@connect(state => ({
  conversationList: state.im.conversationList,
  currentConversation: state.im.currentConversation,
  nextReqMessageID: state.im.nextReqMessageID,
  isCompleted: state.im.isCompleted,
  currentMessageList: state.im.currentMessageList
}))
export default class ConversationList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: props.visible,
      clicked: false,
      hovered: false,
      conversationID: props.currentConversation.conversationID
    };
  }

  componentDidMount() {
    // this.selectConversation(this.props.conversationID)
  }
  componentWillReceiveProps(nextProps) {
    if (this.state.conversationID!==nextProps.currentConversation.conversationID) {
      this.setState({
        conversationID: nextProps.currentConversation.conversationID
      })
    }
    // this.setState({
    // visible: nextPsrops.visible,
    // conversationID: nextProps.conversationID
    // });
  }
  getDate(data) {
    const date = new Date(data * 1000);
    if (isToday(date)) {
      return getTime(date);
    }
    return getDate(date);
  }
  //切换会话
  selectConversation(conversationID) {
    // 1.切换会话前，将切换前的会话进行已读上报
    if (this.props.conversationID) {
      tim.setMessageRead({
        conversationID:
          this.props.conversation && this.props.conversation.conversationID
        // conversationID: this.props.conversationID
      });
    }
    // 2.待切换的会话也进行已读上报
    tim.setMessageRead({ conversationID });
    this.props.dispatch({
      type: 'im/totalUnreadCount',
      payload: ''
    });
    // 3. 获取会话信息
    return tim.getConversationProfile(conversationID).then(({ data }) => {
      // // 3.1 更新当前会话
      this.props.dispatch({
        type: `im/updateCurrentConversation`,
        payload: data.conversation
      });
      eventCenter.emit('changeImStatus', true);
      // 3.2 获取消息列表
      this.getMessageList(conversationID);
      return Promise.resolve();
    },err=>{
      message.error(err.toString())
    });
  }
  getMessageList(conversationID) {
    if (this.props.isCompleted) {
      message.info('没有更多的历史消息了');
      return;
    }
    const { nextReqMessageID, currentMessageList } = this.props;
    tim
      .getMessageList({ conversationID, nextReqMessageID, count: 15 })
      .then(imReponse => {
        // 更新messageID，续拉时要用到
        this.props.dispatch({
          type: 'im/updateCurrentConversationCont',
          payload: {
            nextReqMessageID: imReponse.data.nextReqMessageID,
            isCompleted: imReponse.data.isCompleted,
            currentMessageList: [
              ...imReponse.data.messageList,
              ...currentMessageList
            ] // 更新当前消息列表，从头部插入
          }
        });
      });
  }
  // setConversationId(index) {
  //   this.setState({
  //     ['popClickeState' + index]: true
  //   });
  // }
  render() {
    return (
      <Row
        className="list-container"
        style={{ display: this.state.visible ? 'block' : 'none' }}
      >
        {this.props.conversationList.map((item, index) => {
          let showPopClickeState = false;
          if (this.state.conversationID === item.conversationID) {
            // this.setState({
            //   ['popClickeState' + index]: true
            // });
            showPopClickeState = true;
          }
          if (item.type === '@TIM#SYSTEM') {
            return '';
          }
          // const date = this.getDate(item.lastMessage.lastTime);
          let avatar = '';
          let name = '';
          // let letShowCovId = false;
          if (item.type === 'C2C') {
            avatar = item.userProfile.avatar;
            name = item.userProfile.nick;
          } else if (item.type === 'GROUP') {
            name = item.groupProfile.name;
            avatar = require('../../../assets/images/avatar.png');
          }
          //单人
          // if (this.state.conversationID === item.conversationID) {
          // letShowCovId = true;
          // this.setConversationId(index);
          // }
          return (
            // <Popover
            //   key={item.conversationID+index}
            //   placement="left"
            //   content={
            //     <div className="hover-pop">
            //       <div className="name">{name}</div>
            //       {/* <div className="text">s</div>*/}
            //     </div>
            //   }
            //   trigger="hover"
            //   visible={this.state['hovered' + index]}
            //   onVisibleChange={visible => {
            //     this.setState({
            //       ['hovered' + index]: visible
            //       // clicked: false
            //     });
            //   }}
            // >
              <Popover
                key={index}
                placement="left"
                visible={
                  // this.state.conversationID === item.conversationID
                  //   ? true
                  //   :
                  // showPopClickeState?showPopClickeState:this.state['popClickeState' + index]
                  showPopClickeState
                }
                onVisibleChange={visible => {
                  // this.setState({
                  //   conversationID: item.conversationID
                  // });
                  // this.setState({
                  //   ['popClickeState' + index]: visible
                  //   // hovered: false
                  // });
                }}
                content={
                  <CurrentConversation
                    key={index}
                    visible={this.state.visible}
                    closeClick={() => {
                      // this.props.closeClick();
                      // this.setState({
                      //   conversationID: null,
                      //   ['popClickeState' + index]: false
                      // });
                      // this.setState({ conversationID: null }, () => {
                      // });
                    }}
                  />
                }
                trigger="click"
              >
                <Col
                  span={6}
                  key={item.conversationID}
                  onClick={() => {
                    this.selectConversation(item.conversationID);
                    // this.setState({
                    //   conversationID: item.conversationID
                    // });
                  }}
                  className="avatar"
                >
                  <div style={{display:'flex',flexDirection:'column', alignItems: 'center'}}>
                    {item.type === 'C2C' ? (
                      avatar ? (
                        <img className="avatar-header" src={avatar} />
                      ) : (
                        <span className="avatar-header span-header">
                          {name.substring(name.length - 2, name.length)}
                        </span>
                      )
                    ) : (
                      <img
                        className="avatar-header"
                        src={require('../../../assets/images/prevention/group.png')}
                      />
                    )}
                    <span className='name'>{name}</span>
                  </div>
                  <Badge count={item.unreadCount} showZero={false}></Badge>
                </Col>
              </Popover>
            // </Popover>
          );
        })}
      </Row>
    );
  }
}
