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 {
  config = {
    navigationBarTitleText: '登录'
  }
  state = {}

  getUserInfo() {
    const { dispatchUpdateUserInfo } = this.props
    const sessionKey = Taro.getStorageSync('sessionKey')
    // 获取用户信息
    Taro.getUserInfo({
      lang: 'zh_CN',
      success: 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 => {
          this.toPage(true)
        })
      },
      fail: () => {
        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}`
    })
  }

  render() {
    return (
      <View>
        <View className="userinfo">
          <View className="userinfo-avatar">
            <open-data type="userAvatarUrl"></open-data>
          </View>
          <View className="userinfo-name">
            <open-data type="userNickName"></open-data>
          </View>
        </View>
        <View className='line'></View>
        <View className='content'>
          <View>申请获取以下权限</View>
          <Text>获得你的公开信息(昵称，头像等)</Text>
        </View>
        <Button className='bottom' open-type="getUserInfo" lang="zh_CN" onGetUserInfo={this.getUserInfo}>授权登录</Button>
      </View>
    )
  }
}
