import Taro, { Component } from '@tarojs/taro'
import { View, Image } from '@tarojs/components'
import './com.scss'
export default class Comment extends Component {
  constructor (props) {
    super(props)
    this.state = {
      otherObj: '',
      curObj: {},
    }
  }


  componentWillMount () {
    this.props.onRef(this)
  }

  getData = (otherObj, str) => {
    const curSaleObj = Taro.getStorageSync('APP_cur_sale')
    if (curSaleObj.curObj) {
      if (str === 'estateDtl') {
        this.getList(otherObj)
      } else {
        this.setState({
          curObj: curSaleObj.curObj,
          otherObj,
        })
      }
    } else {
      this.getList(otherObj)
    }
  }

  getList (otherObj) {
    Taro.api.room.apisalelist({show_status: 1}).then(res => {
      const list = res.list || []
      const arrIndex = Math.floor(Math.random() * list.length)
      this.setState({
        curObj: list[arrIndex],
        otherObj,
      })
      Taro.setStorageSync('APP_cur_sale', {curObj: list[arrIndex]})
    })
  }



  netLink () {
    const { curObj, otherObj } = this.state
    Taro.navigateTo({
      url: `/pagesQa/msg/chat?to_user_id=${curObj.user_id}&eTitle=${otherObj.name}&eId=${otherObj.id}`
    })
  }
  callHandle () {
    const { curObj } = this.state
    Taro.makePhoneCall({
      phoneNumber: curObj.sale_phone
    })
  }
  afterCount (type) {
    if (type === 'chat') {
      this.netLink()
    }
    if (type === 'call') {
      this.callHandle()
    }
  }
  countHandle (type) {
    const { curObj, otherObj } = this.state
    let params = {
      target_id: otherObj.id,
      target_type: 2,
      sale_id: curObj.sale_id,
      click_type: type === 'call' ? '2' : '1' // 1在线聊 2打电话
    }
    Taro.api.room.apiusercontactclick(params).then(() => {
      this.afterCount(type)
    }).catch(() => {
      this.afterCount(type)
    })
  }




  render () {
    const { curObj } = this.state
    const tagStr = curObj.custom_tag ? curObj.custom_tag.substring(0, 8) : ''
    return (
      <View className="scoped-sale">
        <View className="ss-img">
          <Image src={curObj.sale_avatar} className="img"/>
        </View>
        <View className="ss-info">
          <View className="p1">{curObj.sale_name}</View>
          <View className="p2">{tagStr}</View>
        </View>
        <View className="ss-r">
          <View className="b" onClick={this.countHandle.bind(this, 'chat')}>在线问</View>
          <View className="b t2" onClick={this.countHandle.bind(this, 'call')}>打电话</View>
        </View>
      </View>
    )
  }
}