<template>
    <div class="page">
        <div class="kyc-form" v-if="isShow">
            <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"
            />
            <remit-input
                v-model:value="infoForm.areaCode"
                fkey="areaCode"
                :required="true"
                type="select"
                :show-search="true"
                :columns="phoneCodes"
                :label="t('improve-info.p4')"
                :rules="rules['areaCode']"
                @change="handleChange"
            />
            <remit-input
                v-model:value="infoForm.mobile"
                fkey="mobile"
                :label="t('improve-info.p6')"
                :required="true"
                :rules="rules['mobile']"
                @change="handleChange"
            />
            <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')" @change="handleChange" />
            <remit-input
                v-model:value="infoForm.facePicture"
                type="upload"
                fkey="facePicture"
                :label="t('improve-info.p30')"
                @change="handleChange"
            />
            <!-- <div class="form-item phone-input">
                <div :class="{ 'phone-code': true, 'phone-code-active': form.phoneCode }">
                    <van-field
                        is-link
                        readonly
                        @click="showPicker = true"
                        v-model="form.phoneCode"
                        :placeholder="t('improve-info.phoneCode')"
                        :rules="[{ required: true, message: t('improve-info.phoneCode') }]"
                        autocomplete="off"
                    />
                    <van-popup v-model:show="showPicker" destroy-on-close round position="bottom">
                        <van-picker
                            v-model="form.phoneCode1"
                            :visible-option-num="8"
                            show-toolbar
                            :title="t('improve-info.country')"
                            :columns="[phoneCodes]"
                            :cancel-button-text="t('common.cancel')"
                            :confirm-button-text="t('common.confirm')"
                            @cancel="showPicker = false"
                            @confirm="onConfirm"
                        />
                    </van-popup>
                </div>
                <div class="phone-divider"></div>
                <div class="phone-number">
                    <van-field
                        v-model="form.phone"
                        :placeholder="t('improve-info.phone')"
                        :rules="[{ required: true, message: t('improve-info.phone') }]"
                        autocomplete="off"
                    />
                </div>
            </div> -->

            <div class="kyc-button">
                <van-button type="primary" block @click="kycSubmit">{{ t('improve-info.p33') }}</van-button>
            </div>
        </div>
    </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 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') }],
    lastName: [{ required: true, message: t('improve-info.p3') }],
    firstName: [{ required: true, message: t('improve-info.p3') }],
    address: [{ required: true, message: t('improve-info.p3') }],
    mobile: [{ required: true, message: t('improve-info.p3') }],
    areaCode: [{ required: true, message: t('improve-info.p5') }],
}
const infoForm = ref({
    areaCode: 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,
})
const formData = 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
            isShow.value = true
        }
    } 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(error || String(error))
    }
}
const kycSubmit = async () => {
    const requiredFields = ['email', 'lastName', 'firstName', 'address', 'mobile', 'areaCode'] as const
    const missingFields = requiredFields.filter((field) => !formData.value[field])
    if (missingFields.length > 0) {
        showToast(t('eur-remit.requiredFieldsMissing'))
        return
    }
    let res

    if (formData.value.uniqueId) {
        res = await ucardApi.merchantUpdate(formData.value as any)
        if (res.code === 200) {
            showToast(t('improve-info.kycSuccess'))
        }
    } else {
        res = await ucardApi.merchantRegister(formData.value as any)
        if (res.code === 200) {
            showToast(t('improve-info.kycSuccess'))
            userInfo.value.customInfo.uniqueId = res.data
            console.log(userInfo.value)
            userStore.saveUserInfo(userInfo.value)
            router.push('/')
        }
    }
}
const handleChange = (value: any) => {
    formData.value = { ...formData.value, [value.key]: value.value }
    if (value.key === 'nationality') {
        getCityListForSelect(value.value)
        formData.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
    }
    data.lastName = convertToPinyin(data.lastName)
    data.firstName = convertToPinyin(data.firstName)
    infoForm.value = { ...data }
    formData.value = { ...formData.value, ...data }
}
const getUserInfo = async () => {
    if (!userToken.value) {
        showToast('请先登录')
        return
    }
    try {
        const res = await userApi.getUserInfo()

        if (res.code === 200) {
            if (res.data.customInfo.uniqueId) {
                router.push('/')
            } else {
                router.push('/improve/info')
            }
        } else {
            showToast(res.msg || '登录失败')
        }
    } catch (error: any) {
        showToast(error.message || '登录失败')
    } finally {
    }
}
onMounted(() => {
    getInfoForm()
    isShow.value = false
    getCountryListForSelect()
    getCountry()
    if (infoForm.value.nationality) {
        getCityListForSelect(infoForm.value.nationality)
    } else {
        isShow.value = true
    }
})
</script>

