import React, { Component } from 'react'
import css from './all.scss'
import SearchPanel from '../../common/searchPanel/searchPanel'
import SearchDate from '../../common/searchDate/searchDate'
import SysItem from '../sys/item/item'
import Panel from '../../common/panel/panel'
import TodoItem from '../todo/item/item'
import AdItem from '../address/item/item'
import FriendItem from '../friendCircle/item/item'
import KnowledgeItem from '../knowledge/item/item'
import NewsItem from '../news/item/item'
import _ from 'lodash'
import MsgGroup from '../message/group/group'
import MsgPost from '../message/post/post'
import MsgFile from '../message/file/file'
import getSearchTime from '../../../utils/getSearchTime'
import Nothing from '../nothing/nothing'
import { Modal, Load } from 'karaui'
import MessageModal from '../msgModal'

class All extends Component {
  constructor (props) {
    super(props)
    this.state = {
      searchResult: {},
      showHeadIcon: false,//头像的弹框是否显示
      headIcon: '',
      addressList: [],//通讯录的列表
      msgModelShow: false,//消息弹窗是否显示
      modalType: '',//消息弹窗的类型：file,msg,group,video.bot
      load: true, //加载中，默认显示
      connecting: false, // 会话连接中
    }
  }

  componentDidMount () {
    const {kw, searchTime} = this.props
    if (kw) {
      this.searchAll(kw, searchTime.start, searchTime.end)
    }
  }

  componentWillReceiveProps (next) {
    const {kw} = this.props
    const {searchTime} = next
    if (kw && kw !== next.kw) {
      this.searchAll(next.kw, searchTime.start, searchTime.end)
    }
  }

  setSearchCount = (searchResult) => {
    const {appCount = 0, accountCount = 0, channelCount = 0, chatRecordCount = 0, faqItemCount = 0, fileCount = 0, cmsCount = 0, momentCount = 0, todoTaskCount = 0} = searchResult
    const count = {
      all: appCount + accountCount + channelCount + chatRecordCount + faqItemCount + fileCount + cmsCount + momentCount + todoTaskCount,
      sys: appCount,
      todo: todoTaskCount,
      msg: channelCount + chatRecordCount + fileCount,
      tel: accountCount,
      friend: momentCount,
      news: cmsCount,
      knowledge: faqItemCount,
    }
    this.props.setSearchCount(count)
  }

  //根据时间查询
  searchByTime = (type, s, e, label) => {
    const {startTime, endTime} = getSearchTime(type, s, e)
    const {kw, changeSearchTime} = this.props
    this.searchAll(kw, startTime, endTime)
    // console.log('set time', type, s, e, startTime, endTime)
    changeSearchTime({type, label, start: startTime, end: endTime})
  }

  searchAll = (kw, from = '', to = '') => {
    const {httpAgent, language} = this.props
    const body = {
      keywords: kw,
      from,
      to,
      language: language === 'en' ? 'en' : 'cn',
      isHighlight: true,
      platform: 'web',
      isShowRich: true
    }
    this.lastKeyWord = kw
    httpAgent.post('/search/global/all', body, kw).then(res => {
      // console.log('res', res)
      if (res && res.result && res.resultCode === '000000' && this.lastKeyWord === res.backParams) {
        this.setState({
          searchResult: res.result,
          addressList: res.result.accountInfos,
        }, () => {
          this.setSearchCount(res.result)
          this.setState({
            load: false
          })
        })

      }
    })
  }

  connectingStart = () => {
    this.setState({connecting: true})
  }

  connectingEnd = () => {
    this.setState({connecting: false})
  }

  //获取系统
  getSysItem = (appInfos) => {
    const {lang, history, httpAgent} = this.props
    const li = appInfos.map((v) => {
      return <SysItem key={v.id} data={v} lang={lang} all/>
    })
    //重新添加类名写样式
    return <ul className={`${css['li-float']} clearfix`}>
      {li}
    </ul>
  }

  //待办
  getTodoItem = (todoTaskInfos) => {
    const {lang, history, httpAgent} = this.props
    const li = todoTaskInfos.map((v) => {
      return <TodoItem key={v.id} data={v} noLine lang={lang} history={history} httpAgent={httpAgent} all/>
    })
    return <ul className={`${css['li-float']} clearfix`}>
      {li}
    </ul>
  }

  //通讯录
  getAddressItem = (accountInfos) => {
    const {lang, history, httpAgent, user, karaui, hideContent, onClose} = this.props
    const {showHeadIcon, favourite, connectingStart, connectingEnd} = this
    const li = accountInfos.map((v) => {
      return <AdItem showHeadIcon={showHeadIcon} key={v.accountId} data={v} lang={lang} history={history}
                     httpAgent={httpAgent} user={user} karaui={karaui} favourite={favourite} hideContent={hideContent}
                     connectingStart={connectingStart} onClose={onClose}
                     connectingEnd={connectingEnd}
      />
    })
    return <ul className={css['ad-pad']}>
      {li}
    </ul>
  }

