<template>
    <div class="page page-shadow">
        <van-form ref="formRef" class="kyc-form" v-if="isShow && countryOptions.length > 0">
            <remit-input
                v-model:value="infoForm.lastName"
                fkey="lastName"
                :required="true"
                :label="t('improve-info.p8')"
                :rules="rules['lastName']"
                @change="handleChange"
            />
            <remit-input
                v-model:value="infoForm.firstName"
                fkey="firstName"
                :required="true"
                :label="t('improve-info.p9')"
                :rules="rules['firstName']"
                @change="handleChange"
            />

            <remit-input
                v-model:value="infoForm.email"
                fkey="email"
                :label="t('improve-info.p7')"
                :required="true"
                :rules="rules['email']"
                @change="handleChange"
            />
            <div class="f">
                <remit-input
                    class="l"
                    v-model:value="infoForm.areaCode"
                    v-if="phoneCodes.length > 0"
                    fkey="areaCode"
                    :required="true"
                    type="select"
                    :show-search="true"
                    :columns="phoneCodes"
                    :label="t('improve-info.p6')"
                    :rules="rules['areaCode']"
                    @change="handleChange"
                />
                <remit-input class="r" v-model:value="infoForm.mobile" fkey="mobile" label=" " :rules="rules['mobile']" @change="handleChange" />
            </div>
            <remit-input
                v-model:value="infoForm.sex"
                fkey="sex"
                type="select"
                :columns="sexOptions"
                :label="t('improve-info.p13')"
                @change="handleChange"
            />
            <remit-input v-model:value="infoForm.birthday" type="date" fkey="birthday" :label="t('improve-info.p10')" @change="handleChange" />
            <remit-input
                v-model:value="infoForm.nationality"
                fkey="nationality"
                type="select"
                :show-search="true"
                :columns="countryOptions"
                :label="t('improve-info.p17')"
                @change="handleChange"
            />
            <remit-input
                v-model:value="infoForm.town"
                fkey="town"
                :show-search="true"
                type="select"
                :columns="cityOptions"
                :label="t('improve-info.p19')"
                @change="handleChange"
            />
            <remit-input
                v-model:value="infoForm.address"
                fkey="address"
                :label="t('improve-info.p21')"
                :required="true"
                :rules="rules['address']"
                @change="handleChange"
            />
            <remit-input v-model:value="infoForm.postCode" fkey="postCode" :label="t('improve-info.p22')" @change="handleChange" />
            <remit-input
                v-model:value="infoForm.idType"
                fkey="idType"
                type="select"
                :columns="idTypeOptions"
                :label="t('improve-info.p23')"
                @change="handleChange"
            />
            <remit-input v-model:value="infoForm.idNo" fkey="idNo" :label="t('improve-info.p27')" @change="handleChange" />
            <remit-input
                v-model:value="infoForm.idNoExpiryDate"
                type="date"
                fkey="idNoExpiryDate"
                :label="t('improve-info.p28')"
                @change="handleChange"
            />
            <remit-input
                v-model:value="infoForm.idPicture"
                type="upload"
                fkey="idPicture"
                :label="t('improve-info.p29')"
                :isUploadD="true"
                accept="image/png, image/jpeg, image/jpg"
                @change="handleChange"
            >
                <div class="cwg-upload">
                    <van-icon name="back-top" />
                    <p class="name">{{ t('improve-info.p28_1') }}{{ t('improve-info.p29') }}</p>
                    <p class="back">{{ t('improve-info.p28_2') }}</p>
                </div>
            </remit-input>
            <remit-input
                v-model:value="infoForm.facePicture"
                type="upload"
                fkey="facePicture"
                :label="t('improve-info.p30')"
                :isUploadD="true"
                accept="image/png, image/jpeg, image/jpg"
                @change="handleChange"
            >
                <div class="cwg-upload">
                    <van-icon name="back-top" />
                    <p class="name">{{ t('improve-info.p28_1') }}{{ t('improve-info.p30') }}</p>
                    <p class="back">{{ t('improve-info.p28_2') }}</p>
                </div>
            </remit-input>
            <div class="fixed-btn">
                <div class="cwg-button">
                    <van-button type="primary" block @click="infoSubmit">{{ t('improve-info.p33') }}</van-button>
                </div>
            </div>
        </van-form>
    </div>
