<template>
  <view class="login">
    <u-loading-page
      :loading="true"
      loading-text="登陆中..."
      :bg-color="$colors.bgColor"
      color="#ffffff"
    />
  </view>
</template>

<script>
import Cache from '../utils/cache'

export default {
  components: {},

  data() {
    return {
      path: '/pages/index/index',
      query: {}
    }
  },
  computed: {},
  methods: {
    login() {
      // this.$loading('登陆中...')
      this.$api.user.login().then(async res => {
        this.$hideLoading()
        const { token, user_info } = res.data
        await this.$store.dispatch('user/token', token)
        await this.$store.dispatch('user/info', user_info)
        // 绑定上级
        const parentId = Cache.get('parent_id')
        if (parentId && !user_info.info.parent_id) {
          this.$api.user.bind(parentId).then(res => {
            console.log('-->bind parent success')
            this.$store.dispatch('user/info', res.data)
            Cache.remove('parent_id')
          })
        }
        this.relaunch()
      }).catch(async() => {
        await this.$store.dispatch('user/clear')
        this.relaunch()
      })
    },
    relaunch() {
      console.log('-->reLaunch path', this.path)
      uni.reLaunch({
        url: this.path,
        success() {
          console.log('-->reLaunch success')
        },
        fail(err) {
          uni.reLaunch({
            url: '/pages/index/index'
          })
          console.log('-->reLaunch error', err)
        }
      })
    }
  },
  onLoad(options) {
    console.log('-->data', options)
    if (this.$api.user.isLogin()) {
      uni.reLaunch({
        url: '/pages/index/index'
      })
      return
    }
    this.path = options.path ? options.path : this.path
    this.path = this.path.replace('//', '/')
    this.path = this.path.indexOf('/') !== 0 ? '/' + this.path : this.path
    const query = options.query ? JSON.parse(decodeURI(options.query)) : {}
    const queryArr = []
    for (const queryKey in query) {
      queryArr.push(`${queryKey}=${query[queryKey]}`)
    }

    this.path = this.path + '?' + queryArr.join('&')

    this.login()
  },
  onShow() {
    if (this.$api.user.isLogin()) {
      // uni.reLaunch({
      //   url: '/pages/index/index'
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
    .login{

    }
</style>
