<template>
    <uni-popup ref="popupRef" type="center" background-color="#fff">
        <view class="dialog-container">
            <view class="dialog-header">
                <text class="dialog-title" v-t="typeMap[form.type]"></text>
                <view class="dialog-close" @click="close">
                    <text>×</text>
                </view>
            </view>
            <uni-forms ref="formRef" :rules="rules" :model="form" labelWidth="200" label-position="top"
                class="crm-form">
                <uni-row class="form-row uni-row1">
                    <template v-if="form.type === 1">
                        <uni-col :xs="24">
                            <uni-forms-item>
                                <cwg-file-picker v-model="form.bankFront" :editable="editingId === form.id" :limit="1"
                                    uploadUrl="/custom/bank/upload" :baseUrl="updateUrl" :imageWidth="150"
                                    :imageHeight="150" uploadText="点击上传" replaceText="点击替换" noImageText="暂无图片"
                                    :showPreviewDelete="editingId === form.id"
                                    @update:modelValue="(val) => handleFileUpdate(val, form, 'bankFront')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankAccountName')">
                                <uni-easyinput :clearable="false" v-model="form.bankUname"
                                    :placeholder="locale == 'es' ? 'Introduzca el nombre de la red' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankName')">
                                <cwg-combox :clearable="false" :filterable="true" v-model:value="form.bankName"
                                    :options="bankOptions" :placeholder="t('placeholder.choose')"
                                    @change="onStateChange" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankAccount')">
                                <uni-easyinput :clearable="false" v-model="form.bankCardNum"
                                    :placeholder="locale == 'es' ? 'Introduzca la dirección de la billetera' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.AccountOpeningBranch')">
                                <uni-easyinput :clearable="false" v-model="form.bankBranchName"
                                    :placeholder="locale == 'es' ? 'Introduzca la dirección de la billetera' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                    </template>
                    <template v-if="form.type === 4">
                        <!-- 区块链名称 -->
                        <uni-col :xs="24">
                            <uni-forms-item prop="addressName" :label="t('blockchain.item3')">
                                <uni-easyinput :clearable="false" v-model="form.addressName"
                                    :placeholder="t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <!-- 钱包地址 -->
                        <uni-col :xs="24">
                            <uni-forms-item prop="address" :label="t('blockchain.item4')">
                                <uni-easyinput :clearable="false" v-model="form.address"
                                    :placeholder="t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                    </template>
                    <template v-if="form.type === 2">
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankAccountName')">
                                <uni-easyinput :clearable="false" v-model="form.bankUname" :disabled="true"
                                    :placeholder="locale == 'es' ? 'Introduzca el nombre de la red' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankAccount')">
                                <uni-easyinput :clearable="false" v-model="form.bankCardNum"
                                    :placeholder="locale == 'es' ? 'Introduzca la dirección de la billetera' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankName')">
                                <uni-easyinput :clearable="false" v-model="form.bankName"
                                    :placeholder="locale == 'es' ? 'Introduzca el nombre del banco' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankAddress')">
                                <uni-easyinput :clearable="false" v-model="form.bankAddr"
                                    :placeholder="locale == 'es' ? 'Introduzca la dirección del banco' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.SwiftBIC')">
                                <uni-easyinput :clearable="false" v-model="form.swiftCode"
                                    :placeholder="locale == 'es' ? 'Introduzca el SWIFT/BIC' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.BankCode')">
                                <uni-easyinput :clearable="false" v-model="form.bankCode"
                                    :placeholder="locale == 'es' ? 'Introduzca el código del banco' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item
                                :label="locale == 'es' ? 'Número de sucursal (opcional)' : 'Account Agency NO'">
                                <uni-easyinput :clearable="false" v-model="form.agencyNo"
                                    :placeholder="locale == 'es' ? 'Introduzca el número de sucursal' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                    </template>
                    <template v-if="form.type === 3">
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.CreditCardAccountName')">
                                <uni-easyinput :clearable="false" v-model="form.bankUname" :disabled="true"
                                    :placeholder="t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.CreditCardAccount')">
                                <uni-easyinput :clearable="false" v-model="form.bankCardNum"
                                    :placeholder="locale == 'es' ? 'Introduzca el número de tarjeta' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('PersonalManagement.Label.ExpirationYear')">
                                <uni-easyinput :clearable="false" v-model="form.expiryYearMonth"
                                    :placeholder="locale == 'es' ? 'Introduzca MM/AA' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('CVV')">
                                <uni-easyinput :clearable="false" v-model="form.cvv"
                                    :placeholder="locale == 'es' ? 'Introduzca el CVV' : t('placeholder.input')" />
                            </uni-forms-item>
                        </uni-col>
                    </template>
                    <uni-col :xs="24">
                        <uni-forms-item class="checkbox-item" prop="defaultBank">
                            <uni-data-checkbox v-model="form.defaultBank" multiple :localdata="hobbys" />
                        </uni-forms-item>
                    </uni-col>
                </uni-row>
            </uni-forms>
            <view class="dialog-footer">
                <view class="btn btn-cancel" @click="close">{{ t('Btn.Cancel') }}</view>
                <view class="btn btn-confirm" @click="submit">{{ t('Btn.Confirm') }}</view>
            </view>
        </view>
    </uni-popup>
</template>

