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

import Notice from '@components/Notice'
import Poster from './poster'
import ProjectItem from '../project/item'
import BackHomeBtn from '@components/BackHomeBtn'
import getUserPhone from '@utils/getUserPhone'
import ready from '@utils/ready'

import { ROLE_CODE } from '@constants/user'
import { addCardUv, addCardShareNum, favorCard, cancelFavorCard } from '@services/card'
import { getMiniQrcode, savePoint, updatePoint } from '@services/common'
import { connect } from '@tarojs/redux'
import { reportClient } from '@services/report'

import * as actions from '@actions/card'
import { dispatchProjectDetail } from '@actions/project'


@connect(
  ({ user, card, project }) => ({ ...user, ...card, ...project }),
  { dispatchProjectDetail, ...actions }
)

export default class Index extends Component {
  config = {
    navigationBarTitleText: '个人主页' 
  }
  state = {
    cardId: null,
    loaded: false,
    makePosterStatus: false,
    posterData: {},
    actionSheetHide: true, // 控制分享弹窗modal
    recordId: null,
    isSave: false,
    modalStatus: false,
  }

  componentWillMount() {
    ready.queue(() => {
      const router = Taro.getStorageSync('router')
      const id = this.$router.params.id || router.query.id || '4604a792d575eb8187711625bd88832c'

      if(router.query.id){
        this.setState({
          cardId: id,
          modalStatus: true
        }, this.loadCardDetail)
      }else{
        this.setState({
          cardId: id,
          modalStatus: false
        }, this.loadCardDetail)
      }

      addCardUv(id)
    })
  }

  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

  loadCardDetail() {
    const { cardId } = this.state
    const { dispatchCardInfo, dispatchProjectDetail } = this.props
    Taro.showLoading()
    dispatchCardInfo(cardId).then(res => {
      Taro.hideLoading()
      this.setState({
        loaded: true,
        isSave: res.isSave
      })
      let buildingId = res.projects[0]
      if (buildingId) {
        dispatchProjectDetail(buildingId)
      }
      savePoint({
        event: 'detail',
        eventType: 'card',
        propertyName: '个人主页',
        buildingId: buildingId,
        targetId: cardId,
        data: '{}'
      }).then(res1 => {
        this.setState({
          recordId: res1.recordId
        })
        console.log('个人主页')
      })
    })
  }
  // 跳转页
  navigateTo(url) {
    Taro.navigateTo({ url: url })
  }

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

  getLocation = () => {
    const { cardInfo: { address, company } } = this.props
    Taro.getLocation({ //返回可以用于Taro.openLocation的经纬度，官方提示bug: iOS 6.3.30 type 参数不生效，只会返回 wgs84 类型的坐标信息  
      success: function (res) {
        Taro.openLocation({
          latitude: 31.979190,
          longitude: 118.733660,
          name: company,
          address
        })
      }
    })
    savePoint({
      event: 'navigation',
      eventType: 'card',
      propertyName: '导航',
      data: '{}'
    }).then(res => {
      console.log('导航')
    })
  }

  // 同步到通讯录
  addContacts = () => {
    const { name, phone } = this.props.cardInfo
    Taro.addPhoneContact({
      firstName: name,//联系人姓名
      mobilePhoneNumber: phone//联系人手机号
    })
    savePoint({
      event: 'sync',
      eventType: 'card',
      propertyName: '同步通讯录',
      data: '{}'
    }).then(res => {
      console.log('同步通讯录')
    })
  }

  //转发
  onShareAppMessage = (e) => {
    const {
      userInfo: { personId },
      cardInfo: { id, name, picture, projects }
    } = this.props
    const isSelf = personId === id

    // const btnId = (e.target && e.target.id)
    // const isReport = btnId === 'reportBtn'

    // 分享埋点
    addCardShareNum(id)
    savePoint({
      event: 'share',
      eventType: 'card',
      propertyName: '置业顾问卡片分享',
      data: '{}'
    }).then(res => {
      console.log('置业顾问卡片分享')
    })

    return {
      title: isSelf ? `欢迎访问${name}个人主页` : `${name}邀请您成为TA的客户`,//分享内容
      path: `/pages/card/index?id=${id}&from=card_share&recommender=${personId}`,
      imageUrl: picture
    }
  }
  openActionSheet = () => {
    this.setState({
      actionSheetHide: false
    });
  }