  //同事圈
  getCircleItem = (momentInfos) => {
    const {httpAgent, history, closeSearchModal} = this.props
    const li = momentInfos.map((v) => {
      return <FriendItem key={v.id} data={v} httpAgent={httpAgent} history={history}
                         closeSearchModal={closeSearchModal}/>
    })
    return <ul className={css['ul-padding']}>
      {li}
    </ul>
  }

  //资讯
  getNewsItem = (informationInfos) => {
    const li = informationInfos.map((v) => {
      return <NewsItem key={v.id} data={v}/>
    })
    return <ul className={css['ul-padding']}>
      {li}
    </ul>
  }

  //知识库
  getKnowledgeItem = (faqItemInfos) => {
    const li = faqItemInfos.map((v) => {
      return <KnowledgeItem key={v.number} data={v}/>
    })
    return <ul className={css['ul-padding']}>
      {li}
    </ul>
  }

  //点击头像，显示用户的头像
  showHeadIcon = (headIcon) => {
    this.setState({
      showHeadIcon: true,
      headIcon: headIcon
    })
  }

  hiddenModal = () => {
    this.setState({
      showHeadIcon: false
    })
  }

  //关注/取消联系人
  favourite = (id, or, e) => {
    const {httpAgent} = this.props

    let yesOrNo
    if (!or) {
      //添加关注
      yesOrNo = 'yes'
      let newResult = _.cloneDeep(this.state.addressList)
      _.find(newResult, ['accountId', id]).contactStatus = true
      this.setState({
        addressList: newResult
      })
    } else {
      yesOrNo = 'no'
      let newResult = _.cloneDeep(this.state.addressList)
      _.find(newResult, ['accountId', id]).contactStatus = false
      this.setState({
        addressList: newResult
      })
    }
    httpAgent.post(`/sdm/contact/${id}/${yesOrNo}`, {}).then(res => {
      // console.log('关注结果', res)
      if (res && res.resultCode === '000000') {
        this.setState({
          favId: id
        })
      }
    })
  }

  //消息中的类别的查看更多
  msgGetMore = (type) => {

    this.setState({
      msgModelShow: true,
      modalType: type
    })

  }

  msgModelHide = () => {
    this.setState({
      msgModelShow: false
    })
  }

