import Taro, { Component } from '@tarojs/taro'
import { connect } from '@tarojs/redux'
import { mergeNotNull } from '@/utils/tools'
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.showLoading()
    // 获取用户信息
    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 => {
          Taro.hideLoading()
          this.toPage(true)
        })
      },
      fail: () => {
        Taro.hideLoading()
        this.toPage(false)
      }
    })
  }

  toPage(succed) {
    const router = Taro.getStorageSync('router') || { query: {} }
    const loadOptions = wx.getLaunchOptionsSync()


    console.log('-------router, loadOptions--------->', router, loadOptions)

    let { query, path } = router
    if (!path) {
      query = loadOptions.query
      path = loadOptions.path
    } else {
      query = mergeNotNull(query, loadOptions.query)
    }

    console.log('-------query--------->', query)

    Taro.setStorageSync('firstLoading', '8')
    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
    }

    const params = query.params || Object.keys(query).map((k) => {
      const v = query[k]
      if (typeof v === 'object' || typeof v === 'function') {
        return ''
      }

      return `${k}=${v}`
    }).filter(x => x).join('&')

    console.log('-------params--------->', params)

    Taro.reLaunch({
      url: `/${path}?${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>
    )
  }
}
