import Taro, { Component } from '@tarojs/taro'
import { connect } from '@tarojs/redux'
import './index.scss'
import { queryUserInfo } from '@services/user'
import { getMiniQrcode } from '@services/common'
import Poster from './poster'
import { ROLE_CODE } from '@constants/user'
@connect(
  ({ user }) => ({ ...user })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: '我的推广码'
  }
  state = {
    user: {},
    makePosterStatus: false,
    posterData: {},
    qrcode: ''
  }
  componentDidShow() {
    this.getPosterData()
  }

  getPosterData = () => {
    return new Promise(resolve => {
      const { posterData } = this.state
      if (posterData.qrcode) {
        resolve(posterData)
        return
      }
      const { userInfo: { person: { personId, personType, agentCode, avatarurl, nickname } } } = this.props
      const payload = {
        "scene": personType == ROLE_CODE['CONSULTANT'] ? `id=${personId}&from=card_share&recommender=${personId}` : `id=${personId}&from=share&recommender=${personId}&agentCode=${agentCode}`,
        "page": personType == ROLE_CODE['CONSULTANT'] ? 'pages/card/index' : 'pages/agent/become/index',
      }
      getMiniQrcode(payload).then(qrcode => {
        let data = {
          qrcode,//小程序二维码
          nickname,//访问者名字
          avatarurl: avatarurl,//访问者头像
          tip:personType == ROLE_CODE['CONSULTANT'] ? '扫一扫上面的二维码图案,成为我的客户' : '扫一扫上面的二维码图案,成为独立经纪人'
        }
        this.setState({
          qrcode
        })
        resolve(data)
      })
    })
  }

  // 开始生成海报
  toggleVisiblePoster = (flag) => {
    if (flag) {
      this.getPosterData().then(posterData => {
        this.setState({
          makePosterStatus: !!flag,
          posterData,
          actionSheetHide: true
        })
      })
    } else {
      this.setState({
        makePosterStatus: !!flag
      })
    }
  }
  render() {
    const { makePosterStatus, posterData, qrcode } = this.state
    const { userInfo: { person: { nickname, avatarurl, personType } } } = this.props
    return (
      <Block>
        {/* 生成海报 */}
        {makePosterStatus && (<Poster data={posterData} toggle={this.toggleVisiblePoster}></Poster>)}
        <View className='page'>
          <View className='spread-code'>
            <View className='spread-code-head'>
              <Image src={avatarurl} className='spread-code-head_img'></Image>
              <View className='spread-code-head_name'>{nickname}</View>
            </View>
            <Image src={qrcode} className='spread-code-qcode' mode='widthFix'></Image>
            {
              personType == ROLE_CODE['CONSULTANT'] ? <View className='spread-code-tip'>扫一扫上面的二维码图案,成为我的客户</View> : <View className='spread-code-tip'>扫一扫上面的二维码图案,成为独立经纪人</View>
            }
            
          </View>
          <View className='save_btn'  onClick={() => { this.toggleVisiblePoster(true) }}>保存到手机</View>
        </View>
      </Block>

    )
  }
}
