<template>
    <view class="account-card">
        <view class="content-title">
            <view v-t="'Custom.Index.AccountList'"></view>
            <view class="content-title-btns">
                <view class="btn-primary btn-primary1" @click="createAccount()">
                    <cwg-icon icon="crm-plus" :size="16" color="#fff" />
                    <text v-t="'Custom.Index.AddAccount'" />
                </view>
            </view>
        </view>
        <view class="tabs-class"><cwg-tabs v-model:cativeIndex="cativeIndex" :tabs="tabs" /></view>
        <view v-if="accounts.length">
            <AccountCard v-for="acc in accounts" :zhtype="cativeIndex" :key="acc.accountNumber" :account="acc"
                @action="handleAction" @copy="handleCopy" @change-password="handleChangePassword" />
        </view>
        <cwg-empty-state v-else />
        <DeleteAccountDialogs ref="deleteAccountDialogRef" v-model:visible="deleteAccountDialogVisible" />
    </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch } from 'vue';
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n();
import useRouter from "@/hooks/useRouter";
const router = useRouter();
import { customApi } from '@/service/custom';
import { userApi } from '@/api/user';
import useUserStore from "@/stores/use-user-store";
const userStore = useUserStore();
import AccountCard from './AccountCard.vue'
import DeleteAccountDialogs from './DeleteAccountDialogs.vue'
import { useFilters } from '@/composables/useFilters'
const { numberFormat, numberDecimal } = useFilters()
const search = ref({ platform: 'MT4' })
const isAfterJuly28 = () => {
    const now = new Date();
    const july28 = new Date(2025, 6, 28, 0, 0, 0); // 月份从0开始，所以7月是6

    return now >= july28;
}


const handleAction = (type) => { /* 处理交易/入金等 */ };
const handleCopy = (text) => { uni.setClipboardData({ data: text }); };
const handleChangePassword = () => { /* 跳转修改密码 */ };
const typeMap = computed(() => ({
    1: t('AccountType.ClassicAccount'),
    2: t('AccountType.SeniorAccount'),
    3: !isAfterJuly28() ? t('AccountType.AgencyAccount') : '',
    5: t('AccountType.SpeedAccount'),
    6: t('AccountType.SpeedAccount'),
    7: t('AccountType.StandardAccount'),
    8: t('AccountType.CentAccount')
}));
const cativeIndex = ref(0)
const tabs = computed(() => ([
    { id: 'real', name: t('vu.item1') },
    { id: 'demo', name: t('vu.item2') }
]))

const tableRef = ref(null)
const expanded = ref(null)
const toggleRowExpand = (row) => {
    expanded.value = row.expanded ? row.rowIndex : null
}
const toggleExpand = (index) => {
    tableRef?.value.toggleRowExpand(index)
}
const createActionButtons = (row) => {
    console.log(row, 'row');

    return computed(() => [
        {
            icon: 'crm-circle-dollar-to-slot',
            text: t('Custom.Index.Deposit'),
            action: 'deposit',
            disabled: row.closeFunctions?.indexOf('1') !== -1,
            show: true,
            class: 'deposit-btn'
        },
        {
            icon: 'crm-credit-card',
            text: t('Custom.Index.Withdrawals'),
            action: 'withdraw',
            disabled: row.closeFunctions?.indexOf('2') !== -1,
            show: true,
            class: 'withdraw-btn'
        },
        {
            icon: 'crm-money-bill-transfer',
            text: t('Custom.Index.Transfer'),
            action: 'transfer',
            disabled: (
                row.closeFunctions?.indexOf('5') !== -1 ||
                row.closeFunctions?.indexOf('6') !== -1 ||
                row.closeFunctions?.indexOf('3') !== -1
            ),
            show: true,
            class: 'transfer-btn'
        },
        {
            icon: 'crm-gear',
            text: t('Custom.Index.Settings'),
            action: 'settings',
            disabled: row.closeFunctions?.indexOf('4') !== -1,
            show: true,
            class: 'settings-btn'
        },
        {
            icon: 'crm-award',
            text: t('standardRebate.item1'),
            action: 'standardRebate',
            disabled: false,
            show: row.type === 7,
            class: 'rebate-btn'
        }
    ])
}
// 处理按钮点击
const handleActionBtn = (action, row) => {
    switch (action) {
        case 'deposit':
            toDeposit(row)
            break
        case 'withdraw':
            toWithdraw(row)
            break
        case 'transfer':
            toTransfer(row)
            break
        case 'settings':
            toSettings(row)
            break
        case 'standardRebate':
            toStandardRebate(row)
            break
    }
}


const deleteAccountDialogVisible = ref(false)
const openDeleteAccountDialogs = () => {
    deleteAccountDialogVisible.value = true
}
const createAccount = () => {
    getCustomLoginInfo()
}
const isZh = computed(() => ['cn', 'zh', 'zhHant'].includes(locale.value));

watch(cativeIndex, (newVal) => {
    // search.value.platform = tabs.value[newVal].id
    getAccountList()
})

