<!-- 实名认证 -->
<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 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" />
                    </template>
                </Field>
                <Field v-model="formData.cardnum" name="cardnum" :label="$t('user.authentication.cardnum')"
                    :placeholder="$t('user.authentication.pleaseenterthecardnum')" :rules="formRules.cardnum" />
                <Field v-if="formData.mobilephone != ''" name="mobilephone" v-model="formData.mobilephone"
                    :label="$t('user.register.mobile')" readonly />
                <Field v-else v-model="formData.mobilephone" type="digit" name="mobilephone"
                    :placeholder="$t('user.register.tips1')" :rules="formRules.mobilephone">
                    <template #label>
                        <span>{{ $t('user.register.mobile') }}</span>
                        <span style="margin-left: 10px;" @click="show = true">{{ countryCode }}</span>
                        <Popup v-model:show="show" position="bottom" teleport="body" round>
                            <Picker :columns="datalist" @cancel="onCancel" @confirm="onConfirm"
                                :confirm-button-text="$t('operation.confirm')"
                                :cancel-button-text="$t('operation.cancel')">
                                <template #option="{ text, index }">
                                    <slot name="option" :row="datalist[index]" :index="index">
                                        {{ text }}
                                    </slot>
                                </template>
                            </Picker>
                        </Popup>
                    </template>
                </Field>
                <Field name="bankid" :label="$t('banksign.OpenBankAccId')" :rules="formRules.bankid" is-link>
                    <template #input>
                        <app-select v-model="formData.bankid" :placeholder="$t('banksign.Pleaseselectyourbank')"
                            :options="banklist" :optionProps="{ label: 'bankname', value: 'bankid' }" />
                    </template>
                </Field>
                <Field :label="$t('banksign.bankno')" v-model="formData.bankaccount" name="bankaccount"
                    :placeholder="$t('banksign.Pleaseenterbankno')" :rules="formRules.bankaccount" maxlength="30" />
                <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 === '1'"
                    :label="$t('user.authentication.cardbackphoto')" :rules="formRules.cardbackphotourl">
                    <template #input>
                        <app-uploader @success="f_afterRead" />
                    </template>
                </Field>
                <Field name="halfbodyphotourl" v-if="showHalfBodyPhoto === '1'" :label="halfBodyPhotoTitle"
                    :rules="formRules.halfbodyphotourl">
                    <template #input>
                        <app-uploader @success="h_afterRead" />
                    </template>
                </Field>
                <Field v-if="modifyremark != ''" v-model="modifyremark" readonly name="modifyremark"
                    :label="$t('user.authentication.modifyremark')" />
            </CellGroup>
        </Form>
        <!-- <img v-if="oem != 'tss'" src="../../../assets/images/certification.png" /> -->
        <template #footer>
            <div class="g-form__footer inset">
                <Button type="danger" @click="formRef?.submit" round block>{{ $t('user.authentication.submit')
                }}</Button>
            </div>
        </template>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, computed, ref, onMounted } from 'vue'
import { CellGroup, Button, Field, Form, FormInstance, showFailToast, FieldRule, Popup, Picker, PickerConfirmEventParams } 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 { getIdCardAge } from '@/filters'
import { validateRules } from '@/constants/regex'
import { useRequest } from '@/hooks/request'
import { getWskhOpenAccountConfigs } from '@/services/api/account'
import { useQueryCusBankSignBank } from '@/business/bank'
import { getCountryCodeList } from '@/constants/unit'
import { i18n, useUserStore } from '@/stores'
import AppUploader from '@mobile/components/base/uploader/index.vue'
import AppSelect from '@mobile/components/base/select/index.vue'
import service from '@/services'

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

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

// 是否弹出选择器
const show = shallowRef(false)
const datalist = computed(() => {
    return getCountryCodeList().map(e => {
        return { text: e.value, value: e.value }
    })
})
const countryCode = ref(datalist.value[0]?.value.toString() ?? '')

const showHalfBodyPhoto = shallowRef('0')
const showCardBackPhoto = shallowRef('0')
const halfBodyPhotoTitle = shallowRef(t('user.authentication.halfbodyphoto'))

const oem = service.getConfig('oem')

const { banklist } = useQueryCusBankSignBank()

const onCancel = () => {
    show.value = false
}

const onConfirm = ({ selectedValues: [value] }: PickerConfirmEventParams) => {
    show.value = false
    countryCode.value = value.toString()
}

// 获取网上开户配置
useRequest(getWskhOpenAccountConfigs, {
    params: {
        configs: '53,54,78'
    },
    onSuccess: (res) => {
        /// 是否显示半身照和 证件背面照
        showCardBackPhoto.value = res.data.filter(e => e.configid === 53)[0].configvalue ?? '0'
        showHalfBodyPhoto.value = res.data.filter(e => e.configid === 54)[0].configvalue ?? '0'
        halfBodyPhotoTitle.value = res.data.filter(e => e.configid === 78)[0].configvalue ?? t('user.authentication.halfbodyphoto')
    }
})

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

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

const h_afterRead = (filePath: string) => {
    formData.halfbodyphotourl = filePath
}

// 表单验证规则
const formRules: { [key: string]: FieldRule[] } = {
    username: [{
        required: true,
        message: t("user.authentication.pleaseentertheusername"),
    }],
    cardnum: [{
        required: true,
        message: t("user.authentication.pleaseenterthecardnum"),
        validator: (val) => {
            // if (getIdCardAge(val)) {
            //     return t("user.authentication.openfailure")
            // }

            // 待优化
            const enumItem = cerTypePersonList.find((e) => e.enumitemname === formData.cardtype)
            if (enumItem) {
                return new RegExp(enumItem.param1).test(val) || t('regex.cardno')
            }
            return t('regex.cardno')
        }
    }],
    cardbackphotourl: [{
        required: true,
        message: t("user.authentication.pleaseuploadthecardbackphoto"),
    }],
    cardfrontphotourl: [{
        required: true,
        message: t("user.authentication.pleaseuploadthecardfrontphoto"),
    }],
    bankid: [{
        message: t('banksign.Pleaseselectyourbank'),
        validator: () => {
            return !!formData.bankid
        }
    }],
    bankaccount: [{
        required: true,
        message: t('banksign.Pleaseenterbankno'),
    }],
}

const onSubmit = () => {
    fullloading((hideLoading) => {
        // 手机号+区号
        if (userStore.userInfo.mobile2 === '') {
            formData.mobilephone = countryCode.value + formData.mobilephone
        }
        formSubmit().then((res) => {
            /// 失败
            if (res.code.toString() != '0') {
                showFailToast(res.message)
            } else {
                hideLoading()
                dialog(t("user.authentication.opensuccess")).then(() => {
                    router.back()
                })
            }
        }).catch((err) => {
            formData.cardnum = ''
            showFailToast(err)
        })
    })
}

onMounted(() => {
    formData.mobilephone = userStore.userInfo.mobile2
})
</script>