  render () {
    const {changeActiveTab, contentRef, httpAgent, lang, history, kw, closeSearchModal, karaui, searchTime, onClose} = this.props
    const parent = document.getElementById('app')
    const selectDate = <SearchDate chooseTime={this.searchByTime} searchTime={searchTime} lang={lang}/>
    //数据:系统条数--内容，通讯录--内容,知识库，资讯，同事圈，待办
    //消息：accountCount+chatRecordCount+fileCount,--对应内容
    const {
      appCount = 0, appInfos = [],
      accountCount = 0, accountInfos = [],
      faqItemCount = 0, faqItemInfos = [],
      cmsCount = 0, informationInfos = [],
      momentCount = 0, momentInfos = [],
      todoTaskCount = 0, todoTaskInfos = [],
      chatRecordCount = 0, chatRecords = [],
      channelCount = 0, channelInfos = [],//群组
      fileCount = 0, fileInfos = [],
      millis,
    } = this.state.searchResult
    const allDataNum = appCount + accountCount + channelCount + chatRecordCount + faqItemCount + fileCount + cmsCount + momentCount + todoTaskCount

    const {showHeadIcon, headIcon, addressList, msgModelShow, modalType, load, connecting} = this.state

    return (
      !load ? !load && allDataNum > 0 ?
        <SearchPanel num={allDataNum} selectDate={selectDate} time={millis} lang={lang}>

          {/*通讯录,显示3条*/}
          {accountCount > 0 ? accountCount > 3 ?
            <Panel title={`${lang.contact}（${accountCount > 50 ? '50' : accountCount}${lang.item}）`}
                   onMore={() => {
                     changeActiveTab('tel')
                   }} lang={lang} addTitle={lang.note}>
              {this.getAddressItem(_.slice(addressList, 0, 3))}
              <Modal show={showHeadIcon} parent={parent} onMask={this.hiddenModal}>
                <img className={css['head-icon']} src={headIcon} alt=""/>
              </Modal>
            </Panel> : <Panel title={`${lang.contact}（${accountCount}${lang.item}）`} lang={lang}>
              {this.getAddressItem(addressList)}
              <Modal show={showHeadIcon} parent={parent} onMask={this.hiddenModal}>
                <img className={css['head-icon']} src={headIcon} alt=""/>
              </Modal>
            </Panel> : null}

          {/*/!*系统显示两条*!/*/}
          {appCount > 0 ? appCount > 2 ?
            <Panel title={`${lang.sys}（${appCount > 99 ? '99+' : appCount}${lang.item}）`} onMore={() => {
              changeActiveTab('sys')
            }} lang={lang}>
              {this.getSysItem(_.slice(appInfos, 0, 2))}
            </Panel> : <Panel title={`${lang.sys}（${appCount}${lang.item}）`} lang={lang}>
              {this.getSysItem(appInfos)}
            </Panel> : null}

          {/*待办显示两条*/}
          {todoTaskCount > 0 ? todoTaskCount > 2 ?
            <Panel title={`${lang.todo}（${todoTaskCount > 99 ? '99+' : todoTaskCount}${lang.item}）`}
                   onMore={() => {
                     changeActiveTab('todo')
                   }} lang={lang}>
              {this.getTodoItem(_.slice(todoTaskInfos, 0, 2))}
            </Panel> : <Panel title={`${lang.todo}（${todoTaskCount}${lang.item}）`} lang={lang}>
              {this.getTodoItem(todoTaskInfos)}
            </Panel> : null}

          {/*消息--群组，显示5条*/}
          <MsgGroup
            data={{result: channelInfos.slice(0, 5), count: channelCount}}
            listArr={channelInfos.slice(0, 5)}
            lang={lang}
            httpAgent={httpAgent}
            history={history}
            onMore={channelCount > 5 ? () => {
              this.msgGetMore('group')
            } : null}
            kw={kw}
            closeSearchModal={closeSearchModal}
          />
          {/*消息--聊天记录，显示3条*/}
          <MsgPost
            data={{result: chatRecords.slice(0, 3), count: chatRecordCount}}
            listArr={chatRecords.slice(0, 3)}
            lang={lang} onClose={onClose}
            httpAgent={httpAgent}
            history={history}
            onMore={chatRecordCount > 3 ? () => {
              this.msgGetMore('msg')
            } : null}
            kw={kw}
            closeSearchModal={closeSearchModal}
          />
          {/*消息--文件，显示4条*/}
          <MsgFile
            data={{result: fileInfos.slice(0, 4), count: fileCount}}
            contentRef={contentRef}
            httpAgent={httpAgent}
            lang={lang}
            onMore={fileCount > 4 ? () => {
              this.msgGetMore('file')
            } : null}
            kw={kw}
          />

          {/*同事圈，显示3条*/}
          {momentCount > 0 ? momentCount > 3 ?
            <Panel title={`${lang.group}（${momentCount > 99 ? '99+' : momentCount}${lang.item}）`} onMore={() => {
              changeActiveTab('friend')
            }} lang={lang}>
              {this.getCircleItem(_.slice(momentInfos, 0, 3))}
            </Panel> : <Panel title={`${lang.group}（${momentCount}${lang.item}）`} lang={lang}>
              {this.getCircleItem(momentInfos)}
            </Panel> : null}


          {/*资讯,显示3条*/}
          {cmsCount > 0 ? cmsCount > 3 ?
            <Panel title={`${lang.news}（${cmsCount > 99 ? '99+' : cmsCount}${lang.item}）`} onMore={() => {
              changeActiveTab('news')
            }} lang={lang}>
              {this.getNewsItem(_.slice(informationInfos, 0, 3))}
            </Panel> : <Panel title={`${lang.news}（${cmsCount}${lang.item}）`} lang={lang}>
              {this.getNewsItem(informationInfos)}
            </Panel> : null}


          {/*知识库，显示3条*/}
          {faqItemCount > 0 ? faqItemCount > 3 ?
            <Panel title={`${lang.knowledge}（${faqItemCount > 99 ? '99+' : faqItemCount}${lang.item}）`}
                   onMore={() => {
                     changeActiveTab('knowledge')
                   }} isLast lang={lang}>
              {this.getKnowledgeItem(_.slice(faqItemInfos, 0, 3))}
            </Panel> : <Panel title={`${lang.knowledge}（${faqItemCount}${lang.item}）`} isLast lang={lang}>
              {this.getKnowledgeItem(faqItemInfos)}
            </Panel> : null}

          {msgModelShow ?
            <MessageModal modalType={modalType} parent={parent} msgModelHide={this.msgModelHide} contentRef={contentRef}
                          lang={lang} httpAgent={httpAgent} kw={kw}
                          history={history} searchTime={searchTime}
                          karaui={karaui} msgModelShow={msgModelShow} onClose={onClose} closeSearchModal={closeSearchModal}/> : null}

          {connecting ? <Modal show parent={document.getElementById('app') || document.body}
                               replaceStyle={{backgroundColor: 'rgba(0,0,0,0.3)'}}>
            <Load className={css.connecting} text="发起会话中..."/>
          </Modal> : null}

        </SearchPanel> : <Nothing lang={lang}/> : <Load/>
    )
  }

}

export default All