import React, { Component } from 'react'
import tCss from './item.scss'
import { PlainMessage, Tooltip, Tost } from 'karaui'
import _ from 'lodash'
import LowerListModal from '../telModal/lowerListModal'
import UserInfoModal from '../telModal/userInfoModal'

export default class AdItem extends Component {

  //定义tab标签
  constructor (props) {
    super(props)
    this.state = {
      tabType: 'tel',
      accountId: '',//当前查看的用户的accountId
      lowerModal: false,//下属列表框是否显示
      pageNo: 1,//下属页码
      pageSize: 10,//每页数量
      lowerList: [],//下属列表
      infoModal: false,//名片信息弹出框是否显示
      accountIdArr: [],//都是查看了谁的名片，压栈方式存accountId，关闭弹框时，remove掉本地存储，并且将此数组赋空
      personData: {},//名片信息
    }

  }

  //展示下属列表的盒子
  showLowerModal = (accountId) => {
    this.setState({
      lowerModal: true,
      accountId
    })
    this.getLowerPerson(accountId, 10)
  }

  //隐藏下属列表盒子
  hideLowerModal = () => {
    this.setState({
      lowerModal: false,
      lowerList: [],
      pageNo: 1
    })
  }

  //滚动加载，更改页码
  getMoreLower = (accountId = this.state.accountId, pageSize = this.state.pageSize) => {
    const {pageNo, pageCount} = this.state
    //当前请求页小于总页数发出请求
    if (pageNo < pageCount) {
      let newPageNo = pageNo + 1

      this.setState({
        pageNo: newPageNo
      }, () => {
        this.getLowerPerson(accountId, pageSize, this.state.pageNo)
      })
    }
  }

  //获取下属列表
  getLowerPerson = (accountId, pageSize = this.state.pageSize, pageNo = 1) => {
    if (pageNo === 1) {
      this.setState({
        pageNo: 1
      })
    }
    const {httpAgent} = this.props
    // const {pageNo} = this.state
    const body = {
      accountId,
      pageInfo: {
        pageNo: pageNo,
        pageSize: pageSize,
      },
    }
    httpAgent.post(`/search/addressbook/subordinateStaff`, body).then(res => {
      if (res && res.resultCode === '000000') {
        this.setState({
          lowerList: pageNo === 1 ? res.pageInfo.result : _.concat(this.state.lowerList, res.pageInfo.result),
          pageCount: res.pageInfo.pageCount
        })
      }
    })
  }
  //展示详细名片
  showDetailInfoModal = (accountId) => {
    this.hideLowerModal()
    this.setState({
      infoModal: true,
      lowerList: [],
      pageNo: 1
    })
    this.getDetailInfo(accountId)
  }

  //隐藏详细名片弹窗
  hideDetailInfoModal = () => {
    this.setState({
      infoModal: false,
      accountIdArr: [],
      lowerList: [],
    })
  }

  //获取详细名片的信息
  getDetailInfo = (accountId) => {
    const {httpAgent} = this.props
    httpAgent.get(`/sdm/addressbook/member/${accountId}`).then(res => {
      // console.log('名片信息', res)
      if (res && res.resultCode === '000000') {
        this.setState({
          personData: res.addressBookStaff
        })
      }
    })

    //  向数组中存入accountID，用来返回上一个，存在本地存储中
    let accArr = _.clone(this.state.accountIdArr)
    accArr.push(accountId)

    // console.log('已经打开的人', accArr)
    this.setState({
      accountIdArr: accArr
    })
  }

  //点击返回按钮，删除accountIdArr的最后一个
  delPopPerson = () => {
    let accArr = _.clone(this.state.accountIdArr)
    //删除数组中的最后一个，
    accArr.pop()
    //  并且显示删除后，数组中最后一个人的详情
    this.getDetailInfo(accArr[accArr.length - 1])
    this.setState({
      accountIdArr: accArr,
    })
  }

  //关注联系人，更改对应状态
  changeStatus = (status) => {
    let newData = _.clone(this.state.personData)
    newData.contactStatus = status
    this.setState({
      personData: newData
    })

  }

