<!-- 实名认证 -->
<template>
    <app-view class="g-form account-certification">
        <template #header>
            <app-navbar :title="t('user.authentication.title')" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="onSubmit">
            <CellGroup title="信息填写" inset>
                <Field v-model="formData.username" name="username" :label="t('user.authentication.customername')"
                    :placeholder="t('user.authentication.pleaseentertheusername')" :rules="formRules.username" />
                <Field name="cardtype" :label="t('user.authentication.cardtype')" :rules="formRules.cardtype" is-link>
                    <template #input>
                        <app-select v-model="formData.cardtype"
                            :placeholder="t('user.authentication.pleaseselectthecardtype')" :options="cerTypePersonList"
                            @confirm="formRef?.validate('cardtype')" />
                    </template>
                </Field>
                <Field v-model="formData.cardnum" name="cardnum" :label="t('user.authentication.cardnum')"
                    :placeholder="t('user.authentication.pleaseenterthecardnum')" :rules="formRules.cardnum"
                    v-if="formData.cardtype !== undefined" />
                <Field name="cardfrontphotourl" :label="t('user.authentication.cardfrontphoto')"
                    :rules="formRules.cardfrontphotourl">
                    <template #input>
                        <app-uploader @success="b_afterRead" />
                    </template>
                </Field>
                <Field name="cardbackphotourl" v-if="showCardBackPhoto" :label="t('user.authentication.cardbackphoto')"
                    :rules="formRules.cardbackphotourl">
                    <template #input>
                        <app-uploader @success="f_afterRead" />
                    </template>
                </Field>
                <Field name="halfbodyphotourl" v-if="showHalfBodyPhoto" :label="halfBodyPhotoTitle"
                    :rules="formRules.halfbodyphotourl">
                    <template #input>
                        <app-uploader @success="h_afterRead" />
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <div class="g-form__footer inset">
            <Button type="primary" @click="formRef?.submit" round block>
                {{ t('user.authentication.submit') }}
            </Button>
        </div>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, showFailToast, FieldRule } from 'vant'
import { addAuthReq } from '@/business/user'
import { fullloading, dialog } from '@/utils/vant'
import { getCerTypePersonList } from "@/constants/account"
import { useNavigation } from '@mobile/router/navigation'
import { useRequest } from '@/hooks/request'
import { getWskhOpenAccountConfigs } from '@/services/api/account'
import { i18n, useUserStore } from '@/stores'
import AppUploader from '@mobile/components/modules/uploader/index.vue'
import AppSelect from '@mobile/components/base/select/index.vue'

const userStore = useUserStore()
const formRef = shallowRef<FormInstance>()
const { formData, formSubmit } = addAuthReq()
const { router } = useNavigation()
const { global: { t } } = i18n

const cerTypePersonList = getCerTypePersonList() // 证件类型列表

const showHalfBodyPhoto = shallowRef(false)
const showCardBackPhoto = shallowRef(false)
const halfBodyPhotoTitle = shallowRef('')

// 获取网上开户配置
useRequest(getWskhOpenAccountConfigs, {
    defaultParams: {
        configs: '53,54,78'
    },
    onSuccess: (res) => {
        const configMap = new Map(res.data.map((item) => [item.configid, item.configvalue]))

        /// 是否显示半身照和 证件背面照
        showCardBackPhoto.value = configMap.get(53) === '1'
        showHalfBodyPhoto.value = configMap.get(54) === '1'
        halfBodyPhotoTitle.value = configMap.get(78) ?? t('user.authentication.halfbodyphoto')
    }
})

const b_afterRead = (filePath: string) => {
    formData.cardfrontphotourl = filePath
    formRef.value?.validate('cardfrontphotourl')
}

const f_afterRead = (filePath: string) => {
    formData.cardbackphotourl = filePath
    formRef.value?.validate('cardbackphotourl')
}

const h_afterRead = (filePath: string) => {
    formData.halfbodyphotourl = filePath
    formRef.value?.validate('halfbodyphotourl')
}

// 表单验证规则
const formRules: { [key: string]: FieldRule[] } = {
    username: [{
        required: true,
        message: t("user.authentication.pleaseentertheusername"),
    }],
    cardtype: [{
        message: t('user.authentication.pleaseselectthecardtype'),
        validator: () => formData.cardtype !== undefined
    }],
    cardnum: [{
        message: t("user.authentication.pleaseenterthecardnum"),
        validator: (val) => {
            // 任务 #7009
            const enumItem = cerTypePersonList.find((e) => e.enumitemname === formData.cardtype)
            if (enumItem && new RegExp(enumItem.param1).test(val)) {
                return true
            }
            return t('regex.cardno')
        }
    }],
    cardbackphotourl: [{
        message: t("user.authentication.pleaseuploadthecardbackphoto"),
        validator: () => !!formData.cardbackphotourl
    }],
    cardfrontphotourl: [{
        message: t("user.authentication.pleaseuploadthecardfrontphoto"),
        validator: () => !!formData.cardfrontphotourl
    }]
}

const onSubmit = () => {
    fullloading((hideLoading) => {
        formSubmit().then((res) => {
            /// 失败
            if (res.code.toString() === '0') {
                userStore.getUserData().finally(() => {
                    hideLoading()
                    dialog(t("user.authentication.opensuccess")).then(() => {
                        router.back()
                    })
                })
            } else {
                showFailToast(res.message)
            }
        }).catch((err) => {
            formData.cardnum = ''
            showFailToast(err)
        })
    })
}
</script>

<style lang="less">
@import './index.less';
</style>