<template>
    <view class="col-lg-4 col-md-6">
        <view class="card">
            <view class="card-header d-flex align-items-center justify-content-between border-0 pb-2 p-3">
                <text v-if="!isDel" class="badge bg-success-subtle text-success">正常</text>
                <text v-if="isDel" class="badge bg-danger-subtle text-danger">已删除</text>
                <view class="clearfix">
                    <view class="btn-group">
                        <cwg-dropdown ref="dropdownRef" @open="onOpen" @close="onClose" :menu-list="customMenuList"
                            @menuClick="handleCustomClick">
                            <button class="btn btn-white btn-sm btn-shadow btn-icon waves-effect dropdown-toggle"
                                type="button">
                                <cwg-icon name="crm-ellipsis-vertical" :size="18"
                                    :color="!isDark ? '#6c8595' : '#fff'" />
                            </button>
                        </cwg-dropdown>
                    </view>
                </view>
            </view>
            <view class="card-body p-3 pt-0">
                <view class="text-left mb-3">
                    <h5 class="fw-bold mb-3  cursor-pointer" @click="copy(account.accountNumber)"># {{
                        account.accountNumber }}</h5>
                    <h4 class="mb-2 cursor-pointer" @click="copy(account.fwq)">{{ account.fwq }}</h4>
                    <template v-for="(label, index) in account.labels" :key="index">
                        <text v-if="label" class="badge text-danger1 bg-danger-subtle mx-1">{{ label }}</text>
                    </template>
                    <h1 class="mt-2">${{ balanceInteger }}{{ balanceDecimal }}</h1>
                    <!-- <button type="submit" value="Submit" class="btn btn-secondary btn-sm w-75 waves-effect waves-light"
                        @click="handleAction('trade')">
                        <view class="d-flex align-items-center justify-content-center gap-1"><cwg-icon name="crm-trade"
                                :size="16" color="#fff" />
                            开始交易</view>

                    </button> -->
                    <hr>
                </view>
                <view class="text-left">
                    <view class="border-0 card-header p-2">
                        <view class="row">
                            <view class="col-6">
                                <view class="mb-3">
                                    <view class="mb-1">{{ t('Label.Leverage') }}</view>
                                    <view class="d-flex fw-semibold mb-0 text-dark">{{ account.actualLeverage }}</view>
                                </view>
                                <view class="mb-3">
                                    <view class="mb-1">{{ t('Label.FloatingPL') }}</view>
                                    <view class="d-flex fw-semibold mb-0 text-dark">{{ account.floatingPL }}</view>
                                </view>
                                <view class="mb-3">
                                    <view class="mb-1">{{ t('Label.Balance') }}</view>
                                    <view class="text-dark fw-semibold mb-0">{{ account.balanceWithSymbol }}</view>
                                </view>
                            </view>
                            <view class="col-6">
                                <view class="mb-3">
                                    <view class="mb-1">{{ t('Label.Equity') }}</view>
                                    <view class="text-dark fw-semibold mb-0">{{ account.equityWithSymbol }}</view>
                                </view>
                                <view class="mb-3">
                                    <view class="mb-1">{{ t('Label.Credit') }}</view>
                                    <view class="text-dark fw-semibold mb-0">{{ account.creditWithSymbol }}</view>
                                </view>
                                <view class="mb-3">
                                    <view class="mb-1">{{ t('Documentary.console.item3') }}</view>
                                    <view class="text-dark fw-semibold mb-0">{{ account.platform }}</view>
                                </view>
                            </view>
                        </view>
                        <view class="d-flex flex-wrap gap-2" v-if="isReal">
                            <button v-for="btn in actionButtons" :key="btn.key" type="submit" value="Submit"
                                class="btn btn-dark btn-sm waves-effect waves-light"
                                :class="{ 'disabled': btn.disabled, 'btn-outline-dark1': btn.key !== 'deposit'}" @click="handleAction(btn.action)">
                                <view class="d-flex align-items-center justify-content-center gap-1">
                                    <cwg-icon :name="btn.icon" :size="14" :color="btn.key === 'deposit' ? '#fff' : ''" />
                                    {{ t(btn.label) }}
                                </view>
                            </button>
                        </view>
                    </view>
                </view>
            </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') + ' # '" />
</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'
import useGlobalStore from '@/stores/use-global-store'
const globalStore = useGlobalStore()
const isDark = computed(() => globalStore.theme === 'dark')
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 isDel = computed(() => accountInfo.value.listType == 'del')
const isReal = computed(() => accountInfo.value.listType == 'real')

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: 'deposit', label: 'Home.page_customer.item2', icon: 'crm-deposit', action: 'deposit', needDemo: isDemo.value, disabled: !closeFunctionOpen('1'), color: '#6c8595' },
    { key: 'withdraw', label: 'Home.page_customer.item3', icon: 'crm-withdraw', action: 'withdraw', needDemo: isDemo.value, disabled: !closeFunctionOpen('2'), color: '#6c8595' },
    { key: 'transfer', label: 'Custom.Index.Transfer', icon: 'crm-transfer', action: 'transfer', needDemo: isDemo.value, disabled: !(closeFunctionOpen('5') && closeFunctionOpen('6') && closeFunctionOpen('3')), color: '#6c8595' }
])
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 actionButtons = ref([
    { key: 'deposit', label: 'Home.page_customer.item2', icon: 'crm-deposit', action: 'deposit', disabled: computed(() => !closeFunctionOpen('1')) },
    { key: 'withdraw', label: 'Home.page_customer.item3', icon: 'crm-withdraw', action: 'withdraw', disabled: computed(() => !closeFunctionOpen('2')) },
    { key: 'transfer', label: 'Custom.Index.Transfer', icon: 'crm-transfer', action: 'transfer', disabled: computed(() => !(closeFunctionOpen('5') && closeFunctionOpen('6') && closeFunctionOpen('3'))) }
])

const terminalDialogVisible = ref(false)
const terminalChangePasswordDialogVisible = ref(false)
const terminalInfoDialogVisible = ref(false)
const pwdType = ref(1)

const dropdownRef = ref(null)

const handleAction = (type: string) => {
    if (dropdownRef.value) {
        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 'changePassword3':
            pwdType.value = 3
            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(() => {
    switch (accountInfo.value.listType) {
        case 'real':
            return [
                { label: '开始交易', type: 'trade' },
                { 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('Custom.Settings.TitReset'), type: 'changePassword3' }
            ]
        case 'demo':
            return [
                { label: '开始交易', type: 'trade' },
                { label: t('Documentary.TundManagement.item29'), type: 'info' }
            ]

        case 'del':
            return [
                { 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 accountInfo.value.balance ? Math.floor(accountInfo.value.balance).toString() : '0';
});
const balanceDecimal = computed(() => {
    const parts = accountInfo.value?.balance?.toFixed(2)?.split || [];
    console.log(accountInfo.value?.balance, 1212);
    if (!accountInfo.value?.balance) return '.00'

    return parts[1] ? '.' + parts[1] : '.00';
});
onMounted(() => {
});
onBeforeUnmount(() => {
});
</script>

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

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

.btn {
    margin-left: 0;
    margin-right: 0;
}

.text-danger1 {
    color: var(--bs-emphasis-color) !important;
}

.btn-outline-dark1 {
    background-color: var(--btn-color) !important;
    color: var(--bs-emphasis-color) !important;
    border-color: var(--btn-color) !important;
}
</style>