<template>
    <view class="account-card">
        <!-- 标签区域 -->
        <view class="card-top">
            <view class="labels-container">
                <view class="account-number" @click="copy(account.accountNumber)"># {{ account.accountNumber }}</view>
                <view class="account-number" @click="copy(account.fwq)">{{ account.fwq }}</view>
                <view class="labels">
                    <template v-for="(label, index) in account.labels" :key="index">
                        <view v-if="label" class="label-badge" :class="{ 'active': index === 0 && isDemo }">
                            {{ label }}
                        </view>
                    </template>
                </view>
            </view>
            <cwg-dropdown ref="dropdownRef" @open="onOpen" @close="onClose" :menu-list="customMenuList"
                @menuClick="handleCustomClick">
                <view class="more-icon more-btn">
                    <cwg-icon name="crm-ellipsis-vertical" :size="20" color="#fff" />
                </view>
                <template #btn>
                    <view class="mobile-buttons">
                        <!-- 交易 -->
                        <template v-for="(item, index) in circleButtons" :key="index">
                            <view class="circle-btn" :class="{ 'is-disabled': item.disabled }"
                                @click="handleAction1(item)" v-if="!item.needDemo">
                                <view class="circle-icon" :class="{ 'primary': item.primary }">
                                    <cwg-icon :name="item.icon" :size="16" :color="item.color" />
                                </view>
                                <text class="circle-label" v-t="item.label" />
                            </view>
                        </template>
                    </view>
                </template>
            </cwg-dropdown>
        </view>


        <!-- 主要内容区域（余额和操作按钮） -->
        <view class="main-content">
            <!-- 余额 -->
            <view class="balance">
                <text class="balance-number">{{ balanceInteger }}</text>
                <text class="balance-decimal">{{ balanceDecimal }} {{ account.currency }}</text>
            </view>
        </view>
        <view class="info-bottom">
            <!-- 底部信息区域（折叠时隐藏） -->
            <view class="info-section">
                <view class="info-column">
                    <cwg-label-line-value :label="t('Label.Leverage')" :value="account.actualLeverage" />
                    <cwg-label-line-value :label="t('Label.FloatingPL')" :value="account.floatingPL" />
                    <cwg-label-line-value :label="t('Label.Balance')" :value="account.balanceWithSymbol" />
                </view>
                <view class="info-column">
                    <cwg-label-line-value :label="t('Label.Equity')" :value="account.equityWithSymbol" />
                    <cwg-label-line-value :label="t('Label.Credit')" :value="account.creditWithSymbol" />
                    <cwg-label-line-value :label="t('Documentary.console.item3')" :value="account.platform" />
                </view>
            </view>
        </view>

        <TerminalDialog v-model:visible="terminalDialogVisible" />
        <TerminalChangePasswordDialog v-model:visible="terminalChangePasswordDialogVisible" :pwdType="pwdType"
            :account="account" :accountLabel="t('Documentary.tradingCenter.item29') + ' # '" />
        <TerminalInfoDialog v-model:visible="terminalInfoDialogVisible" :accountNumber="accountInfo.login"
            :form="accountInfo" :fieldList="fieldList" :title="t('Documentary.TundManagement.item29')"
            :accountLabel="t('Documentary.tradingCenter.item29') + ' # '" />
    </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick, onBeforeUnmount } from 'vue';
import useRouter from "@/hooks/useRouter";
const router = useRouter();
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
import TerminalDialog from './TerminalDialog.vue'
import TerminalChangePasswordDialog from './TerminalChangePasswordDialog.vue'
import TerminalInfoDialog from './TerminalInfoDialog.vue'