  onChat = (accountId) => {
    const {httpAgent, history, user, hideContent, connectingStart, connectingEnd, onClose} = this.props
    this.showConnecting = true
    setTimeout(() => {
      // 如果一秒内接口没有返回数据 那么显示加载中提示
      if (this.showConnecting) {
        connectingStart()
      }
    }, 1000)
    setTimeout(() => {
      // 如果5秒还在加载提示 那么关闭提示 显示失败tost
      if (this.showConnecting) {
        connectingEnd()
        Tost({type: 'error', msg: '发起会话失败'})
      }
    }, 6000)
    if (user.accountId === accountId) {
      httpAgent.post(`/webapi/channel/selfChannel`).then(res => {
        if (res && res.resultCode === '000000') {
          const {id} = res.channelInfo
          this.showConnecting = false
          connectingEnd() // 发起成功 关闭 提示信息
          hideContent() // 关闭 搜索 内容
          history.push(`/chat/${id}`) // 跳转到 im
          onClose()
        }
      })
    } else {
      httpAgent.post(`/webapi/channel/createprivate/${accountId}`).then(res => {
        if (res && res.resultCode === '000000') {
          const {id} = res.channelInfo
          this.showConnecting = false
          hideContent()
          connectingEnd()
          history.push(`/chat/${id}`)
          onClose()
        }
      })
    }

  }

  //过滤span
  filterSpan = (text) => {
    return text.replace(/\<span.*?\>(.+?)\<\/span\>/g, '$1')
  }