<style scoped lang="scss">
.kyc-page {
    min-height: 100vh;
    background: linear-gradient(135deg, #232323 0%, #2a2a2a 100%);
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 32px 12px;
}
.kyc-header {
    width: 100%;
    text-align: center;
    margin-bottom: 24px;
    h2 {
        font-size: var(--font-size-18);
        color: var(--main-yellow);
        margin-bottom: 8px;
    }
    p {
        color: #bbb;
        font-size: var(--font-size-12);
        line-height: 1.5;
    }
}
.kyc-form {
    width: 100%;
    max-width: 350px;
    border-radius: 20px;
    padding: 28px 18px 18px 18px;
    display: flex;
    flex-direction: column;
    gap: 18px;
}

.form-item {
    margin-bottom: 0;
    ::v-deep {
        .van-field {
            background: #181818;
            border-radius: 12px;
            padding: 12px 16px;
            transition: all 0.3s ease;

            &:focus-within {
                background: #1f1f1f;
            }

            .van-field__label {
                color: #bbb;
                font-size: var(--font-size-14);
                width: 80px;
            }

            .van-field__control {
                color: #fff;
                font-size: var(--font-size-14);
                min-height: 20px;
                line-height: 20px;

                &::placeholder {
                    color: #666;
                    font-size: var(--font-size-14);
                }

                &::-webkit-input-placeholder {
                    color: #666;
                }

                &::-moz-placeholder {
                    color: #666;
                    opacity: 1;
                }
            }

            .van-field__right-icon {
                color: var(--main-yellow);
                margin-left: 8px;
            }

            .van-field__error-message {
                color: #ff4d4f;
                font-size: var(--font-size-12);
                margin-top: 4px;
            }
        }
    }
}
.kyc-button {
    margin-top: 18px;
    ::v-deep {
        .van-button {
            height: 44px;
            border-radius: 24px;
            background: var(--main-yellow);
            border: none;
            color: #232323;
            font-size: var(--font-size-16);
            font-weight: bold;

            &:active {
                opacity: 0.9;
            }
        }
    }
}
.apply-card-steps {
    width: 100%;
    max-width: 350px;
    margin-bottom: 32px;

    .steps-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 12px;
    }

    .step {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 8px;

        .step-circle {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background: var(--action-bg, #181818);
            border: 2px solid #444;
            color: #444;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: var(--font-size-16);
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .step-label {
            font-size: var(--font-size-14);
            color: #444;
            transition: all 0.3s ease;
        }

        &.active {
            .step-circle {
                background: var(--main-yellow);
                border-color: var(--main-yellow);
                color: #232323;
            }

            .step-label {
                color: var(--main-yellow);
            }
        }
    }

    .step-dash {
        flex: 1;
        height: 2px;
        margin: 0 8px;
        position: relative;
        top: -16px;
        transition: all 0.3s ease;
        background-image: linear-gradient(to right, #444 50%, transparent 50%);
        background-size: 8px 2px;
        background-repeat: repeat-x;

        &.active {
            background-image: linear-gradient(to right, var(--main-yellow) 50%, transparent 50%);
        }
    }
}

.phone-input {
    display: flex;
    align-items: center;
    background: #181818;
    border-radius: 12px;
    padding: 0 16px;
    height: 44px;
    transition: all 0.3s ease;

    &:focus-within {
        background: #1f1f1f;
    }

    .phone-code {
        width: 20%;
        ::v-deep .van-cell {
            &::after {
                border-bottom: 0;
            }
            .van-icon {
                font-size: var(--font-size-14);
                line-height: 20px;
            }
        }
        ::v-deep {
            .van-field {
                background: transparent;
                padding-left: 0;
                padding-right: 0;

                .van-field__control {
                    color: var(--white);
                    text-align: center;
                    padding: 0;
                }
            }
        }
    }
    .phone-code-active {
        ::v-deep .van-cell {
            .van-icon {
                color: var(--white);
            }
        }
    }

    .phone-divider {
        width: 1px;
        height: 20px;
        background: #333;
        margin: 0 12px;
        transition: all 0.3s ease;
    }

    .phone-number {
        flex: 1;
        ::v-deep {
            .van-field {
                background: transparent;
                padding-left: 10px;

                .van-field__control {
                    color: #fff;
                    text-align: left;
                    padding: 0;

                    &::placeholder {
                        color: #666;
                        text-align: left;
                    }
                }
            }
        }
    }
}

@keyframes slideDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

@keyframes fadeIn {
    from {
        opacity: 0;
    }
    to {
        opacity: 0.2;
    }
}

::v-deep {
    .van-picker {
        background: #181818;

        .van-picker__toolbar {
            background: #181818;
            border-bottom: 1px solid #333;
            height: 44px;
            padding: 0 16px;

            .van-picker__title {
                color: #fff;
                font-size: var(--font-size-16);
                font-weight: 500;
            }

            .van-picker__cancel,
            .van-picker__confirm {
                color: var(--main-yellow);
                font-size: var(--font-size-14);
                padding: 0 8px;
                height: 28px;
                line-height: 28px;
                border-radius: 14px;
                transition: all 0.3s ease;

                &:active {
                    opacity: 0.8;
                    background: rgba(255, 193, 7, 0.1);
                }
            }
        }

        .van-picker-column {
            color: #fff;

            .van-picker-column__item {
                color: #fff;
                font-size: var(--font-size-14);
                padding: 0 16px;
                height: 44px;
                line-height: 44px;
                transition: all 0.3s ease;

                &--selected {
                    color: var(--main-yellow);
                    font-weight: 500;
                    font-size: var(--font-size-16);
                }

                &:active {
                    background: rgba(255, 255, 255, 0.05);
                }
            }

            .van-picker-column__wrapper {
                &::after {
                    border-color: #333;
                }
            }
        }

        .van-picker__mask {
            background-image: linear-gradient(180deg, rgba(24, 24, 24, 0.9), rgba(24, 24, 24, 0.4)),
                linear-gradient(0deg, rgba(24, 24, 24, 0.9), rgba(24, 24, 24, 0.4));
        }

        .van-picker__indicator {
            height: 44px;
            background: rgba(255, 193, 7, 0.05);
            border-top: 1px solid rgba(255, 193, 7, 0.1);
            border-bottom: 1px solid rgba(255, 193, 7, 0.1);
        }
    }
}
</style>