const props = defineProps<{
    account: Account;
}>();
const accountInfo = ref(props.account)
// 定义账户数据类型
export interface Account {
    labels: string[];          // 标签数组，如 ['真实', 'MT4', 'Standard']
    accountNumber: string;      // 账号，如 '85319215'
    nickName: string;           // 昵称，如 '标准账户'
    balance: number;            // 余额数字
    currency: string;           // 货币，如 'USD'
    actualLeverage: string;     // 实际杠杆，如 '1:2000'
    maxLeverage: string;        // 调整杠杆，如 '1:2000'
    floatingPL: string;         // 浮动盈亏，如 '0.00 USD'
    creditWithSymbol: string;         // 可用保证金，如 '0.00 USD'
    equityWithSymbol: string;             // 净值，如 '0.00 USD'
    platform: string;           // 平台，如 'MT4'
    server: string;             // 服务器，如 'Exness-Real28'
    login: string;              // 登录名，如 '85319215'
    balanceWithSymbol: string;              // 余额，如 '85319215'
    fwq: string;                // 服务器名称
    listType: string;           // 账户类型，如 'real' 或 'demo'
    closeFunctions?: string;    // 关闭的功能
}
const isDemo = computed(() => accountInfo.value.listType == 'demo')
const closeFunctionOpen = (code) => {
    const closeFunctions = accountInfo.value.closeFunctions || ""
    if (closeFunctions == null || closeFunctions === "") {
        return true;
    }
    return String(closeFunctions).indexOf(String(code)) === -1;
}
// 圆形按钮数据
const circleButtons = ref([
    { key: 'trade', label: 'Shop.Index.Transaction', icon: 'crm-trade', action: 'trade', needDemo: false, primary: true, disabled: false, color: '#fff' },
    { key: 'deposit', label: 'Home.page_customer.item2', icon: 'crm-deposit', action: 'deposit', needDemo: isDemo.value, disabled: !closeFunctionOpen('1'), color: '#282b44' },
    { key: 'withdraw', label: 'Home.page_customer.item3', icon: 'crm-withdraw', action: 'withdraw', needDemo: isDemo.value, disabled: !closeFunctionOpen('2'), color: '#282b44' },
    { key: 'transfer', label: 'Custom.Index.Transfer', icon: 'crm-transfer', action: 'transfer', needDemo: isDemo.value, disabled: !(closeFunctionOpen('5') && closeFunctionOpen('6') && closeFunctionOpen('3')), color: '#282b44' }
])

const fieldList = ref([
    { label: t('Custom.PaymentHistory.AccountType'), key: 'nickname', copyable: false },
    { label: t('Label.Leverage'), key: 'actualLeverage', copyable: false },
    { label: t('Label.FloatingPL'), key: 'floatingPL', copyable: false },
    { label: t('Label.Balance'), key: 'balanceWithSymbol', copyable: false },
    { label: t('Label.Equity'), key: 'equityWithSymbol', copyable: false },
    { label: t('Label.Credit'), key: 'creditWithSymbol', copyable: false },
    { label: t('Documentary.console.item3'), key: 'platform', copyable: false },
    { label: t('Documentary.console.item4'), key: 'login', copyable: true }
])
const nickName = ref(accountInfo.value.nickName);


const terminalDialogVisible = ref(false)
const terminalChangePasswordDialogVisible = ref(false)
const terminalInfoDialogVisible = ref(false)
const pwdType = ref(1)
const handleAction1 = (item) => {
    if (item.disabled) {
        uni.showToast({
            title: t('news_add_field.Des.item1'),
            icon: 'none'
        })
        return
    }
    handleAction(item.action, item)
}
const dropdownRef = ref(null)

// 处理按钮操作
const handleAction = (type: string) => {
    dropdownRef.value.close()
    switch (type) {
        case 'trade':
            terminalDialogVisible.value = true
            break;
        case 'changePassword1':
            pwdType.value = 1
            terminalChangePasswordDialogVisible.value = true
            break;
        case 'changePassword2':
            pwdType.value = 2
            terminalChangePasswordDialogVisible.value = true
            break;
        case 'info':
            terminalInfoDialogVisible.value = true
            break;
        case 'deposit':
            toDeposit()
            break;
        case 'withdraw':
            toWithdraw()
            break;
        case 'transfer':
            toTransfer()
            break;
        case 'position':
            toPosition()
            break;
        case 'history':
            toHistory()
            break;
        case 'payment-history':
            toPaymentHistory()
            break;
        default:
            break;
    }
};

