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

import getDateFormat from '@utils/chatDate'
import { connect } from '@tarojs/redux'

@connect(state => ({ ...state.user, ...state.card }))
export default class MsgItem extends Component {
  static defaultProps = {
    item: {
      time: 'test',
      list: []
    }
  }
  onPreviewImg(row) {
    const { messageType, message } = row
    if (messageType !== 'image') return

    Taro.previewImage({
      urls: [message],
      current: message
    })
  }

  makePhoneCall = () => {
    const { cardInfo: { phone, tel } } = this.props
    Taro.makePhoneCall({
      phoneNumber: phone || tel
    })
  }

  getPhoneNumber(e) {
    // this.$scope.triggerEvent('onget', e.detail, { bubbles: true, composed: true })
    this.props.getPhone(e)
  }

  renderMsgContent(row, phone) {
    if (row.messageType === 'card') {
      return (
        <View className="item__content-card">
          <View className="card-msg">{row.message}</View>
          <View className="card-tip">你还可以通过以下方式快速联系我：</View>
          <View className="card-btn" onClick={this.makePhoneCall}>
            <Text className="iconfont icon-dianhua2"></Text>
            <Text>拨打我的电话</Text>
          </View>

          {
            phone ? (
              <View className="card-btn" onClick={this.getPhoneNumber}>
                <Text className="iconfont icon-shouji"></Text>
                <Text>留下您的电话</Text>
              </View>
            ) : (
                <Button className="card-btn" open-type="getPhoneNumber" onGetphonenumber={this.getPhoneNumber}>
                  <Text className="iconfont icon-shouji"></Text>
                  <Text>留下您的电话</Text>
                </Button>
              )
          }
        </View>
      )
    }
    if (row.messageType === 'image') {
      return (<Image className="item__content-img" mode="aspectFill" src={row.message} onClick={this.onPreviewImg.bind(this, row)} />)
    }

    return (<View className="item__content-txt">{row.message}</View>)

  }
  render() {
    const { item: { time, list } } = this.props
    const { userInfo: { person: { personId, phone, avatarurl } } } = this.props

    return (
      <View className="item">
        <View className="item__time"><Text className="item__time-text">{getDateFormat(time, true)}</Text></View>

        {/* {list.map(row => (<Item row={row} key={row.chatId}></Item>))} */}
        {list.map(row => (
          <View key={row.chatId} className={`item__wrap ${row.sendPerson === personId ? "self" : "other"}`} >
            <Image mode="aspectFit" className="item__headimg" src={row.sendPerson === personId ? avatarurl : (row.sendAvatar||require('@assets/default-avatar.png'))} />

            {this.renderMsgContent(row, phone)}
          </View>
        ))}
      </View>
    );
  }
}