  render () {
    const {lowerList, lowerModal, infoModal, personData, accountIdArr} = this.state
    const {
      showDetailInfoModal, getMoreLower, hideDetailInfoModal, getLowerPerson,
      showLowerModal, hideLowerModal, getDetailInfo, delPopPerson, onChat, changeStatus
    } = this

    const {isLast, lang, list, favourite, showHeadIcon, httpAgent} = this.props
    const {
      accountId = '无', accountName = '无', accountType = '无', companyName = '无', email = '无', gender = '无',
      headIcon = '无', mobile = '无', officeAddr = '无', orgName = '无', orgNameEn = '无', contactStatus = '无',
      parentStaffName = '无', phone = '无', staffAccount = '无', staffCode = '无', staffName = '无',
      tags = '无', parentStaffCode = '无', sbuId = '无', sbuName = '无', costCenter = '无', costCenterName = '无',
      parentAccountId = '无', childAccountCount = 0
    } = this.props.data

    return (
      <li className={`${tCss['tel-item']} clearfix`}>
        {/*头像*/}
        <div className={tCss['t-left']}>
          <div className={`${tCss['t-h-img']} s-bg-info`} onClick={() => {
            showHeadIcon(headIcon)
          }}>
            <img src={headIcon} alt=""/>
          </div>
          <div className={tCss['t-name']}>
            <div
              className={tCss['wrap-name']}
              onMouseEnter={(e) => {
                Tooltip({e, msg: this.filterSpan(accountName), position: 'right'})
              }}
              onMouseLeave={() => {
                Tooltip({leave: true})
              }}
            >
              <PlainMessage text={accountName}/>
              <PlainMessage text={staffCode}/>
            </div>
          </div>
          <p className={tCss['t-icon']}>
            <i className={`${tCss['msg-icon']} ks-iconfont ks-icon-xiaoxi s-primary`} title={lang.chatting}
               onClick={() => {
                 this.onChat(accountId)
               }}/>

            <i
              className={`${contactStatus || list === '1' ? 's-primary' : 's-tips'} ${tCss['star-icon']} ks-iconfont ks-icon-collection-b`}
              title={contactStatus || list === '1' ? lang.no : lang.yes}
              onClick={(e) => {
                favourite(accountId, contactStatus, e)
              }}> </i>
          </p>

        </div>

        {/*信息*/}

        <div className={tCss['t-right']}>
          <table>
            <tbody>
            <tr>
              {/*<td>{lang.emId}：</td>*/}
              {/*<td><PlainMessage text={staffCode}/></td>*/}
              <td>NT：</td>
              <td><PlainMessage text={staffAccount}/></td>
              <td>{lang.workStation}：</td>
              <td><PlainMessage text={officeAddr === '无' ? lang.doNotAbout : officeAddr}/></td>

              <td>{lang.phone}/{lang.tel}：</td>
              {
                mobile === '无' && phone === '无' ?
                  <td>{lang.doNotAbout}</td> :
                  <td><PlainMessage
                    text={`${mobile === '无' ? lang.doNotAbout : mobile}/${phone === '无' ? lang.doNotAbout : phone}`}/>
                  </td>
              }
            </tr>
            <tr>
              <td>{lang.departmentzh}：</td>
              <td><PlainMessage text={orgName === '无' ? lang.doNotAbout : orgName}/></td>
              <td>{lang.departmenten}：</td>
              <td><PlainMessage text={orgNameEn === '无' ? lang.doNotAbout : orgNameEn}/></td>
              <td>SBU：</td>
              {
                sbuId === '无' && sbuName === '无' ?
                  <td>{lang.doNotAbout}</td> :
                  <td><PlainMessage
                    text={`${ sbuId === '无' ? lang.doNotAbout : sbuId}（${ sbuName === '无' ? lang.doNotAbout : sbuName}）`}/>
                  </td>
              }
            </tr>
            <tr>
              <td>CC：</td>
              {
                costCenter === '无' && costCenterName === '无' ?
                  <td>{lang.doNotAbout}</td> :
                  <td>{`${ costCenter === '无' ? lang.doNotAbout : costCenter}(${ costCenterName === '无' ? lang.doNotAbout : costCenterName})`}</td>
              }

              <td>{lang.company}：</td>
              <td><PlainMessage text={companyName === '无' ? lang.doNotAbout : companyName}/></td>
              <td>{lang.email}：</td>
              <td className={tCss.email}><a href={`mailto:${email}`}>{email === '无' ? lang.doNotAbout : email}</a></td>
            </tr>
            <tr>
              <td>{lang.superior}：</td>
              {
                parentStaffName === '无' && parentStaffCode === '无' ?
                  <td>{lang.doNotAbout}</td> :
                  <td className={tCss.blueText}
                      onClick={() => {this.showDetailInfoModal(parentAccountId)}}>{`${ parentStaffName === '无' ? lang.doNotAbout : parentStaffName}（${ parentStaffCode === '无' ? lang.doNotAbout : parentStaffCode}）`}</td>
              }
              <td>{lang.lower}：</td>
              <td
                className={childAccountCount && childAccountCount > 0 ? `${tCss.lowerTd} ${tCss.blueText}` : tCss.lowerTd}
                onMouseEnter={() => {
                  (childAccountCount > 0 ?
                    this.showLowerModal(accountId) : null)

                }} onMouseLeave={() => {this.hideLowerModal()}}>
                {childAccountCount > 0 ? `${childAccountCount}人` : '暂无'}
                {/*查看详情*/}
                {/*下属列表框*/}
                {lowerModal ? <LowerListModal data={lowerList} showDetailInfoModal={showDetailInfoModal}
                                              getMoreLower={getMoreLower}/> : null}
              </td>

              <td>{lang.label}：</td>
              <td className={tCss.tagsTd}
              >
                <div onMouseEnter={(e) => {
                  tags !== '无' && Tooltip({e, msg: this.filterSpan(tags), position: 'bottom'})
                }} onMouseLeave={() => {
                  tags !== '无' && Tooltip({leave: true})
                }}>{tags === '无' ? lang.doNotAbout : tags}</div>
              </td>
            </tr>
            </tbody>
          </table>
          <UserInfoModal show={infoModal} data={personData} close={hideDetailInfoModal} getDetailInfo={getDetailInfo}
                         showDetailInfoModal={showDetailInfoModal} accountIdArr={accountIdArr}
                         delPopPerson={delPopPerson} onChat={onChat} httpAgent={httpAgent} changeStatus={changeStatus}
                         getLowerPerson={getLowerPerson} lowerData={lowerList} getMore={getMoreLower}
          />
        </div>

        {isLast ? null : <i className={`${tCss.bottom} s-b-default clearfix`}/>}

      </li>
    )
  }

}