const customMenuList = computed(() => !isDemo.value ? [
    { label: t('Ib.Report.Tit1'), type: 'history' },
    { label: t('Ib.Report.Tit4'), type: 'position' },
    { label: t('Home.page_customer.item4'), type: 'payment-history' },
    { label: t('Documentary.TundManagement.item29'), type: 'info' },
    { label: t('vu.item3'), type: 'changePassword1' },
    { label: t('vu.item4'), type: 'changePassword2' }
] : [
    // { label: t('Ib.Report.Tit1'), type: 'history' },
    // { label: t('Ib.Report.Tit4'), type: 'position' },
    { label: t('Documentary.TundManagement.item29'), type: 'info' }
])
const handleCustomClick = (item, index) => {
    handleAction(item.value.type)
}
// 复制文本
const copy = (text: string) => {
    uni.setClipboardData({
        data: text,
        success: function () {
            uni.showToast({
                title: t('Btn.item8'),
                icon: 'none',
                duration: 2000
            });
        }
    });
};
// 按钮对应的操作方法
const toHistory = () => {
    router.push(`/pages/customer/trade-history?login=${accountInfo.value.login}`)
}
// 按钮对应的操作方法
const toPosition = () => {
    router.push(`/pages/customer/trade-position?login=${accountInfo.value.login}`)
}
// 按钮对应的操作方法
const toPaymentHistory = () => {
    router.push(`/pages/customer/payment-history?login=${accountInfo.value.login}`)
}
// 按钮对应的操作方法
const toDeposit = () => {
    router.push(`/pages/customer/deposit-select?login=${accountInfo.value.login}&type=${accountInfo.value.type}&balance=${accountInfo.value.balance}&currency=${accountInfo.value.currency}`)
}
const toWithdraw = () => {
    router.push(`/pages/customer/withdrawal-select?login=${accountInfo.value.login}&type=${accountInfo.value.type}&balance=${accountInfo.value.balance}&currency=${accountInfo.value.currency}`)
}
const toTransfer = () => {
    router.push(`/pages/customer/transfer?login=${accountInfo.value.login}&type=${accountInfo.value.type}&balance=${accountInfo.value.balance}&currency=${accountInfo.value.currency}`)
}
// 格式化余额，拆分为整数和小数部分
const balanceInteger = computed(() => {
    return Math.floor(accountInfo.value.balance).toString();
});
const balanceDecimal = computed(() => {
    const parts = accountInfo.value.balance.toFixed(2).split('.');
    return parts[1] ? '.' + parts[1] : '.00';
});
// 在组件挂载后初始化
onMounted(() => {
});
onBeforeUnmount(() => {
});
</script>

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

