<template>
    <app-view class="g-form setting-password">
        <template #header>
            <app-navbar title="修改密码" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="onSubmit">
            <CellGroup inset>
                <Field v-model="formData.OldPwd" type="password" name="OldPwd" label="原密码" placeholder="必填"
                    autocomplete="off" :rules="formRules.OldPwd" />
                <Field v-model="formData.NewPwd" name="NewPwd" type="password" label="新密码" placeholder="必填"
                    autocomplete="off" :rules="formRules.NewPwd" />
                <Field v-model="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 { shallowRef } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, FieldRule, Toast } from 'vant'
import { fullloading, dialog } from '@/utils/vant'
import { validateRules } from '@/constants/regex'
import { useAuth } from '@/business/auth'
import { useAccountPassword } from '@/business/user'

const { logout } = useAuth()
const { formData, formSubmit } = useAccountPassword(1)
const formRef = shallowRef<FormInstance>()
const confirmpassword = shallowRef('')

// 表单验证规则
const formRules: { [key in keyof Proto.ModifyPwdReq | 'confirmpassword']?: FieldRule[] } = {
    OldPwd: [{
        required: true,
        message: '请输入原密码',
    }],
    NewPwd: [{
        required: true,
        message: '请输入新密码',
        validator: (val) => {
            if (validateRules.password.validate(val)) {
                return true
            }
            return validateRules.password.message
        }
    }],
    confirmpassword: [{
        required: true,
        message: '请输入确认密码',
        validator: (val) => {
            if (formData.NewPwd === val) {
                return true
            }
            return '新密码和确认密码不一致'
        }
    }],
}

const onSubmit = () => {
    fullloading((hideLoading) => {
        formSubmit().then(() => {
            hideLoading()
            dialog('密码修改成功，请重新登录。').then(() => {
                logout()
            })
        }).catch((err) => {
            Toast.fail(err)
        })
    })
}
</script>