<template>
    <view class="user-form crm-form">
        <uni-row class="demo-uni-row uni-row1">
            <uni-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                <view class="bank-menu">
                    <view v-for="item in bankTypes" :key="item.key" class="bank-menu-item"
                        :class="{ active: selectedBankType === item.key }" @click="selectedBankType = item.key">
                        <image class="bank-icon" :src="item.icon" mode="widthFix" />
                        <text>{{ item.label }}</text>
                    </view>
                </view>
            </uni-col>
            <uni-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                <view class="bank-content" v-if="selectedBankType === 'crypto'">
                    <view class="bank-info" v-for="(item, index) in cryptoWallets" :key="item.id">
                        <view class="card-header">
                            <view class="bank-header">
                                <uni-row style="width: 100%;">
                                    <uni-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
                                        <view class="bank-title">
                                            <cwg-icon v-if="item.defaultBank" name="crm-star" color="#ea2027" />
                                            <text>{{ currentBankType?.label }} {{ index + 1 }} </text>
                                            <text v-if="item.defaultBank" v-t="'PersonalManagement.Title.Default'" />
                                        </view>
                                    </uni-col>
                                    <uni-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
                                        <view class="bank-actions">
                                            <view class="action-btn bg-secondary" v-if="item.authStatus == 0"
                                                type="primary" v-t="'State.ToCertified'"
                                                @click="doReady(item.id, item)" />
                                            <view class="action-btn bg-secondary" v-if="item.authStatus == 0"
                                                type="primary" @click="openCardDialog(item.id, item)"
                                                v-t="'PersonalManagement.CardVerify.Title'" />
                                            <view class="action-btn bg-secondary"
                                                v-if="!editingId && item.authStatus !== 1" @tap="startEdit(item)"
                                                v-t="'Btn.Editor'" />
                                            <template v-if="editingId === item.id">
                                                <view class="action-btn bg-secondary" @tap="saveBank(item)"
                                                    v-t="'Btn.Save'" />
                                                <view class="action-btn bg-secondary" @tap="cancelEdit()"
                                                    v-t="'Btn.Cancel'" />
                                            </template>
                                            <view class="action-btn delete" @tap="confirmDelete(item)"
                                                v-t="'Btn.Delete'" />
                                        </view>
                                    </uni-col>
                                </uni-row>
                            </view>
                        </view>
                        <uni-forms :model="item" labelWidth="200" label-position="top">
                            <uni-row class="demo-uni-row">
                                <uni-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                                    <uni-forms-item :label="t('blockchain.item3')">
                                        <uni-easyinput :clearable="false" v-model="item.addressName"
                                            :disabled="editingId !== item.id"
                                            :placeholder="locale == 'es' ? 'Introduzca el nombre de la red' : t('placeholder.input')" />
                                    </uni-forms-item>
                                </uni-col>
                                <uni-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                                    <uni-forms-item :label="t('blockchain.item4')">
                                        <uni-easyinput :clearable="false" v-model="item.address"
                                            :disabled="editingId !== item.id"
                                            :placeholder="locale == 'es' ? 'Introduzca la dirección de la billetera' : t('placeholder.input')" />
                                    </uni-forms-item>
                                </uni-col>
                                <uni-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"
                                    v-if="item.cardFiles && item.cardFiles.length">
                                    <uni-forms-item :label="t('PersonalManagement.Label.CertificationPhoto')">
                                        <view class="photo-upload">
                                            <view v-for="(file, idx) in item.cardFiles" :key="idx" class="photo-item">
                                                <image class="photo-preview" :src="updateUrl + file.path"
                                                    mode="aspectFill" />
                                            </view>
                                        </view>
                                    </uni-forms-item>
                                </uni-col>
                            </uni-row>
                        </uni-forms>
                    </view>
                    <view class="add-wallet-btn" @click="openAddBankCard" v-if="cryptoWallets.length < 2">
                        <text>+</text>
                        <text>添加加密货币钱包</text>
                    </view>
                </view>
                <view class="bank-content" v-if="selectedBankType === 'unionpay'">
                    <view class="bank-info" v-for="item in unionpayCards" :key="item.id">
                    </view>
                    <view class="add-wallet-btn" @click="openAddBankCard">
                        <text>+</text>
                        <text>{{ t('ImproveImmediately.Label.AddCryptoWallet') }}</text>
                    </view>
                </view>
            </uni-col>
        </uni-row>
    </view>
    <!-- 删除确认弹窗 -->
    <uni-popup ref="deletePopup" type="dialog">
        <uni-popup-dialog :title="t('Msg.SystemPrompt')" :content="t('Msg.Delete')" @confirm="deleteBank"
            @close="closeDeletePopup" :cancelText="t('Btn.Cancel')" :confirmText="t('Btn.Confirm')" />
    </uni-popup>
    <!-- 新增银行弹窗 -->
    <cwg-add-bank-dialog ref="addBankDialogRef" @success="addSuccess" />
    <!-- kyc认证弹窗 -->
    <kyc-dialog ref="kycDialogRef" />
    <!-- 证件认证弹窗 -->
    <card-dialog ref="cardDialogRef" />
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { personalApi } from '@/service/personal';
import KycDialog from './KycAuthDialog.vue';
import CardDialog from './CardAuthDialog.vue';
import config from '@/config'
import { BankType, AuthStatus, ApproveStatus } from './bank'
const { t } = useI18n();
interface BankListType {
    key: string;
    label: string;
    icon: string;
}

