<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" :loading="loading">
      点击授权
    </wd-button>
  </view>
</template>

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

const userStore = useUserStore()
const appStore = useAppStore()
const loading = ref(false)

// 微信登录
const handleLogin = async () => {
  loading.value = true
  wx.getUserProfile({
    desc: '用于完善用户信息',
    success: ({ userInfo }) => {
      //   console.log('用户信息:', userInfo)
      //   avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
      //   city: ""
      //   country: ""
      //   gender: 0
      //   is_demote: true
      //   language: ""
      //   nickName: "微信用户"
      //   province: ""
      userStore.setUserInfo(userInfo)

      // 获取token
      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

              appStore.setAppInfo({ token, userid, 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',
          })
        },
        complete: () => {
          loading.value = false
        },
      })
    },
    fail: function (err) {
      console.error('获取用户信息失败:', err)
      loading.value = false
      uni.showToast({
        title: '获取用户信息失败，请重试',
        icon: 'none',
      })
    },
  })
}

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

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