
<template>
    <app-view class="g-form">
        <template #header>
            <app-navbar :title="$t('mine.profile.wechat')" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="onSubmit">
            <CellGroup inset>
                <Field :required="true" v-model="formData.wechat" :rules="formRules.wechat" name="email" :label="$t('mine.profile.wechat')"
                    :placeholder="$t('common.required')" />
            </CellGroup>
        </Form>
        <template #footer>
            <div class="g-form__footer inset">
                <Button round block type="danger" @click="formRef?.submit">{{ $t('operation.submit') }}</Button>
            </div>
        </template>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, reactive } from 'vue'
import { Form, Field, FormInstance, CellGroup, FieldRule, Button, showFailToast } from 'vant'
import { updateUserInfoWechatAndEmail } from '@/services/api/user'
import { useLoginStore, useUserStore } from '@/stores'
import { useNavigation } from '@mobile/router/navigation'
import { fullloading } from '@/utils/vant'
import { decryptAES } from '@/services/websocket/package/crypto'

// formRef
const formRef = shallowRef<FormInstance>()
// loginStore
const loginStore = useLoginStore()
// userStore
const userStore = useUserStore()
// router
const { router } = useNavigation()

const formData = reactive<Model.UserInfoWechatAndEmailReq>({
    userid: loginStore.userId, // 用户ID
    wechat: decryptAES(userStore.userInfo.wechat), //  微信
})

// 表单验证规则
const formRules: { [key in keyof Model.UserInfoWechatAndEmailReq]?: FieldRule[] } = {
    wechat: [{
        message: '请输入微信号',
        validator: () => {
            return !!formData.wechat
        }
    }],
}

const onSubmit = () => {
    fullloading((hideLoading) => {
        updateUserInfoWechatAndEmail({
            data: formData
        }).then(() => {
            hideLoading()
            router.back()
        }).catch((err) => {
            showFailToast(err)
        })
    })
}
</script>