// 获取客户登录信息
async function getCustomLoginInfo() {
    try {
        const res = await userApi.getUserInfo();
        userStore.saveUserInfo(res.data);
        if (res.code === 200) {
            if (
                res.data.customInfo.status == 2 &&
                res.data.customInfo.applyRealStatus == 2
            ) {
                router.push(`/pages/customer/account-select?server=${cativeIndex.value == 1 ? 'demo' : 'real'}`)
            } else {
                // this.dialogCheck = true;
            }
        }
    } catch (error) {
        //  console.log(error, 111);
    }
}
const AccountList = ref([])
const getAccountList = async () => {
    AccountList.value = []

    const api = cativeIndex.value == 1 ? customApi.demoList : customApi.AccountAllList
    const res = await api({
        page: {
            current: 1,
            size: 100
        }
    })
    if (res.code === 200) {
        AccountList.value = res.data
    }
}
// 格式化数值函数
function formatMoney(value) {
    if (value === null || value === undefined) value = 0;
    const sign = value >= 0 ? '' : '-';
    const absoluteValue = Math.abs(value);
    return sign + '$' + absoluteValue.toFixed(2);
}

// 转换数组
const accounts = computed(() =>
    AccountList.value && AccountList.value.length != 0 ? AccountList.value.map((acc, index) => {
        const currency = acc.currency || 'USD';
        const floating = acc.floating ?? 0;
        let labels = [t('vu.item1'), 'MT4', 'Standard'];
        labels[0] = cativeIndex.value == 1 ? t('vu.item2') : t('vu.item1');
        labels[1] = acc.platform || 'MT4';
        labels[2] = typeMap.value[acc.type];
        let nickname = typeMap.value[acc.type];
        const balance = acc.balance
        return {
            ...acc,
            labels,
            isExpanded: index == 0,
            balance,
            accountNumber: acc.login.toString(),
            nickname,
            balanceWithSymbol: acc.balanceWithSymbol ?? '$0', // 余额
            creditWithSymbol: acc.creditWithSymbol ?? '$0',//信用
            equityWithSymbol: acc.equityWithSymbol ?? '$0',//净值
            currency,
            actualLeverage: '1:' + (acc.leverage ?? 0), // 实际杠杆
            floatingPL: formatMoney(floating), // 盈亏
            platform: acc.platform || 'MT4',
            server: acc.groupCode || '',
            login: acc.login.toString(),
            listType: cativeIndex.value == 1 ? 'demo' : 'real'
        };
    }) : []
)
onMounted(async () => {
    await getAccountList()
})
</script>

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

.account-card {
    width: 100%;
    background-color: var(--color-white);
    box-sizing: border-box;
}

.tabs-class {
    width: px2rpx(200);
    margin: px2rpx(20) 0;
}

.content-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: px2rpx(22);
    font-weight: 500;
    color: var(--color-slate-800);
    background-color: rgba(255, 255, 255, 0);

    .content-title-btns {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(12);


        .btn-primary {
            min-width: px2rpx(120);
            background-color: var(--color-error);
            color: var(--color-slate-150);
            padding: 0 px2rpx(12);
            border: none;
            font-size: px2rpx(14);
            text-align: center;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: px2rpx(8);
        }

        .btn-primary1 {
            background-color: var(--color-navy-700);
        }
    }
}

.operation-btn {
    :deep(span) {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: px2rpx(4);
        cursor: pointer;
        background-color: var(--color-slate-150);
        padding: px2rpx(8) 0;
    }
}

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

.search-bar {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: px2rpx(16);
    margin: px2rpx(16) 0;

    .cwg-combox,
    .uni-easyinput,
    .uni-date {
        width: px2rpx(240) !important;
        flex: none;
    }
}

.expand-btn {
    display: flex;
    align-items: center;
    justify-self: center;
    gap: 4px;
    cursor: pointer;
    width: px2rpx(32);
    height: px2rpx(32);
    justify-content: center;

    .icon {
        transition: transform 0.3s ease;
    }

    &:hover {
        background-color:
            color-mix(in oklab, var(--color-slate-300) 20%, transparent);
    }

    &.expanded {
        background-color:
            color-mix(in oklab, var(--color-slate-300) 20%, transparent);
    }

    &.expanded .icon {
        transform: rotate(180deg);
    }

}

.action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: px2rpx(8);
    justify-content: flex-end;
    padding: px2rpx(16) px2rpx(20);
    background-color: var(--color-slate-100);

    .action-btn {
        display: inline-flex;
        align-items: center;
        height: px2rpx(24);
        padding: 0 px2rpx(16);
        border: none;
        background-color: var(--color-secondary-focus);
        color: var(--color-white);
        font-size: px2rpx(13);
        font-weight: 500;
        cursor: pointer;
        transition: all 0.2s ease;

        .icon {
            margin-right: px2rpx(4);
        }
    }

    .action-btn.disabled {
        cursor: not-allowed;
        opacity: 0.5;
    }
}
</style>