interface BankInfo {
    id?: string;
    type: number;
    defaultBank: boolean;
    approveStatus?: number;
    authStatus?: number;
    blockchainName: string;
    walletAddress: string;
    photos?: string[];
    expiryYearMonth?: string;
    expiryYear?: string;
    expiryMonth?: string;
    [key: string]: any;
}
const selectedBankType = ref<string>('crypto');
const bankTypes = computed<BankListType[]>(() => [
    { key: 'crypto', label: t('blockchain.item2'), icon: '/static/images/info/bank-info_1.png' },
    { key: 'unionpay', label: t('PersonalManagement.Title.ChinaUnionPayCard'), icon: '/static/images/info/bank-info_2.png' },
    { key: 'bank', label: t('PersonalManagement.Title.BankWireTransfer'), icon: '/static/images/info/bank-info_3.png' },
    { key: 'credit', label: t('PersonalManagement.Label.CreditCard'), icon: '/static/images/info/bank-info_4.png' }
]);
const currentBankType = computed(() => bankTypes.value.find((item: BankListType) => item.key === selectedBankType.value));

// 状态
const updateUrl = config.Host05
const editingId = ref(null)
const bankOptions = ref([])

// 银行数据
const bankData = ref({
    [BankType.CRYPTO]: [],
    [BankType.UNIONPAY]: [],
    [BankType.WIRE_TRANSFER]: [],
    [BankType.CREDIT_CARD]: []
})

// 计算属性 - 各类型银行列表
const cryptoWallets = computed(() => bankData.value[BankType.CRYPTO] || [])
const unionpayCards = computed(() => bankData.value[BankType.UNIONPAY] || [])
const wireTransfers = computed(() => bankData.value[BankType.WIRE_TRANSFER] || [])
const creditCards = computed(() => bankData.value[BankType.CREDIT_CARD] || [])
console.log(unionpayCards, bankData.value, 231232);



// 弹出层ref
const deletePopup = ref(null)
const deleteTarget = ref(null)


// 开始编辑
const startEdit = (item) => {
    editingId.value = item.id
}

// 取消编辑
const cancelEdit = () => {
    editingId.value = null
    getBankInfo() // 重新加载数据
}

