<script>
import config from './config'
import store from '@/store'
import { getAccessToken } from '@/utils/auth'

export default {
  data() {
    return {
      invateId: ''
    }
  },
  onLaunch: function (options) {
    if (options.query.invateId) {
      this.invateId = options.query.invateId
    }
    this.initApp()
  },
  methods: {
    // 初始化应用
    async initApp() {
      await uni.hideTabBar()
      uni.hideTabBar({
        animation: false
      })
      // 初始化应用配置
      this.initConfig()
      // 检查用户登录状态
      this.checkLogin()
    },
    initConfig() {
      this.globalData.config = config
    },
    checkLogin() {
      if (!getAccessToken()) {
        this.login()
      } else {
        this.loginSuccess()
      }
    },
    login() {
      uni.login({
        success: res => {
          const data = {
            type: 34,
            code: res.code,
            state: 'default',
            userType: this.getUserType()
          }
          // 系统登录
          this.$store.dispatch('Login', data).then(() => {
            this.loginSuccess()
          })
        }
      })
    },
    getUserType() {
      // 企业邀请
      if (this.invateId) return 2
      // if (this.type == 'internal') return 3
      // return 1
      return 3
    },
    loginSuccess() {
      this.$store.dispatch('GetInfo').then(res => {
        this.handlerNavigateTo(res.data.user)
      })
    },
    handlerNavigateTo(user) {
      // 邀请企业
      if (this.invateId) {
        uni.navigateTo({
          url: `/sub/enterprise/edit?invateId=${this.invateId}`
        })
        return
      }

      // 审核中
      if (user.audit == 1) {
        uni.navigateTo({
          url: '/sub/common/waiting'
        })
        return
      }

      // 审核通过
      if (user.audit == 2) {
        return
      }

      // 局内用户首次登录
      uni.navigateTo({
        url: '/sub/owner/edit'
      })
    }
  }
}
</script>

<style lang="scss">
@import '@/uni_modules/windi-css-uniapp/index.scss';
@import '@/static/scss/index.scss';
</style>
