import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import AchievePhone from '@/components/achievePhone'
import AchieveAvatar from '@/components/achieveAvatar'
import { connect } from '@tarojs/redux'
import ready from '@/utils/ready'
import { queryHouseDetail } from '@/services/project'
import dayjs from 'dayjs'
import { transferImage } from '@/utils/tools'
import Blank from '../../components/Blank'
import * as noticeType from '@/constants/common.js'
import Statement from '../../components/Statement'
import { View } from '@tarojs/components'
import * as houseActions from '@/actions/house'

@connect(
  ({ user, house }) => ({ ...user, house }),
  { ...houseActions }
)

export default class Index extends Component {
  config = {
    navigationBarTitleText: '房源详情',
  }

  state = {
    grantPhoneVisible: false, // 授权电话
    grantAvatarVisible: false, // 授权头像
    houseDetail: {},
    popVisiable: false,
  }

  componentDidShow() {
    ready.queue(() => {
      // 分享场景需要先授权手机, 再授权头像
      if (this.toggleGrantPhone()) {
        this.toggleGrantAvatar()
      }
      const id = this.$router.params.id
      const { userInfo: { person: { personId } } } = this.props
      const params = {
        houseId: id,
        personId,
      }
      queryHouseDetail(params).then(res => {
        this.setState({
          houseDetail: !res ? {} : res,
          buildingImgList: res.buildingImgList || []
        })
      })

    })
  }



  // 调起授权电话
  toggleGrantPhone = () => {
    const { userInfo: { person: { phone, tel } } } = this.props
    if (!phone && !tel) {
      this.setState({ grantPhoneVisible: true })
      return false
    }
    console.log('phone:', phone, 'tel:', tel, '!!!!!')
    console.log(this.props, 'this.propsphone!!!!!')

    return true
  }

  // 调起授权头像
  toggleGrantAvatar = () => {
    const { userInfo: { person: { avatarurl } } } = this.props

    if (!avatarurl || avatarurl.indexOf('wx.qlogo.cn') === -1) {
      this.setState({ grantAvatarVisible: true })
      return false
    }

    console.log(avatarurl, "avatarurl")
    console.log(this.props.userInfo, "this.props")
    return true
  }

  chooseBtn(type) {
    const { houseDetail: { houseId, buildingId } } = this.state
    Taro.navigateTo({
      url: `/onlineSelling/pages/detail/resultPage?type=${type}&id=${houseId}&buildingId=${buildingId}`
    })
    this.setState({ popVisiable: false })
  }


  handleChat(buildingId) {
    Taro.navigateTo({
      url: `/pages/card/list/index?buildingId=${buildingId}`
    })
  }

  handlePanoramaClick(panoramaLink) {

    if (!panoramaLink) return;

    Taro.navigateTo({ url: `/pages/project/panorama/index?url=${encodeURIComponent(panoramaLink)}` })

  }

  goToPanorama(panoramaLink) {
    if (!panoramaLink) return;

    this.navigateTo(`/pages/project/panorama/index?url=${encodeURIComponent(panoramaLink)}`)

  }