<script setup lang="ts">
import { ref, nextTick, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Validators } from '@/utils/validators';
import { personalApi } from '@/service/personal';
const { t, locale } = useI18n();
const typeMap = {
    4: 'blockchain.item2',
    1: 'PersonalManagement.Title.ChinaUnionPayCard',
    2: 'PersonalManagement.Title.BankWireTransfer',
    3: 'PersonalManagement.Label.CreditCard'
}
interface AddBankForm {
    addressName: string;
    address: string;
    checkboxGroup: string[];
}
const hobbys = computed(() => {
  let value = [
    { value: 1, text: t('blockchain.item8') },
  ]
  switch (form.value.type){
      case 1:
        value = [
          { value: 1, text: t('PersonalManagement.Title.DefaultBank') },
        ]
      break;
      case 2:
        value = [
          { value: 1, text: t('PersonalManagement.Title.DefaultWire') },
        ]
      break;
      case 3:
        value = [
          { value: 1, text: t('PersonalManagement.Title.DefaultCredit') },
        ]
      break;
      case 4:
        value = [
          { value: 1, text: t('blockchain.item8') },
        ]
      break;
  }
  return value

});
const emit = defineEmits(["success"]);

const popupRef = ref<any>(null);
const formRef = ref<any>(null);

const form = ref<AddBankForm>({});

const rules = {
    addressName: [Validators.required(t('blockchain.item3') + t('common.cannotbeempty'))],
    address: [Validators.required(t('blockchain.item4') + t('common.cannotbeempty'))]
};

// 打开弹窗
const open = async (type: number) => {
    form.value = {}
    await nextTick();
    form.value.type = type;
    getBankList()
    popupRef.value?.open();
};

// 关闭弹窗
const close = () => {
    popupRef.value?.close();
    resetForm();
};

// 重置表单
const resetForm = () => {
    form.value = {};
    formRef.value?.clearValidate();
};

// 提交表单
const submit = async () => {
    try {
        // 校验表单
        const valid = await formRef.value?.validate();
        if (!valid) {
            return;
        }
        // 调用 API 添加钱包
        const submitData = {
            ...form.value,
            expiryYear: form.value?.expiryYearMonth ? form.value.expiryYearMonth.split("/")[0] : undefined,
            expiryMonth: form.value?.expiryYearMonth ? form.value.expiryYearMonth.split("/")[1] : undefined,
            defaultBank: form.value?.defaultBank && form.value?.defaultBank[0] ? 1 : 0,
        };
        let res = await personalApi.customBankAdd({
            bankUname: 'username',
            ...submitData,
        });
        if (res.code == 200) {
            uni.showToast({ title: t('Msg.Success'), icon: 'success' });
            emit("success", res.data);
        } else {
            uni.showToast({ title: res.msg || t('common.error'), icon: 'none' });
        }
        close();
    } catch (error: any) {
        console.log(error);
        uni.showToast({ title: error.message || error.msg || t('common.error'), icon: 'none' });
    }
};

const bankList = ref([])
const isZh = computed(() => ['cn', 'zh', 'zhHant'].includes(locale.value));
const getLangName = (item: any) => (isZh.value ? item.name : item.enName);
const createOptions = (list: any[], valueKey = 'code') => {
    return list.map((item) => ({
        text: getLangName(item),
        value: getLangName(item)
    }));
};

const bankOptions = computed(() => createOptions(bankList.value, 'name'));
// 获取银行列表
const getBankList = async () => {
    const res = await personalApi.BankList({})
    if (res.code === 200) {
        bankList.value = res.data
    }
}
// 文件更新处理
const handleFileUpdate = (newValue, item, field) => {
    item[field] = newValue
}
// 暴露方法
defineExpose({
    open,
    close
});
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.dialog-container {
    width: 80vw;
    max-width: px2rpx(800);
    max-height: 85vh;
    padding: px2rpx(24);
    overflow: hidden;
    border-radius: px2rpx(12);

    .dialog-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: px2rpx(24);
        padding-bottom: px2rpx(16);
        border-bottom: 1px solid #f3f4f6;

        .dialog-title {
            font-size: px2rpx(18);
            font-weight: 600;
            color: #1f2937;
        }

        .dialog-close {
            width: px2rpx(32);
            height: px2rpx(32);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: px2rpx(28);
            color: #9ca3af;
            cursor: pointer;
            transition: all 0.3s;

            &:hover {
                color: #1f2937;
            }
        }
    }

    .dialog-footer {
        display: flex;
        gap: px2rpx(12);
        justify-content: flex-end;
        padding-top: px2rpx(16);
        border-top: 1px solid #f3f4f6;

        .btn {
            min-width: px2rpx(120);
            padding: px2rpx(12) px2rpx(24);
            border-radius: px2rpx(6);
            font-size: px2rpx(14);
            font-weight: 600;
            border: none;
            cursor: pointer;
            text-align: center;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;

            &.btn-cancel {
                background: #f3f4f6;
                color: #6b7280;

                &:hover {
                    background: #e5e7eb;
                }

                &:active {
                    background: #d1d5db;
                }
            }

            &.btn-confirm {
                background: #ea2027;
                color: #fff;

                &:hover {
                    background: #d11920;
                }

                &:active {
                    background: #c01819;
                }
            }
        }
    }

    .crm-form {
        overflow-y: auto;
        max-height: 70vh;
    }
}
</style>