  listenerActionSheet = () => {
    this.setState({
      actionSheetHide: !this.state.actionSheetHide
    })
  }

  onLike = () => {
    const { cardInfo: { liked, id, name, phone }, dispatchCardLike, dispatchCardUnlike } = this.props

    if (liked) {
      dispatchCardUnlike(id).then(res => {
        Taro.showToast({
          title: '取消点赞'
        })
        savePoint({
          event: 'like',
          eventType: 'card',
          propertyName: '取消点赞',
          data: '{}'
        }).then(res => {
          console.log('取消点赞')
        })
      })

    } else {
      dispatchCardLike(id).then(res => {
        Taro.showToast({
          title: '点赞成功'
        })
        savePoint({
          event: 'like',
          eventType: 'card',
          propertyName: '给置业顾问点赞',
          data: '{}'
        }).then(res => {
          console.log('给置业顾问点赞')
        })
      })
    }
  }

  onViewFans = () => {
    const { cardInfo: { id } } = this.props
    this.navigateTo('/pages/card/fans/index?type=card&id=' + id)
  }

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

  toChatList = () => {
    this.navigateTo('/pages/im/list/index')
  }

  toCardList = () => {
    this.navigateTo('/pages/card/list/index')
  }

  toHomePage = () => {
    Taro.switchTab({
      url: '/pages/project/index'
    })
  }
  toProjectDetail = () => {
    const { projectDetail: { buildingId } } = this.props
    this.navigateTo(`/pages/project/detail/index?id=${buildingId}`)
  }
  getPosterData = () => {
    return new Promise(resolve => {
      const { posterData } = this.state
      if (posterData.qrcode) {
        resolve(posterData)
        return
      }
      const { userInfo: { person }, projectDetail: { buildingId }, cardInfo } = this.props
      const { id } = cardInfo
      const { personId } = person
      const payload = {
        "scene": `id=${id}&from=card_share&recommender=${personId}&buildingId=${buildingId}`,
        "page": 'pages/card/index',
      }
      getMiniQrcode(payload).then(qrcode => {
        let data = Object.assign({ qrcode }, cardInfo)
        resolve(data)
      })
    })
  }

  // 开始生成海报
  toggleVisiblePoster = (flag) => {
    if (flag) {
      this.getPosterData().then(posterData => {
        this.setState({
          makePosterStatus: !!flag,
          posterData,
          actionSheetHide: true
        })
      })
    } else {
      this.setState({
        makePosterStatus: !!flag
      })
    }
    savePoint({
      event: 'poster',
      eventType: 'card',
      propertyName: '生成海报',
      data: '{}'
    }).then(res => {
      console.log('生成海报')
    })
  }

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

  handleGetPhone(e) {
    getUserPhone(e, (phoneNumber) => {
      if (phoneNumber) {
        this.handleModalConfirm(phoneNumber)
      } else {
        Taro.showToast({
          title: '授权失败，请重试',
          icon: 'none'
        })
      }
    })
  }

  handleModalConfirm() {
    const {
      cardInfo: { id, projects },
      userInfo: { person: { phone, tel } }
    } = this.props

    const buildingId = projects[0]

    const payload = {
      realtyConsultant: id, //报备人 置业顾问
      buildingId,
      phone: phone || tel
    }
    reportClient(payload).then(res => {
      this.hideModal()
      Taro.showToast({
        title: '报备成功'
      })
    })
  }

