<script setup lang="ts">
import { debounce } from 'feng-uniapp-exploit/utils/index'
import { getMobile } from '@/api/login'

import useUserStore from '@/store/user'
const userStore = useUserStore()

const loginCode = ref('')

// 获取微信登录 code
const getLoginCode = async (): Promise<string> => {
    try {
        const res = await uni.login({ provider: 'weixin' })
        loginCode.value = res.code
        return res.code
    } catch (error) {
        console.error('获取登录code失败:', error)
        throw error
    }
}

// 处理获取手机号

interface phoneEvent {
    detail: { errMsg: string; iv: string; encryptedData: string; code: string }
}
const onGetPhoneNumber = debounce(async (e: phoneEvent) => {
    if (e.detail.errMsg.includes('fail')) {
        uni.showToast({ title: '用户拒绝授权', icon: 'none' })
        return
    }

    try {
        if (!loginCode.value) {
            await getLoginCode()
        }

        if (!userStore.openId) {
            await userStore.getopenid({ code: loginCode.value })
        }

        getMobile({ openid: userStore.openId, code: e.detail.code })
            .then((res) => {
                const { data: phone } = res as { data: string }

                userStore.mobile = phone

                userStore.getUserInfo()

                onLoginSuccess()
            })
            .catch(() => {
                uni.showToast({ title: '登录失败！', icon: 'none' })
            })
    } catch (error) {
        uni.showToast({ title: '登录失败', icon: 'none' })
    }
})

const onLoginSuccess = () => {
    uni.showToast({
        title: '登录成功',
        icon: 'none',
        success: () => {
            setTimeout(() => {
                userStore.showtoast = false
                uni.reLaunch({ url: '/pages/votingElection/index' })
            }, 1000)
        }
    })
}

onShow(() => {
    if (userStore.mobile) {
        onLoginSuccess()
    }
})
</script>
<template>
    <view class="login">
        <image class="logo-img" src="@/static/logo.png" mode="widthFix" />

        <view class="btn_box">
            <u-button
                @getphonenumber="onGetPhoneNumber"
                text="手机号快捷签到"
                icon-color="#fff"
                open-type="getPhoneNumber"
                color="linear-gradient(270deg, rgba(232, 123, 7, 1) 0%, rgba(247, 205, 77, 1) 100%)"
                shape="circle"
            />
        </view>
    </view>
</template>

<style scoped lang="scss">
.login {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    position: relative;
    text-align: center;
    box-sizing: border-box;
    padding: 500rpx 30rpx 0;
    background-color: #fff;

    .logo-img {
        width: 220rpx;
        margin-bottom: 60rpx;
    }
}
</style>
