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() {
    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.toPage(true)
          this.props.onSuccess();
        })
      },
      fail: (err) => {
        console.error(err)

        Taro.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
        return
        // this.toPage(false)
      }
    })
  }
  toPage(succed) {
    const router = Taro.getStorageSync('router')
    const { query, path } = router

    if (!succed && path === 'pages/signin/index') {
      return
    }
    if (path === 'pages/project/index' || path === 'pages/shop/index' || path === 'pages/person/index') {
      Taro.switchTab({
        url: '/' + path
      })
      return
    }
    Taro.reLaunch({
      url: `/${path}?${query.params}`
    })
  }

  renderMaskBanner() {
    return (
      <View>
        <View className="avatar-page">
          <View className="content">
            <View className="title">请允许获取昵称、头像、地区及性别</View>
            <Image className="touxiang" src={require('@assets/default-avatar.png')}></Image>
            <View className="name">用户昵称</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>
    )
  }
}