  handlePanoramaClick(panoramaLink) {
    this.goToPanorama(panoramaLink)
  }
  navigateTo(url) {
    Taro.navigateTo({ url: url })
  }
  open() {
    const { houseDetail: { isPreselect } } = this.state
    if (!isPreselect) {
      const { userInfo: { miniApp: { tpls } } } = this.props

      const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_HOUSE && x.isSubscribe == true)[0] || {}).tplId
      const that = this
      wx.requestSubscribeMessage({
        tmplIds: [tplId],
        success(res) { },
        fail(res) { },
        complete() {
          that.setState({ popVisiable: true })
        }
      })
    } else {
      this.setState({ popVisiable: true })
    }

  }

  toRaiseMoney() {
    const detail = this.state.houseDetail || {}

    if (detail.status != 1 || detail.houseLockingStatus == 'locked') {
      Taro.showToast({
        url: '当前房源被锁定或未发布, 不能认筹',
        icon: 'none',
      })

      return;
    }


    this.props.dispatchAddCart(detail)
    Taro.navigateTo({ url: `/onlineSelling/pages/raiseMoney/index?houseId=${detail.houseId}&salesBatchId=${detail.salesBatchId}` })
  }


  render() {
    const { grantPhoneVisible, grantAvatarVisible, houseDetail, buildingImgList = [], popVisiable } = this.state
    const { taRaise } = this.state.houseDetail
    const { userInfo } = this.props
    const address = `${houseDetail.buildingName || ''}${houseDetail.termName || ''}${houseDetail.blockName || ''}${houseDetail.unitName || ''}${houseDetail.floorName || ''}${houseDetail.roomName || ''}`

    return (
      <Block>
        {
          grantPhoneVisible &&
          <AchievePhone user={userInfo.person} onSuccess={this.toggleGrantAvatar}></AchievePhone>
        }
        {
          grantAvatarVisible &&
          <AchieveAvatar user={userInfo.person} onSuccess={() => { this.setState({ grantAvatarVisible: false }) }} ></AchieveAvatar>
        }
        {popVisiable &&
          <Block>
            <View className="mask"> </View>
            <View className="pop-box">
              <View className="title" >{!houseDetail.isPreselect ? `确认使用手机号${userInfo.person.phone || userInfo.person.tel}预选此房源？` : '确认取消预选此房源？'}</View>
              <View className="sure" onClick={!houseDetail.isPreselect ? () => this.chooseBtn('add') : () => this.chooseBtn('cancel')}>确定</View>
              <View className="cancel" onClick={() => this.setState({ popVisiable: false })}>取消</View>
            </View>
          </Block>
        }

        <View className='detail'>
          <View className='detail-top'>
            {buildingImgList && buildingImgList.length ?
              <Image className="cover-img" mode="widthFix" onClick={() => buildingImgList[0].type == '1' ? this.handlePanoramaClick(buildingImgList[0].panoramaLink) : ''} src={transferImage(buildingImgList[0].url)} />
              : <Blank tips="暂无户型信息"></Blank>
            }
          </View>
          {buildingImgList && buildingImgList.length && buildingImgList[0].type == '1' &&
            <Image className="vr-img" onClick={() => this.handlePanoramaClick(buildingImgList[0].panoramaLink)} src={require('@/assets/vr.png')} />
          }
          <ScrollView
            enableBackToTop
            className="wrap"
            scrollY>
            <View className='detail__main'>
              <View style="padding: 0 30rpx;">
                <View className="name">{houseDetail.apartmentName || ''}</View>
                <View className="btn" onClick={() => this.handleChat(houseDetail.buildingId)}>询问优惠</View>
                {
                  taRaise.displayHousePrice && <View className="price"> 现价：{houseDetail.price}万</View>
                }

                {houseDetail.apartmentName &&
                  <View className="area">
                    {houseDetail.buildingArea ? <Text>建筑面积约<Text style="color:#FE1C1C">{houseDetail.buildingArea}</Text>m² </Text> : '建筑面积待定'}
                    <Text style="margin-left:20rpx">{houseDetail.insideArea ? <Text>使用面积约<Text style="color:#FE1C1C">{houseDetail.insideArea}</Text>m² </Text> : '使用面积待定'}</Text>
                  </View>
                }
                <View className="address">
                  <Image className="location-icon" src={require('../../assets/location.png')}></Image>{address || ''}
                </View>
                <View className="date">
                  预选时间：{dayjs(houseDetail.preselectionStartTime).format('MM/DD HH:mm:ss')}--{dayjs(houseDetail.preselectionEndTime).format('MM/DD HH:mm:ss')}
                </View>
                {taRaise && <View className="date">认筹时间：{dayjs(taRaise.raiseStartTime).format('MM/DD HH:mm:ss')}--{dayjs(taRaise.raiseEndTime).format('MM/DD HH:mm:ss')}
                </View>}

              </View>
              <View className="num">
                已有{houseDetail.realHeat + houseDetail.heat + 0}人预选此房源，快快预选认筹~
              </View>
              <Statement style="margin: 104rpx 0 30rpx 0" />
              <View style="padding: 0 30rpx;">
                {
                  houseDetail.preselectionBtn && <View>
                    {!houseDetail.isPreselect ?
                      <View className="choose-btn" onClick={() => this.open()}>
                        预选此房源
                  </View> : <View className="choose-btn" onClick={() => this.open()}>
                        取消预选
                  </View>
                    }
                  </View>
                }

                {houseDetail.raiseBtn && <View className="raise-btn" onClick={() => this.toRaiseMoney()}>
                  认筹此房源
              </View>}
              </View>
            </View>
          </ScrollView>
        </View>

      </Block >
    );
  }
}