// 保存银行信息
const saveBank = async (item) => {

    if (item.approveStatus == 1) {
        uni.showToast({
            title: "加密钱包认证审核中",
            icon: "none"
        });
        return;
    }
    try {
        const params = { ...item }
        params.defaultBank = params.defaultBank ? 1 : 0

        if (params.type === BankType.CREDIT_CARD && params.expiryYearMonth) {
            const [year, month] = params.expiryYearMonth.split('/')
            params.expiryYear = year
            params.expiryMonth = month
        }
        const res = await personalApi.customBankUpdate(params)
        if (res.code === 200) {
            uni.hideLoading()
            uni.showToast({
                title: t('Msg.Success'),
                icon: 'success'
            })
            editingId.value = null
            getBankInfo()
        } else {
            throw new Error(res.msg)
        }
    } catch (error) {
        uni.hideLoading()
        uni.showToast({
            title: error.message || t('Msg.Fail'),
            icon: 'none'
        })
    }
}
// 删除
const confirmDelete = (item) => {
    if (item.approveStatus == 1) {
        uni.showToast({
            title: '加密钱包认证审核中',
            icon: 'none'
        })
        return
    }
    deleteTarget.value = item
    deletePopup.value.open()
}

// 关闭删除弹窗
const closeDeletePopup = () => {
    deletePopup.value.close()
    deleteTarget.value = null
}

// 执行删除
const deleteBank = async () => {
    if (!deleteTarget.value) return
    uni.showLoading({ title: t('Btn.Deleting') })
    try {
        const res = await personalApi.customBankDelete({
            ids: [deleteTarget.value.id]
        })
        if (res.code === 200) {
            uni.hideLoading()
            uni.showToast({
                title: t('Msg.DeleteSuccess'),
                icon: 'success'
            })
            deletePopup.value.close()
            deleteTarget.value = null
            getBankInfo()
        } else {
            throw new Error(res.msg)
        }
    } catch (error) {
        uni.hideLoading()
        uni.showToast({
            title: error.message || t('Msg.Fail'),
            icon: 'none'
        })
        deletePopup.value.close()
    }
}
// 新增银行信息
const addBankDialogRef = ref(null);
function openAddBankCard() {
    const wallets = cryptoWallets.value || [];

    // 1️⃣ 没有钱包
    if (wallets.length === 0) {
        addBankDialogRef.value?.open();
        return;
    }

    // 2️⃣ 是否存在未认证钱包
    const hasUnAuth = wallets.some(
        item => item.authStatus === 0 || item.approveStatus === 1
    );

    if (hasUnAuth) {
        uni.showToast({
            title: "加密钱包未认证",
            icon: "none"
        });
        return;
    }

    // 3️⃣ 是否达到上限
    if (wallets.length >= 2) {
        uni.showToast({
            title: t('blockchain.item9'),
            icon: "none"
        });
        return;
    }

    // 4️⃣ 正常打开
    addBankDialogRef.value?.open();
}
// 新增银行信息成功回调
const addSuccess = (e) => {
    openKycDialog(e)
    getBankInfo();
}

// kyc认证和证件认证
const kycDialogRef = ref(null);
const cardDialogRef = ref(null);
// kyc认证
const doReady = (bankId, item) => {
    if (item.approveStatus == 1) {
        uni.showToast({
            title: "加密钱包认证审核中",
            icon: "none"
        });
        return;
    }
    if (item.authStatus == 1) {
        uni.showToast({
            title: "加密钱包已认证",
            icon: "none"
        });
        return;
    }
    openKycDialog(bankId)
}
// 打开kyc认证弹窗
function openKycDialog(e) {
    kycDialogRef.value?.open(e);
}
// 打开证件认证弹窗
function openCardDialog(e, item) {
    if (item.approveStatus == 1) {
        uni.showToast({
            title: "加密钱包认证审核中",
            icon: "none"
        });
        return;
    }
    if (item.authStatus == 1) {
        uni.showToast({
            title: "加密钱包已认证",
            icon: "none"
        });
        return;
    }
    cardDialogRef.value?.open(e, item);
}


// 预览图片
const previewImage = (path) => {
    uni.previewImage({
        urls: [updateUrl + path]
    })
}

// 掩码卡号
const maskCardNumber = (num) => {
    if (!num) return '--'
    if (num.length <= 4) return num
    return '**** **** **** ' + num.slice(-4)
}

// 获取银行列表
const getBankList = async () => {
    const res = await personalApi.BankList({})
    if (res.code === 200) {
        bankOptions.value = res.data
    }
}