.account-card {
    border-radius: px2rpx(16);
    padding: px2rpx(16);
    margin-bottom: px2rpx(16);
    position: relative;
    border: 1px solid rgba(108, 133, 149, 0.12);
    color: var(--bs-emphasis-color);




    .labels-container {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: px2rpx(12);

        margin-bottom: px2rpx(16);

        .labels {
            display: flex;
            gap: px2rpx(8);
        }

        .label-badge {
            background-color: rgba(108, 133, 149, 0.08);
            border-radius: px2rpx(4);
            padding: px2rpx(4) px2rpx(8);
            font-size: px2rpx(12);
            color: var(--bs-emphasis-color);
            font-weight: 500;
        }

        .active {
            background-color: rgba(70, 205, 124, 0.08);
            color: rgb(14, 115, 55);
            font-weight: 500;
        }

        .account-number {
            font-size: px2rpx(18);
            font-weight: 600;
            line-height: 1.3;
            cursor: pointer;
            color: var(--bs-emphasis-color);

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

        .account-nickname {
            font-size: px2rpx(14);
            color: var(--bs-emphasis-color);
        }
    }

    .main-content {
        .balance {
            margin-bottom: px2rpx(16);

            .balance-number {
                font-size: px2rpx(32);
                font-weight: 700;
            }

            .balance-decimal {
                font-size: px2rpx(16);
                color: var(--bs-emphasis-color);
                margin-left: px2rpx(4);
            }
        }


    }

    .info-section {
        display: flex;
        flex-direction: column;
        gap: px2rpx(12);
        padding: px2rpx(16) 0;
        margin: px2rpx(16) 0;

        .info-column {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: px2rpx(12);
        }

        .info-item {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            font-size: px2rpx(14);

            .label {
                color: var(--bs-emphasis-color);
            }

            .line {
                flex: 1;
                height: 1px;
                border-top: 1px dashed rgba(108, 133, 149, 0.5);
                margin-bottom: px2rpx(1);

            }

            .value {
                font-weight: 500;
                color: var(--bs-emphasis-color);
            }
        }
    }

    @media screen and (max-width: 768px) {
        .info-section {
            flex-direction: column;
            gap: px2rpx(12);
        }
    }

    .extra-actions {
        display: flex;
        align-items: center;
        gap: px2rpx(8);
        margin-bottom: px2rpx(12);

        .copy-row {
            display: flex;
            align-items: center;
            gap: px2rpx(4);

            font-size: px2rpx(14);

            .label {
                color: var(--bs-emphasis-color);
                min-width: px2rpx(30);
            }

            .value {
                flex: 1;
                color: var(--bs-emphasis-color);
                font-family: monospace;
            }

            .copy-btn {
                background: transparent;
                border: 1px solid rgba(108, 133, 149, 0);
                padding: 0;
                cursor: pointer;
                color: var(--bs-emphasis-color);
                width: px2rpx(24);
                height: px2rpx(24);
                display: flex;
                align-items: center;
                justify-content: center;
                box-sizing: border-box;

                svg {
                    width: px2rpx(20);
                    height: px2rpx(20);
                }

                &:hover {
                    background-color: rgba(108, 133, 149, 0.05);
                    border: 1px solid rgba(108, 133, 149, 0.2);
                }
            }
        }

        .divider {
            width: 1px;
            height: px2rpx(20);
            border-left: 1px solid rgba(108, 133, 149, 0.5);
        }

        .change-password-btn {
            background: transparent;
            box-sizing: border-box;
            border: 1px solid rgba(108, 133, 149, 0);
            border-radius: px2rpx(8);
            padding: px2rpx(8) px2rpx(16);
            font-size: px2rpx(14);
            color: var(--bs-emphasis-color);
            display: inline-flex;
            gap: px2rpx(8);
            cursor: pointer;
            margin: 0;

            .btn-icon svg {
                width: px2rpx(16);
                height: px2rpx(16);
            }

            &:hover {
                background-color: rgba(108, 133, 149, 0.05);
                border: 1px solid rgba(108, 133, 149, 0.2);
            }
        }
    }



    .notificators {
        // 预留通知区域
    }
}

.card-top {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    :deep(.cwg-dropdown-menu-container) {
        left: px2rpx(-190) !important;

        @media screen and (max-width: 768px) {
            left: px2rpx(-200) !important;
            width: px2rpx(240);
        }
    }

    .more-btn {
        flex-shrink: 0;
        width: px2rpx(40);
        height: px2rpx(40);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(4);
        background-color: rgba(108, 133, 149, 0.08);
        border-radius: px2rpx(4);
        cursor: pointer;

        &:hover {
            background-color: rgba(108, 133, 149, 0.1);
        }
    }

    // 移动端按钮组
    .mobile-buttons {
        display: flex;
        justify-content: center;
        gap: px2rpx(12);
        padding-bottom: px2rpx(16);
        padding: px2rpx(20);


        border-bottom: 1px solid var(--bs-border-color);

        .circle-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            width: px2rpx(40);

            .circle-icon {
                width: px2rpx(40);
                height: px2rpx(40);
                border-radius: 50%;
                background-color: #f5f7f9;
                display: flex;
                align-items: center;
                justify-content: center;
                color: var(--bs-emphasis-color);
                transition: background-color 0.2s;

                &.primary {
                    background-color: #cf1322;
                    ;
                    color: var(--bs-emphasis-color);
                }

                &:hover {
                    background-color: #e9ecef;
                }

                &.primary:hover {
                    background-color: #cf1322;
                    ;
                    color: var(--bs-emphasis-color);
                }

                svg {
                    width: px2rpx(24);
                    height: px2rpx(24);
                }
            }

            .circle-label {
                font-size: px2rpx(12);
                margin-top: px2rpx(4);
                color: var(--bs-emphasis-color);
            }
        }
    }

    .is-disabled {
        cursor: not-allowed;
        opacity: 0.5;
    }

}
</style>