<template>
    <app-view class="g-form forget">
        <template #header>
            <app-navbar title="重置登录密码" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="formSubmit">
            <CellGroup inset>
                <Field v-model="formData.mobile" type="tel" name="mobile" label="手机号码" placeholder="必填"
                    autocomplete="off" :rules="formRules.mobile" />
                <Field v-model="formData.vcode" type="digit" name="vcode" label="短信验证码" placeholder="必填"
                    autocomplete="off" :rules="formRules.vcode">
                    <template #button>
                        <Button size="small" type="primary" :disabled="isCountdown" @click="sendVerifyCode">
                            <span v-if="isCountdown">重新发送({{ currentTime.seconds }})</span>
                            <span v-else>获取验证码</span>
                        </Button>
                    </template>
                </Field>
                <Field v-model="formData.password" name="password" type="password" label="新密码" placeholder="必填"
                    autocomplete="off" :rules="formRules.password" />
                <Field v-model="formData.confirmpassword" name="confirmpassword" type="password" label="确认密码"
                    placeholder="必填" autocomplete="off" :rules="formRules.confirmpassword" />
            </CellGroup>
        </Form>
        <template #footer>
            <div class="g-form__footer">
                <Button type="primary" @click="formRef?.submit()" round block>重置密码</Button>
            </div>
        </template>
    </app-view>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, Toast, FieldRule } from 'vant'
import { useCountDown } from '@vant/use'
import { fullloading, dialog } from '@/utils/vant'
import { getEncryptMobile } from '@/filters'
import { validateRules } from '@/constants/regex'
import { useNavigation } from '@/hooks/navigation'
import { queryLoginId } from '@/services/api/account'
import { resetPassword, sendResetVerifyCode } from '@/services/api/common'
import cryptojs from 'crypto-js'

const { router } = useNavigation()
const formRef = ref<FormInstance>()
const isCountdown = ref(false) // 是否正在倒计时

// 倒计时函数
const countdown = useCountDown({
    time: 60 * 1000,
    onFinish: () => {
        countdown.reset()
        isCountdown.value = false
    }
})

// 倒计时剩余时间
const currentTime = computed(() => countdown.current.value)

// 表单数据
const formData = reactive<Model.ResetPasswordReq & { confirmpassword: string }>({
    logincode: '',
    mobile: '',
    vcode: '',
    password: '',
    confirmpassword: '',
})

// 表单验证规则
const formRules: { [key in keyof Model.ResetPasswordReq | 'confirmpassword']?: FieldRule[] } = {
    mobile: [{
        required: true,
        message: '请输入手机号码',
        validator: (val) => {
            if (validateRules.phone.validate(val)) {
                return true
            }
            return validateRules.phone.message
        }
    }],
    password: [{
        required: true,
        message: '请输入新密码',
        validator: (val) => {
            if (validateRules.password.validate(val)) {
                return true
            }
            return validateRules.password.message
        }
    }],
    vcode: [{
        required: true,
        message: '请输入短信验证码',
    }],
    confirmpassword: [{
        required: true,
        message: '请输入确认密码',
        validator: (val) => {
            if (formData.password === val) {
                return true
            }
            return '新密码和确认密码不一致'
        }
    }],
}

// 发送手机验证码
const sendVerifyCode = () => {
    formRef.value?.validate('mobile').then(() => {
        sendResetVerifyCode({
            data: {
                mobile: getEncryptMobile(formData.mobile),
                businessType: 1
            },
            success: () => {
                isCountdown.value = true
                countdown.start()
            },
            fail: () => {
                Toast.fail('发送失败')
            }
        })
    })
}

const formSubmit = () => {
    fullloading((hideLoading) => {
        queryLoginId({
            data: {
                username: formData.mobile
            },
            success: (res) => {
                const { mobile, password, vcode } = formData
                const logincode = res.data
                const encryptedData = cryptojs.SHA256(logincode + password).toString()
                const encryptedHex = cryptojs.enc.Hex.parse(encryptedData).toString().toLocaleLowerCase()

                resetPassword({
                    data: {
                        logincode,
                        mobile: getEncryptMobile(mobile),
                        password: encryptedHex,
                        vcode,
                    },
                    success: (res) => {
                        if (res.code === '0') {
                            hideLoading()
                            dialog('密码重置成功，请重新登录。').then(() => {
                                router.back()
                            })
                        } else {
                            Toast.fail(res.message)
                        }
                    },
                    fail: (err) => {
                        Toast.fail(err)
                    }
                })
            },
            fail: (err) => {
                Toast.fail(err)
            }
        })
    })
}
</script>