</template>

<script setup lang="ts">
import { pinyin } from 'pinyin-pro'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { showToast } from 'vant'
import { ucardApi } from '@/api/ucard'
import { userApi } from '@/api/user'
import useUserStore from '@/stores/use-user-store'
const userStore = useUserStore()
const userInfo = computed(() => userStore.userInfo)
const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const formRef = ref()
const { type,cardTypeId  } = route.query as { type: string,cardTypeId:string }
const sexOptions = ref([
    { text: t('improve-info.p15'), value: '1' },
    { text: t('improve-info.p16'), value: '2' },
])
const idTypeOptions = ref([
    { text: t('improve-info.p25'), value: 'EUROPEAN_ID' },
    { text: t('improve-info.p26'), value: 'PASSPORT' },
])
// 表单验证规则
const rules = {
    email: [{ required: true, message: t('improve-info.p3_3_5') }],
    lastName: [{ required: true, message: t('improve-info.p3_1') }],
    firstName: [{ required: true, message: t('improve-info.p3_2') }],
    address: [{ required: true, message: t('improve-info.p3_4') }],
    mobile: [{ required: true, message: t('improve-info.p3_3') }],
    areaCode: [{ required: true, message: t('improve-info.p5') }],
}
const infoForm = ref({
    // payerType: 'INDIVIDUAL',
    // payerLastName: 'zhang',
    // payerFirstName: 'tom',
    // payerIdNo: 'ES125664',
    // payerIdNoType: 'PASSPORT',
    // payerIdCountry: 'SG',
    // payerBirthday: '1990-10-10',
    // payerNationalityCountry: 'SG',
    // payerMobile: '+65012345678',
    // payerCountryCode: 'SG',
    // payerCityCode: 'SG_1',
    // payerAddress: '21 Tampines Ave 1, Singapore 529757',
    // payerPostCode: '999002',
    // payerOccupation: 'worker',

    areaCode: undefined,
    country: undefined,
    mobile: undefined,
    idNo: undefined,
    sex: undefined,
    birthday: undefined,
    nationality: undefined,
    town: undefined,
    postCode: undefined,
    idType: undefined,
    idNoExpiryDate: undefined,
    idPicture: undefined,
    facePicture: undefined,
    email: undefined,
    lastName: undefined,
    firstName: undefined,
    address: undefined,
    cId: undefined,
    cardTypeId: undefined,
})
const formData = ref<typeof infoForm.value>({} as any)
const formDatas = ref<typeof infoForm.value>({} as any)
const isShow = ref(false)

