import React, {Component} from 'react'
import css from './post.scss'
import _ from 'lodash'
import {PlainMessage, Scroll} from 'karaui'
import base64 from '../../../../assets/images/base64'

class Group extends Component {
  constructor(props) {
    super(props);
    this.state = {
      spread: false,
      userInfo: {},
      pageNo: 1,
      openResult: []
    }
  }


  componentWillReceiveProps(next) {
    const {kw} = this.props
    if (kw && kw !== next.kw) {
      this.setState({
        spread: false,
        userInfo: {},
        pageNo: 1,
        openResult: []
      })
    }
  }

  //当前人的聊天记录
  getUserList = (userInfo) => {
    const {closeSearchModal} = this.props
    const {spread, openResult} = this.state;
    // const {result = []} = userInfo;
    const {getMoreData} = this;
    if (openResult.length === 0 || !spread) {
      return null
    }
    const li = openResult.map((v) => {
      return <li key={v.id} className="clearfix" onClick={() => {
        this.goToChannel(v.channelId,v.id);
        closeSearchModal();
      }}>
        <div className={`${css.userhead} s-bg-info`}>
          <img src={v.headIcon} onError={this.userHeadError} alt=""/>
        </div>
        <div className={css.userinfo}>
          <strong>{v.userName}</strong><span className={css.chatTime}>{this.transTime(v.ts)}</span>
          <span className={css.chatText}>
            <PlainMessage text={v.text ? v.text : v.richAttachments[0].text}/>
          </span>
        </div>
      </li>
    })
    //展开后的聊天记录列表
    return <ul className={`${css.user} clearfix`}>
      <Scroll onDragEndBottom={() => {
        getMoreData()
      }} onWheelBottom={() => {
        getMoreData()
      }} autoHeight={true}>
        {li}
      </Scroll>

    </ul>
  }

  getMoreData = () => {
    const {pageNo, userInfo} = this.state;
    if (this.state.pageNo < userInfo.pageCount) {
      this.setState({
        pageNo: pageNo + 1
      })
      this.getUserInfo(pageNo + 1);
    }

  }


  getUserInfo = (pageNo) => {
    const {httpAgent, channelId, kw} = this.props
    this.lastKeyWord = kw
    const body = {
      channelId,
      keywords: kw,
      pageInfo: {
        pageNo: pageNo,
        pageSize: 4,
      },
      isHighlight: true,
      isShowRich: true
    }
    const backParams = {kw}
    httpAgent.post('/search/global/channel/message/list', body, backParams).then(res => {
      if (res && res.pageInfo && res.pageInfo.result && res.resultCode === '000000' && this.lastKeyWord === res.backParams.kw) {
        this.setState({
          userInfo: res.pageInfo,
          openResult: pageNo === 1 ? res.pageInfo.result : _.concat(this.state.openResult, res.pageInfo.result)
        })
      }
    })
  }

  openUserInfo = () => {
    this.getUserInfo(1)
    this.setState({spread: true, pageNo: 1})
  }

  closeUserInfo = () => {
    this.setState({spread: false, pageNo: 1})
  }

  //展开与折叠
  getUserHandle = (recordCount, spread, lang) => {
    if (recordCount === 1) {
      return null
    }
    return spread ? <div className={`${css.more} s-primary`} onClick={this.closeUserInfo}>{lang.fold}<i/></div>
      : <div className={`${css.more} s-primary`} onClick={this.openUserInfo}>{lang.spread}<i/></div>
  }

  groupHeadError = (e) => {
    e.target.src = base64.groupHead
  }

  userHeadError = (e) => {
    e.target.src = base64.userHead
  }


  goToChannel = (id,messageId) => {
    const {history,onClose} = this.props
    onClose();
    history.push(`/chat/${id}?msgid=${messageId}`)
  }

  //转化毫秒为时间
  transTime = (time) => {
    let newTime = new Date(time).toLocaleDateString();
    return newTime.replace(/\//g, '-');
  }

  render() {
    const {channelIcon, channelName, channelId, messageId, onlyOneContent, recordCount, channelMembers, lang, channelType, closeSearchModal} = this.props;
    const {userInfo, spread} = this.state;
    return (<li className={`${css.item} clearfix`}>
      <div className={`${css.channel} clearfix`}>
        <div className={css.postWrap} onClick={() => {
          if (recordCount === 1) {
            this.goToChannel(channelId,messageId);
            closeSearchModal();
          } else {
            spread ? this.closeUserInfo() : this.openUserInfo();
          }

        }}>
          <div className={`${css.head} s-bg-info`}>
            <img src={channelIcon} onError={this.groupHeadError} alt=""/>
          </div>
          <div className={css.info}>
            <strong>{channelName}{channelType === "private" ? "" : `（${channelMembers}人）`}</strong>
            {recordCount === 1 ? <div className={`s-lesser ${css.text}`}> <PlainMessage text={onlyOneContent}/></div> :
              <span className="s-lesser">{recordCount}{lang.hasAboutCount}</span>}
          </div>
        </div>
        {this.getUserHandle(recordCount, spread, lang)}
      </div>
      {this.getUserList(userInfo)}
    </li>)
  }


}

export default Group;