import Taro, { Component, requirePlugin } from '@tarojs/taro';
import './index.scss'

import ListView from '@components/ListView'
import getUserPhone from '@utils/getUserPhone'
import { getCardList } from '@services/card'
import { connect } from '@tarojs/redux'
import { savePoint, updatePoint } from '@services/common'
let pageIndex = 1
@connect(({ user }) => ({ ...user }))
export default class Index extends Component {
  config = {
    navigationBarTitleText: '置业顾问列表'
  }

  state = {
    list: [],
    hasMore: true,
    isEmpty: false,
    recordId: null,
    pageIndex:1
  }
  componentWillMount() {
    savePoint({
      event: 'consultants',
      eventType: 'card',
      propertyName: '置业顾问列表',
      data: '{}'
    }).then(res => {
      this.setState({
        recordId: res.recordId
      })
      console.log('置业顾问列表')
    })
  }
  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

  getPhoneNumber(e, item) {
    getUserPhone(e, (phoneNumber) => {
      this.handleChatClick(item)
    })
  }

  handleTelClick(item, e) {
    e.stopPropagation()
    Taro.makePhoneCall({
      phoneNumber: item.phone
    })
    savePoint({
      event: 'phone',
      eventType: 'card',
      propertyName: '拨打置业顾问电话',
      data: '{}'
    }).then(res => {
      console.log('拨打置业顾问电话')
    })
  }

  handleChatClick(item, e) {
    e && e.stopPropagation()
    const { userInfo: { person: { personId, nickname, name } } } = this.props
    
    Taro.navigateTo({
      url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(name || nickname)}&receiverId=${item.id}&receiverName=${encodeURIComponent(item.name)}`
    })
  }

  handleConsuItemClick(item) {
    Taro.navigateTo({
      url: `/pages/card/index?id=${item.id}`
    })
  }

  handleMoreClick() {
    Taro.navigateTo({
      url: `/pages/card/list/index`
    })
  }

  handleStopPropagation(e) {
    e.stopPropagation()
  }

  loadList(pageNumber) {
 
    const { buildingId } = this.$router.params
    const payload = { pageSize: 10, pageNumber, buildingId: '' }
    if (buildingId) {
      payload.buildingId = buildingId
    }
    return getCardList(payload)
  }

  onPullDownRefresh = async (rest) => {
    const { records: list, total } = await this.loadList(1);
    this.setState({
      list,
      isEmpty: total == 0,
      hasMore: list.length >= total ? false : true,
      pageIndex:1
    })
    rest && rest()
  }

  onScrollToLower = async (fn) => {
    const { list } = this.state;
    pageIndex++
    const { records, total } = await this.loadList(this.state.pageIndex+1);
    const newList = list.concat(records)
    this.setState({
      list: newList,
      hasMore: newList.length >= total ? false : true,
      pageIndex:this.state.pageIndex+1
    });
    fn && fn();
  }

  render() {
    const { hasMore, isEmpty, list } = this.state
    const { person: { phone, tel } } = this.props.userInfo
    const hadPhone = (phone || tel) ? true : false

    return (
      <ListView
        needInit
        isEmpty={isEmpty}
        emptyText="暂无置业顾问哦~"
        hasMore={hasMore}
        style={{ height: '100vh' }}
        onPullDownRefresh={fn => this.onPullDownRefresh(fn)}
        onScrollToLower={fn => this.onScrollToLower(fn)}
      >
        <View className='top-tip'>有任何买卖房屋的问题，欢迎随时咨询</View>
        <View className="list">
          {
            list.map(item => (
              <View className='item-main' key={item.id} onClick={this.handleConsuItemClick.bind(this, item)}>
                <View className="item">
                  <View className="flex">
                  <Image className="avatar" mode="aspectFill" src={item.photo || item.avatar}></Image>

                    <View className='info'>
                      <View className='name-info'>
                        <Text className="name">{item.name}</Text>
                        <Image src={require('@assets/person/card.png')} className='card' ></Image>
                      </View>
                      <View className="phone">{item.phone}</View>
                    </View>

                  </View>
                  <View className="flex item-btn__box">

                    {
                      hadPhone ? (
                        <Button className="item-btn chat" onClick={this.handleChatClick.bind(this, item)}>
                          <Image src={require('@assets/person/zixun.png')} className='chat-img'></Image>
                        </Button>
                      ) : (
                          <Button className="item-btn chat" onClick={this.handleStopPropagation} open-type="getPhoneNumber" onGetphonenumber={e => { this.getPhoneNumber(e, item) }}>
                          </Button>
                        )
                    }
                    <Button className="item-btn tel" onClick={this.handleTelClick.bind(this, item)}>
                      <Image src={require('@assets/person/dianhua.png')} className='tel-img'></Image>
                    </Button>
                  </View>

                </View>
                <View className='item-txt'>{item.description || ''}</View>
              </View>

            ))
          }
        </View>
      </ListView>
    );
  }
}