import Taro, { Component } from '@tarojs/taro'
import { connect } from '@tarojs/redux'
import * as actions from '@/actions/user'
import './index.scss'

@connect(state => state.user, { ...actions })

export default class Index extends Component {

  state = {}
  componentDidMount() {
    const { user = {} } = this.props
    console.log('111')
    if (user.avatar && typeof this.props.onSuccess === 'function') {
      this.props.onSuccess();
    }
  }
  getUserInfo() {
    Taro.showLoading({ mask: true, title: '授权中...' });
    const { dispatchUpdateUserInfo } = this.props
    const sessionKey = Taro.getStorageSync('sessionKey')
    Taro.getUserInfo({
      lang: 'zh_CN',
      success: res => {
        console.log(res, "res")
        const payload = Object.assign(res, { sessionKey })
        // const { userInfo: { nickName, gender, country, city, province } } = payload
        // App.zhuge.identify(nickName, {
        //   '昵称': nickName,
        //   '性别': gender == 1 ? '男' : '女',
        //   '国家': country,
        //   '省份': province,
        //   '城市': city
        // })
        // 用户信息保存至服务器
        dispatchUpdateUserInfo(payload).then(res => {
          console.log('更新信息')
          this.props.onSuccess();
          Taro.hideLoading()
        })
      },
      fail: (err) => {
        console.error(err)
        Taro.hideLoading()
        Taro.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
        return
      }
    })
  }

  renderMaskBanner() {
    return (
      <View>
        <View className="avatar-page">
          <View className="content">
            <View className="title">请允许获取昵称、头像、地区及性别</View>
            <View className="touxiang"><open-data type="userAvatarUrl"></open-data></View>
            <View className="name"><open-data type="userNickName"></open-data></View>
            <Button className="btn" open-type="getUserInfo" lang="zh_CN" onGetUserInfo={this.getUserInfo}>好</Button>
          </View>
        </View>
      </View>
    )
  }
  render() {
    const { user = {} } = this.props

    return (
      <Block>
        {this.renderMaskBanner()}
        {/* {!user.avatar && this.renderMaskBanner()} */}
      </Block>
    )
  }
}
