import React, {Component} from 'react'
import adCss from "./address.scss"
import AdItem from "./item/item";
import Panel from "../../common/panel/panel";
import SearchPanel from '../../common/searchPanel/searchPanel';
import _ from 'lodash'
import SearchDate from '../../common/searchDate/searchDate'
import getSearchTime from "../../../utils/getSearchTime";
import Nothing from "../nothing/nothing";
import {Modal, Load} from 'karaui'

export default class Address extends Component {
  constructor(props) {
    super(props);
    this.state = {
      pageInfo: {},
      result: [],
      pageCount: 1,
      showHeadIcon: false,
      headIcon: "",
      load: true,
      connecting: false, // 会话连接中
    }
  }

  componentDidMount() {
    const {kw, pageNum} = this.props;

    if (kw && kw !== "") {
      this.search(kw, pageNum);
    }

  }


  componentWillReceiveProps(next) {
    const {kw, clearSearchCount, pageNum, config} = this.props;
    const {pageCount} = this.state;
    //单纯的搜索
    if (kw && kw !== "" && kw !== next.kw && pageNum === next.pageNum) {
      clearSearchCount()
      this.setState({
        result: []
      }, () => {
        this.search(next.kw, next.pageNum)
      })

    } else if (kw && kw !== "" && pageNum !== next.pageNum && next.pageNum <= pageCount && next.pageNum <= 5) {
      //滚动加载,上限50条
      this.search(next.kw, next.pageNum)
    }
  }

  //根据时间查询
  searchByTime = (type, s, e) => {
    const {startTime, endTime} = getSearchTime(type, s, e)
    const {kw, pageNum} = this.props;
    if (kw !== "") {
      this.search(kw, pageNum, startTime, endTime);
    }
  }

  search = (kw, pageNum, from = '', to = '') => {
    const {httpAgent, language} = this.props
    this.lastKeyWord = kw
    const pageInfo = {
      pageNo: pageNum,
      pageSize: 10
    }
    const body = {
      keywords: kw,
      from,
      to,
      pageInfo,
      language: language === 'en' ? 'en' : 'cn',
      isHighlight: true,
      platform: 'web'
    }
    httpAgent.post('/search/mobileGlobal/user/list', body, kw).then(res => {
      if (res && res.pageInfo.result && res.resultCode === '000000' && this.lastKeyWord === res.backParams) {
        this.setState({
          result: pageNum === 1 ? res.pageInfo.result : _.concat(this.state.result, res.pageInfo.result),
          pageInfo: res.pageInfo,
          pageCount: res.pageInfo.pageCount,
          load: false
        }, () => {
          //渲染滚动条
          this.props.getScroll();
        });

      }
    })
  }


  getItem = (result) => {
    const {favourite, showHeadIcon, connectingStart, connectingEnd} = this;
    const {lang, history, httpAgent, karaui, user, hideContent,onClose} = this.props
    const li = result.map((v) => {
      return <AdItem karaui={karaui} favourite={favourite} key={v.accountId}  data={v} lang={lang}
                     history={history} showHeadIcon={showHeadIcon}
                     httpAgent={httpAgent} user={user} hideContent={hideContent}
                     connectingStart={connectingStart}
                     connectingEnd={connectingEnd} onClose={onClose}
      />
    });

    return <ul className={adCss["tel-content"]}>
      {li}
    </ul>
  }

  //添加关注

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

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

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

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

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


  render() {
    const {lang, karaui, user} = this.props;
    // const {Modal} = karaui;
    const {count, millis, pageCount, pageNo, pageSize, resultCode, resultMessage} = this.state.pageInfo;
    const {result, showHeadIcon, headIcon, load, connecting} = this.state;
    const parent = document.getElementById('app')
    // const selectDate = <SearchDate chooseTime={this.searchByTime} lang={lang}/>;
    return (
      !load ? count > 0 ?
        <SearchPanel num={count > 90 ? "99+" : count} time={millis} lang={lang} addTitle={lang.note}>
          {/*这里肯定不会超过50*/}
          <Panel title={`${lang.contact}（${ count > 50 ? "50" : count}${lang.item}）`} isLast
                 lang={lang}>
            {this.getItem(result)}

            <Modal show={showHeadIcon} parent={parent} onMask={this.hiddenModal}>
              <img className={adCss["head-icon"]} src={headIcon} alt=""/>
            </Modal>

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

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

}