  // 卡片收藏
  cardCollection() {
    const { cardId, isSave } = this.state

    if (isSave) {
      cancelFavorCard(cardId).then(res => {
        Taro.showToast({
          title: '已取消收藏'
        })
        this.setState({
          isSave: false
        })
        savePoint({
          event: 'save',
          eventType: 'card',
          propertyName: '取消个人主页收藏',
          data: '{}'
        }).then(res => {
          console.log('取消个人主页收藏')
        })
      })
    } else {
      favorCard(cardId).then(res => {
        Taro.showToast({
          title: '收藏成功'
        })
        this.setState({
          isSave: true
        })
        savePoint({
          event: 'save',
          eventType: 'card',
          propertyName: '个人主页收藏成功',
          data: '{}'
        }).then(res => {
          console.log('个人主页收藏成功')
        })
      })
    }
  }

  hideModal() {
    this.setState({
      modalStatus: false
    })
  }
  render() {
    const { makePosterStatus, posterData, modalStatus } = this.state
    const { userInfo, cardInfo, projectDetail } = this.props
    const { person: { personType, personId, phone, tel } } = userInfo
    const { unReadNum, picture, visitors, id, isReport } = cardInfo
    const { buildingId } = projectDetail

    const visitorList = visitors ? visitors.slice(0, 5) : []
    const isSelf = personId === id

    const isConsultant = personType === ROLE_CODE['CONSULTANT']
    const hadPhone = (phone || tel) ? true : false
    const visibleChatBtn = !isConsultant && !isSelf
    // const visibleConfirmModal = modalStatus && !isReport && !isSelf && (personType === ROLE_CODE['DRIFT'] || personType === ROLE_CODE['CUSTOMER'])
    const visibleConfirmModal = modalStatus && !isReport && !isSelf
    return (
      <Block>
        {/* 生成海报 */}
        {makePosterStatus && (<Poster data={posterData} toggle={this.toggleVisiblePoster}></Poster>)}

        {
          visibleConfirmModal && (
            <View className="modal">
              <View className="modal-mask" onClick={this.hideModal}></View>
              <View className="modal-body">
                <View className="modal-body__con">请确认是否成为他的客户？</View>
                {
                  hadPhone ? (
                    <Button onClick={this.handleModalConfirm} className='modal-body__btn'>确认</Button>
                  ) : (
                      <Button open-type="getPhoneNumber" onGetphonenumber={this.handleGetPhone} className='modal-body__btn'>确认</Button>
                    )
                }
              </View>
            </View>
          )
        }

        {this.state.loaded && (
          <View className='mycard'>
            <Notice />
            <ScrollView scrollY>
              <View className='mycard__user__info'>
                <View className='mycard__user__imgox'>
                  <Image className='mycard__user__img' src={picture} mode="aspectFill"></Image>
                  <Image src={picture} mode="aspectFill" className='head__img'></Image>
                </View>
                <Image src={require('@assets/person/top.png')} className='top-img' mode="aspectFill"></Image>
              </View>

              <View className='mycard__user__information'>
                {/* 姓名电话 */}
                <View className='mycard__user__information__show'>
                  <View className='tel-info'>
                    <Text className='mycard__user__information__show__name'>{cardInfo.name}</Text>
                    {/* <Text className="line">|</Text> */}
                    <Text className='mycard__user__information__show__tel' onClick={this.makePhoneCall}> {cardInfo.phone}</Text>
                  </View>
                  {
                    visibleChatBtn && (
                      hadPhone ? (
                        <View onClick={this.toChatPage}>
                          <Image src={require('@assets/person/zixun.png')} className='chat-img'></Image>
                          {unReadNum > 0 && <Text className="unread-num">{unReadNum}</Text>}
                        </View>
                      ) : (
                          <Button className="clear-btn" open-type="getPhoneNumber" onGetphonenumber={this.getPhoneNumber}>
                            <Image src={require('@assets/person/zixun.png')} className='chat-img'></Image>
                            {unReadNum > 0 && <Text className="unread-num">{unReadNum}</Text>}
                          </Button>
                        )
                    )
                  }

                </View>
                <View className='row medal'>
                  <Image mode="aspectFill" className="img" src={require('@assets/person/jinpai.png')}></Image>
                  <Text>金牌置业顾问</Text>
                </View>

                {/* 职位 */}
                <View className='mycard__work'>
                  <View className='row mycard__work-department'>{cardInfo.department || ''}<Text className='txt'>部门</Text></View>
                  <View className='row mycard__work-position'>{cardInfo.post || ''}<Text className='txt'>职位</Text></View>
                  <View className='row mycard__work-company'>{projectDetail.buildingName || ''}<Text className='txt'>楼盘</Text></View>
                </View>

                {/* 人气 */}
                <View className='like-info'>
                  <View className="like-info__fans">
                    <View className="fans__list" onClick={this.onViewFans}>
                      <View className="fans__list-con">
                        {visitorList.map(item => (
                          <Image className='fans__list-img' key={item.personId} src={item.avatar}></Image>
                        ))}
                      </View>
                      {visitors.length >= 5 && <Text className="iconfont icon-shenglvehao"></Text>}
                    </View>
                    <View className="fans__num">
                      <Image className='nb' src={require('@assets/person/nb.png')}></Image>
                      <Text>人气</Text>
                      <Text>{visitors.length}</Text>
                    </View>
                  </View>
                  <View className="like-info__zan" onClick={this.onLike}>
                    <Text className={`iconfont icon-dianzan2 ` + (cardInfo.liked ? 'liked' : '')}></Text>
                    <Text className="like-info__zan-num">赞{cardInfo.likeNum || 0}</Text>
                  </View>
                </View>
                {/* 分享名片按钮 */}
                <View className='card__btn'>
                  <Button className={`carbtn ${isConsultant ? '' : 'poster-btn'}`} onClick={() => { this.toggleVisiblePoster(true) }}>{isConsultant ? '生成海报' : '生成海报分享给朋友'}</Button>
                  {/* {
                    isConsultant && (<Button id="reportBtn" className='carbtn' open-type="share">客户报备</Button>)
                  } */}
                </View>
              </View>
              <View className='detailed__information'>
                <View className='detailed__information__title'>详细信息</View>
                <View className='detailed__main'>
                  <View className='detailed__tel' onClick={this.makePhoneCall}>
                    <View className='detailed__tel__txt'>
                      <Text className='tel__txt' space='ensp'>手机&emsp;</Text> {cardInfo.phone}
                    </View>
                    <Text className='iconfont icon-dianhua tel__img'></Text>
                  </View>
                  <View className='detailed__add' onClick={this.getLocation}>
                    <View className='detailed__add__txt'>
                      <Text className='add__txt' space='ensp'>地址&emsp;</Text> {cardInfo.address}
                    </View>
                    <Text className='iconfont icon-daohangdizhi add__img'></Text>
                  </View>
                  {/* <Button className='mail__list__btn' onClick={this.addContacts}>同步到通讯录</Button> */}
                  <Button className='mail__list__btn' onClick={this.openActionSheet}>分享主页</Button>
                </View>
              </View>

              {buildingId && (
                <View className="pro__info">
                  <View className='project__title'>项目信息</View>
                  <ProjectItem data={projectDetail} onClick={this.toProjectDetail.bind(this)} />
                </View>
              )}

            </ScrollView>

            <BackHomeBtn></BackHomeBtn>

            {/* 底部弹框 */}
            <action-sheet hidden={actionSheetHide} bindchange={this.listenerActionSheet}>
              <action-sheet-item open-type="share">
                <Button open-type="share" className='share__friend'>分享给好友</Button>
              </action-sheet-item>
              <action-sheet-item><Button className='creat__img' onClick={() => { this.toggleVisiblePoster(true) }}>生成海报 保存分享</Button></action-sheet-item>
              <action-sheet-cancel onClick={this.listenerActionSheet}>取消</action-sheet-cancel>
            </action-sheet>
          </View>
        )}
      </Block>
    )
  }
}
