<template>
    <app-view class="g-form account-certification">
        <template #header>
            <app-navbar title="实名认证" />
        </template>
        <Form ref="formRef" class="g-form__container" @submit="onCheckCardNum" :loading="loading">
            <CellGroup inset>
                <Field v-model="formData.username" name="username" label="姓名" placeholder="请输入用户姓名" :rules="formRules.username"
                    :readonly="isReadonly" />
                <Field v-model="formData.mobile" name="mobile" readonly label="手机号码" />
                <Field name="idCardType" label="证件类型" :rules="formRules.cardtype" is-link>
                    <template #input>
                        <app-select v-model="formData.cardtype" placeholder="请选择证件类型"
                            :options="getCerTypePersonList()" :readonly="isReadonly" />
                    </template>
                </Field>
                <Field v-model="formData.cardnum" name="cardnum" label="证件号码" placeholder="请输入证件号码" :rules="formRules.cardnum"
                    :readonly="isReadonly" />
                <Field name="cardfrontphotourl" label="证件正面照片" :rules="formRules.cardfrontphotourl">
                    <template #input>
                        <Image fit="contain" :src="getFileUrl(formData.cardfrontphotourl)" width="100" height="100"
                            v-if="isReadonly" />
                        <app-uploader @success="f_afterRead" v-else />
                    </template>
                </Field>
                <Field name="cardbackphotourl" label="证件反面照片" :rules="formRules.cardbackphotourl">
                    <template #input>
                        <Image fit="contain" :src="getFileUrl(formData.cardbackphotourl)" width="100" height="100"
                            v-if="isReadonly" />
                        <app-uploader @success="b_afterRead" v-else />
                    </template>
                </Field>
            </CellGroup>
        </Form>
        <img src="../../../assets/images/certification.png" />
        <template #footer>
            <div class="g-form__footer inset">
                <Button type="danger" :loading="buttonLoading" @click="formRef?.submit" round block>提交实名认证</Button>
            </div>
        </template>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, onMounted } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, showFailToast, FieldRule, Image } from 'vant'
import { fullloading, dialog } from '@/utils/vant';
import { getFileUrl, getIdCardAge } from '@/filters';
import { getCerTypePersonList } from "@/constants/account";
import { useRequest } from '@/hooks/request'
import { queryTencentUsereSignRecords, requestCheckCardNum } from '@/services/api/account';
import { addAuthReq } from '@/business/user/account';
import { validateRules } from '@/constants/regex';
import { useUserStore } from '@/stores'
import AppSelect from '@mobile/components/base/select/index.vue'
import AppUploader from '@mobile/components/base/uploader/index.vue'
import { useNavigation } from '@mobile/router/navigation'
import { getUserId, getMemberUserId } from '@/services/methods/user'

const { router } = useNavigation()
const userStore = useUserStore()
const formRef = shallowRef<FormInstance>()
const { formData, formSubmit, loading } = addAuthReq()

const isReadonly = false//computed(() => userESignRecords.value.some((e) => e.recordstatus === 3))

/// 查询记录
const { loading: buttonLoading } = useRequest(queryTencentUsereSignRecords, {
    params: {
        userId: getUserId(),
        memberUserId: getMemberUserId()
    },
    onError: (err) => {
        showFailToast(err)
    }
})

const b_afterRead = (filePath: string) => {
    formData.cardbackphotourl = filePath
}

const f_afterRead = (filePath: string) => {
    formData.cardfrontphotourl = filePath
}

// 表单验证规则
const formRules: { [key in keyof Model.AddAuthReq]?: FieldRule[] } = {
    username: [{
        required: true,
        message: '请输入用户姓名',
    }],
    mobile: [{
        required: true,
        message: '请输入手机号码',
        validator: (val) => {
            if (validateRules.phone.validate(val)) {
                return true
            }
            return validateRules.phone.message
        }
    }],
    cardnum: [{
        required: true,
        message: '请输入证件号码',
        validator: (val) => {
            if (validateRules.cardno.validate(val)) {
                return true
            }
            if ((getIdCardAge(val) < 18) || (getIdCardAge(val) > 65)) {
                return '开户失败，您的年龄不符合开户要求'
            }
            return validateRules.cardno.message
        }
    }],
    cardbackphotourl: [{
        required: true,
        message: '请上传证件背面照片',
    }],
    cardfrontphotourl: [{
        required: true,
        message: '请上传证件正面照片',
    }],
}

const onCheckCardNum = () => {
    fullloading((hideLoading) => {
        requestCheckCardNum({
            data: {
                cardnum: formData.cardnum
            }
        }).then(() => {
            formSubmit().then(() => {
                hideLoading()
                dialog('提交请求成功，请耐心等待审核！').then(() => {
                    router.back()
                })
            }).catch((err) => {
                hideLoading(err, 'fail')
            })
        }).catch((err) => {
            hideLoading(err, 'fail')
        })
    })
}

onMounted(() => {
    formData.mobile = userStore.userInfo?.mobile2 ?? ''
})
</script>