<template>
</template>

<script>
import http from '@/utils/request'
import * as commonuni from '@/utils/commonuni'

// 设置tabbar可见性
const ystabbar = () => {
  uni.setTabBarItem({ index: 0, visible: true })
  uni.setTabBarItem({ index: 1, visible: true })
  uni.setTabBarItem({ index: 2, visible: false })
  uni.setTabBarItem({ index: 3, visible: false })
}

const djtabbar = () => {
  uni.setTabBarItem({ index: 0, visible: false })
  uni.setTabBarItem({ index: 1, visible: false })
  uni.setTabBarItem({ index: 2, visible: true })
  uni.setTabBarItem({ index: 3, visible: true })
}

export default {
  onLoad(option) {
    if (!option || !(option.code || option.openId || option.isLogin)) return

    const isLogin = option.isLogin === 'true' // 确保isLogin是布尔值
    console.log('isLogin value:', isLogin)

    if (isLogin) {
      this.handleLoginSuccess(option)
      return
    }

    const code = option.code
    const openId = option.openId
    const url = openId ? `app-api/wxLogin/loginOpenId?openId=${openId}` : `app-api/wxLogin/login?code=${code}`

    http.get(url).then(e => {
      uni.setStorage({ key: 'openId', data: e.openId })
      
      if (e.code === '4001') {
        uni.navigateTo({ url: '../login/register' })
        return
      }
      if (e.code === '4002') {
        uni.navigateTo({ url: '../login/registerSuccess' })
        return
      }
      if (e.code === '4003') {
        uni.navigateTo({
          url: `../login/registerFail?isRegister=${e.isRegister}&bhgText=${e.bhgText}&codeId=${e.id}&openId=${e.openId}`
        })
        return
      }

      this.handleLoginSuccess(e)
    })
  },

  methods: {
    handleLoginSuccess(data) {
      // 设置token
      uni.setStorage({ key: 'token', data: data.token })
	
      // 获取用户信息
	  // api/app-api/wxLogin/userInfo
      http.get("app-api/wxLogin/userInfo").then(user => {
        uni.setStorage({ key: 'userInfo', data: user })

		let roles = data.roleCode || []
		console.log("内容",roles)
		if((user.rolesCodes.toString().indexOf('YCAdmin')!= -1 && user.rolesCodes.toString().indexOf('flyAdmin') != -1) ||
			(roles.toString().indexOf('YCAdmin')!= -1 && roles.toString().indexOf('flyAdmin') != -1)){		
			uni.navigateTo({
				url:'/pages/login/multipleRoles'
			})
		}
		
		if ((user.rolesCodes.toString().indexOf('YCAdmin') != -1)
		|| (roles.toString().indexOf('YCAdmin') != -1)) {
			uni.switchTab({
				url: '../ypczk/djfk/index/djfkIndex'
			});
			// djtabbar()
		}
		
		if((user.rolesCodes.toString().indexOf('flyAdmin') != -1)
		|| (roles.toString().indexOf('flyAdmin') != -1)){
			uni.switchTab({
				url: '../ypczk/index/leaderIndex'
			});
			// ystabbar()
		}
		else {
			uni.navigateTo({
				url: '../login/registerFail'
			});
		}
		
      })
    }
  }
}
</script>