// 获取银行信息
const getBankInfo = async () => {
    uni.showLoading({ title: t('Btn.Loading') })
    try {
        const res = await personalApi.customBankList({})
        if (res.code === 200) {
            // 清空数据
            bankData.value = {
                [BankType.CRYPTO]: [],
                [BankType.UNIONPAY]: [],
                [BankType.WIRE_TRANSFER]: [],
                [BankType.CREDIT_CARD]: []
            }
            // 分类数据
            res.data.forEach(item => {
                item.defaultBank = !!item.defaultBank
                if (item.type === BankType.UNIONPAY) {
                    bankData.value[BankType.UNIONPAY].push(item)
                } else if (item.type === BankType.WIRE_TRANSFER) {
                    bankData.value[BankType.WIRE_TRANSFER].push(item)
                } else if (item.type === BankType.CREDIT_CARD) {
                    item.expiryYearMonth = item.expiryYear && item.expiryMonth
                        ? `${item.expiryYear}/${item.expiryMonth}`
                        : ''
                    bankData.value[BankType.CREDIT_CARD].push(item)
                } else if (item.type === BankType.CRYPTO) {
                    bankData.value[BankType.CRYPTO].push(item)
                }
            })
        }
    } catch (error) {
        uni.showToast({
            title: error.message || t('Msg.Fail'),
            icon: 'none'
        })
    } finally {
        uni.hideLoading()
    }
}
// 获取银行信息
onMounted(() => {
    getBankList()
    getBankInfo();
});
</script>



<style scoped lang="scss">
.user-form {
    margin-top: px2rpx(30);
}

:deep(.uni-row1) {
    .uni-col {
    }

    .uni-forms-item {
        min-height: px2rpx(79);
        margin-bottom: px2rpx(10);
    }

    .uni-easyinput__content {
        border: none !important;
        //background-color: var(--color-zinc-100) !important;
    }
}

.bank-menu {
    background: #fff;
    overflow: hidden;

    .bank-menu-item {
        display: flex;
        align-items: center;
        gap: px2rpx(12);
        padding: px2rpx(10) px2rpx(16);
        cursor: pointer;
        border: 1px solid #f3f4f6;
        font-size: px2rpx(16);
        font-weight: 500;
        color: #1f2937;
        transition: all 0.3s;
        height: px2rpx(50);
        border-radius: px2rpx(8);
        margin-bottom: px2rpx(8);

        .bank-icon {
            width: px2rpx(50);
        }

        &.active {
            background: #ea2027;
            color: var(--bs-emphasis-color);
            border-radius: px2rpx(0);
        }

        &:hover {
            background: #f9fafb;
        }

        &.active:hover {
            background: #d11920;
        }
    }
}

.bank-content {
    background: #fff;
    border-radius: px2rpx(8);
    padding: 0 px2rpx(24);

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

            .bank-title {
                display: flex;
                align-items: center;
                font-size: px2rpx(20);
                font-weight: 600;
                color: #1f2937;
                margin-bottom: px2rpx(20);
            }

            .bank-actions {
                display: flex;
                gap: px2rpx(12);
                align-items: center;
                justify-content: flex-end;

                .action-btn {
                    padding: px2rpx(8) px2rpx(16);
                    border: 1px solid #d1d5db;
                    border-radius: px2rpx(4);
                    font-size: px2rpx(14);
                    cursor: pointer;
                    background: #fff;
                    transition: all 0.3s;

                    &:hover {
                        background: #f3f4f6;
                    }

                    &.delete {
                        background: #ea2027;
                        color: var(--bs-emphasis-color);
                        border-color: #ea2027;

                        &:hover {
                            background: #d11920;
                        }
                    }
                }
            }
        }
    }

    .photo-upload {
        display: flex;
        gap: px2rpx(16);

        .photo-item {
            width: px2rpx(120);
            height: px2rpx(120);
            border-radius: px2rpx(8);
            overflow: hidden;
            background: #f3f4f6;

            .photo-preview {
                width: 100%;
                height: 100%;
            }
        }
    }

    .add-wallet-btn {
        margin-top: px2rpx(24);
        height: px2rpx(48);
        background: #ea2027;
        color: var(--bs-emphasis-color);
        border-radius: px2rpx(4);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(8);
        font-size: px2rpx(16);
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            background: #d11920;
        }
    }
}
</style>