<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '登录',
  },
}
</route>

<template>
  <view class="flex flex-col items-center justify-center h-full">
    <!-- <image src="/static/wechat.png" class="w-16 h-16 mb-8" /> -->
    <view class="text-2xl font-bold mb-8 mt-20">达州农机优惠劵</view>
    <view class="text-gray-500 text-sm mb-8">申请获取以下权限</view>
    <view class="text-gray-500 text-sm mb-8">获取您的公开信息(昵称、头像等)</view>
    <wd-button type="success" round block @click="handleLogin">点击授权</wd-button>
  </view>
</template>

<script lang="ts" setup>
import { getAuthCode } from '@/service/auth'
import { onMounted } from 'vue'
import { until } from '@vueuse/core'

// 微信登录
const handleLogin = async () => {
  uni.login({
    provider: 'weixin',
    onlyAuthorize: true,
    success: async function (event) {
      try {
        const { loading, error, data } = useRequest(() => getAuthCode(event.code), {
          immediate: true,
        })

        // 等待数据加载完成
        await until(loading).toBe(false)

        if (!error.value && data.value) {
          const { token, userid, openid } = data.value as any

          uni.setStorageSync('token', token)
          uni.setStorageSync('userid', userid)
          uni.setStorageSync('openid', openid)

          uni.switchTab({ url: '/pages/index/index' })
        } else {
          uni.showToast({
            title: '授权失败，请重试',
            icon: 'none',
          })
        }
      } catch (err) {
        console.error('授权失败:', err)
        uni.showToast({
          title: '授权失败，请重试',
          icon: 'none',
        })
      }
    },
    fail: function (err) {
      console.error('登录失败:', err)
      uni.showToast({
        title: '登录失败，请重试',
        icon: 'none',
      })
    },
  })
}

onMounted(() => {
  // 检查是否已经授权
  //   uni.getSetting({
  //     success: (res) => {
  //       if (res.authSetting['scope.userInfo']) {
  //         uni.navigateBack()
  //       }
  //     },
  //   })
})
</script>

<style lang="scss" scoped>
//
</style>