// 国家选项
const countryOptions = ref<Array<{ text: string; value: string }>>([])
const cityOptions = ref<Array<{ text: string; value: string }>>([])
const phoneCodes = ref([])
// 获取国家列表
const getCountryListForSelect = async () => {
    try {
        const res = await ucardApi.ucardCountryCity({})
        if (res.code === 200 || res.code === 0) {
            countryOptions.value = res.data.map((item: any) => ({
                text: lang.value === 'cn' ? item.cnName : item.enName,
                value: item.code,
            }))
        }
    } catch (error) {
        countryOptions.value = []
    }
}
// 获取城市列表
const getCityListForSelect = async (countryCode: string) => {
    try {
        const res = await ucardApi.ucardCountryCity({ code: countryCode })
        if (res.code === 200 || res.code === 0) {
            const cityList = res.data.map((item: any) => ({
                text: lang.value === 'cn' ? item.cnName : item.enName,
                value: item.code,
            }))
            cityOptions.value = cityList
        }
    } catch (error) {
        cityOptions.value = []
    }
}
const getCountry = async () => {
    try {
        const res = await ucardApi.countryGet()
        phoneCodes.value = res.data.map((item: { callingCode: string; name: string; enName: string }) => ({
            text: lang.value === 'cn' ? item.name + ' + ' + item.callingCode : item.enName + ' + ' + item.callingCode,
            value: item.callingCode,
        }))
    } catch (error) {
        showToast(t('common.error'))
    }
}
const infoSubmit = async () => {
    try {
        const requiredFields = ['email', 'lastName', 'firstName', 'address', 'mobile', 'areaCode'] as const
        await formRef.value?.validate(requiredFields)
    } catch (error) {
        if (Array.isArray(error) && error.length > 0) {
            showToast(error[0].message)
        } else {
            showToast(t('improve-info.errer'))
        }
        return
    }

    let res
    if (formData.value.uniqueId) {
        res = await ucardApi.merchantUpdate(formData.value as any)
        if (res.code === 200) {
            switch (type) {
                case '1':
                    showToast(t('improve-info.kycSuccess'))
                    router.push('/mine')
                    break
                case '3':
                kycSubmit()
                    break
                default:
                    break
            }
        }
    } else {
        res = await ucardApi.merchantRegister(formData.value as any)
        if (res.code === 200) {
            showToast(t('improve-info.kycSuccess'))
            userInfo.value.customInfo.uniqueId = res.data
            userStore.saveUserInfo(userInfo.value)
            router.push('/')
        }
    }
}
const handleChange = (value: any) => {
    formData.value = { ...formData.value, [value.key]: value.value }
    if (value.key === 'nationality') {
        formData.value = { ...formData.value, country: value.value }
        if(userInfo.value?.customInfo.nationality == value.value) return
        getCityListForSelect(value.value)
        infoForm.value.town = ''
    }
}
const containsChinese = (str: string) => /[\u4e00-\u9fa5]/.test(str)
const convertToPinyin = (value: string) => (containsChinese(value) ? pinyin(value, { toneType: 'none', type: 'capitalize' }) : value)
const getInfoForm = () => {
    const customInfo = userInfo.value?.customInfo || {}
    const fields = [
        'areaCode',
        'mobile',
        'idNo',
        'sex',
        'birthday',
        'nationality',
        'town',
        'postCode',
        'idType',
        'idNoExpiryDate',
        'idPicture',
        'facePicture',
        'email',
        'lastName',
        'firstName',
        'address',
        'cId',
        'uniqueId',
    ]

    const data: Record<string, any> = {}
    for (const key of fields) {
        data[key] = customInfo[key] ?? undefined
    }
    if (customInfo.uniqueId) {
        for (const key of fields) {
            data[key] = formDatas.value[key] ?? undefined
        }
    }
    data.lastName = convertToPinyin(data.lastName)
    data.firstName = convertToPinyin(data.firstName)
    infoForm.value = { ...data }
    formData.value = { ...formData.value, ...data, cardTypeId }
}
const getUserInfo = async () => {
    if (!userToken.value) {
        showToast('请先登录')
        return
    }
    try {
        const res = await userApi.getUserSingle()
        if (res.code === 200 && res.data.uniqueId) {
            formDatas.value = res.data
            getInfoForm()
        }
    } catch (error: any) { }
}

const kycSubmit = async () => {
    const {uniqueId,cardTypeId} = formData.value
    const res = await ucardApi.kycSubmit({uniqueId,cardTypeId})
    if (res.code === 200) {
        showToast(t('kyc.kycSuccess'))
        router.push('/cards')
    }
}
onMounted(async () => {
    if (type == '1' || type == '3') {
        getUserInfo()
    } else {
        getInfoForm()
    }
    isShow.value = false

    await getCountry()
    await getCountryListForSelect()
    if (infoForm.value.nationality) {
        await getCityListForSelect(infoForm.value.nationality)
        isShow.value = true
    } else {
        isShow.value = true
    }
})
</script>

<style scoped lang="scss">
.f {
    display: flex;
    align-items: flex-end;
    gap: 12px;

    .l {
        flex: 1;
    }

    .r {
        width: 273px;
    }
}

:deep(.van-uploader) {
    width: 100%;

    .van-uploader__wrapper {
        width: 100%;
        display: block;
    }
}

::v-deep(.van-uploader__preview) {
    width: 100% !important;
    height: 160px !important;
    border: 1px dashed #beb6b6;
    border-radius: 24px;
    overflow: hidden;

    .van-uploader__preview-image {
        width: 100%;
        height: 100%;

        .van-image__img {
            object-fit: contain;
        }
    }

    .van-uploader__preview-delete {
        position: absolute;
        top: 0;
        right: 0;
        width: 30px;
        height: 30px;
        border-radius: 0 24px 0 0;

        i {
            text-align: center;
            line-height: 30px;
            font-size: 30px;
        }
    }
}
</style>
