<template>
    <page-meta :page-style="$theme.pageStyle">
        <!-- #ifndef H5 -->
        <navigation-bar :front-color="$theme.navColor" :background-color="$theme.navBgColor"
            :title="isVerify ? '验证手机号' : '绑定手机号'" />
        <!-- #endif -->
    </page-meta>
    <view class="bg-white min-h-full flex flex-col items-center px-[40rpx] pt-[40rpx] box-border">
        <view class="w-full">
            <view class="text-2xl font-medium mb-[60rpx]">{{ isVerify ? '验证手机号' : '绑定手机号' }}</view>
            <view v-if="isVerify && formData.mobile" class="text-sm text-muted mb-[30rpx]">请验证您的手机号 {{ formData.mobile
                }}</view>
            <view
                class="px-[18rpx] border border-solid border-lightc border-light rounded-[10rpx] h-[100rpx] items-center flex">
                <u-input class="flex-1" v-model="formData.mobile" :border="false" placeholder="请输入手机号码" />
            </view>
            <view
                class="px-[18rpx] border border-solid border-lightc border-light rounded-[10rpx] h-[100rpx] items-center flex mt-[40rpx]">
                <u-input class="flex-1" v-model="formData.code" placeholder="请输入验证码" :border="false" />

                <view class="border-l border-solid border-0 border-light pl-3 leading-4 ml-3 w-[180rpx]"
                    @click="sendSms">
                    <u-verification-code ref="uCodeRef" :seconds="60" @change="codeChange" change-text="x秒" />
                    <text :class="formData.mobile ? 'text-primary' : 'text-muted'">
                        {{ codeTips }}
                    </text>
                </view>
            </view>
            <view class="mt-[40rpx]">
                <u-button type="primary" hover-class="none" :customStyle="{
                    height: '100rpx',
                    opacity:
                        formData.mobile && formData.code
                            ? '1'
                            : '0.5'
                }" @click="handleConfirm">
                    确定
                </u-button>
            </view>
            <view class="mt-[24rpx] text-center">
                <text class="text-muted text-sm" @tap="handleSkip">跳过，暂不绑定</text>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { userBindMobile } from '@/api/user'
import { getVerifyInfo } from '@/api/app'
import { reactive, ref, shallowRef } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user'
const uCodeRef = shallowRef()
const codeTips = ref('')
const isVerify = ref(false)

const userStore = useUserStore()
const codeChange = (text: string) => {
    codeTips.value = text
}

const formData = reactive({
    type: 'bind',
    mobile: '',
    code: ''
})

onLoad((options: any) => {
    if (options?.from === 'verify' && options?.mobile) {
        isVerify.value = true
        formData.mobile = options.mobile
        formData.type = 'change'
    }
})

const sendSms = async () => {
    if (!formData.mobile) return uni.$u.toast('请输入手机号码')
    if (!uCodeRef.value?.canGetCode) return

    try {
        const data: any = await getVerifyInfo({ mobile: formData.mobile, scene: isVerify.value ? 'change' : 'bind' })
        const phone = data.phone
        const code = data.code

        formData.code = code
        uCodeRef.value?.start()

        uni.showModal({
            title: '发送验证短信',
            content: `请发送短信到 ${phone}\n发送内容：${code}\n\n点击确定将打开短信编辑界面`,
            confirmText: '发送短信',
            success: (res) => {
                if (res.confirm) {
                    // #ifdef APP-PLUS
                    try {
                        // @ts-ignore
                        const main = plus.android.runtimeMainActivity()
                        // @ts-ignore
                        const Intent = plus.android.importClass('android.content.Intent')
                        // @ts-ignore
                        const Uri = plus.android.importClass('android.net.Uri')
                        // @ts-ignore
                        const intent = new Intent(Intent.ACTION_SENDTO, Uri.parse('smsto:' + phone))
                        // @ts-ignore
                        intent.putExtra('sms_body', code)
                        // @ts-ignore
                        main.startActivity(intent)
                    } catch (e) {
                        uni.$u.toast('无法打开短信应用')
                    }
                    // #endif
                    // #ifdef H5
                    window.location.href = `sms:${phone}?body=${code}`
                    // #endif
                }
            }
        })
    } catch (error: any) {
        uni.$u.toast(error || '获取验证信息失败')
    }
}

const handleConfirm = async () => {
    if (!formData.mobile) return uni.$u.toast('请输入手机号码')
    if (!formData.code) return uni.$u.toast('请输入验证码')
    await userBindMobile(formData, { token: userStore.temToken || userStore.token })
    uni.$u.toast('绑定成功')
    if (userStore.temToken) {
        userStore.login(userStore.temToken!)
    }
    uni.switchTab({ url: '/pages/index/index' })
}

const handleSkip = () => {
    userStore.login(userStore.temToken!)
    uni.switchTab({ url: '/pages/index/index' })
}
</script>

<style lang="scss">
page {
    height: 100%;
}
</style>
