<template>

    <view class="container">
        <view class="row">
            <view class="col-12">
                <view class="border-0 card-header">
                    <view class="d-flex flex-wrap gap-3 align-items-center justify-content-between mb-3">
                        <h3 class="mb-0" style="align-self: flex-start" v-t="'Custom.Index.AccountList'"></h3>
                        <view type="button" class="btn btn-danger btn-shadow waves-effect cursor-pointer" @click="createAccount">
                            <view class="d-flex align-items-center">
                                <cwg-icon name="crm-plus" :size="14" color="#fff" />
                                <text v-t="'Custom.Index.AddAccount'" />
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <view class="col-lg-12">
                <view class="clearfix">
                    <view class="card">
                        <view class="card-header">
                            <view class="nav nav-underline card-header-tabs">
                                <view class="nav-item cwg-cursor cursor-pointer" v-for="(tab, index) in tabs" :key="index"
                                    @click="handleTabClick(tab.value)">
                                    <view class="nav-link" :class="{ 'active': tab.value === cativeIndex }">{{ tab.text
                                    }}
                                    </view>
                                </view>
                            </view>
                        </view>

                        <view class="card-body">
                            <view class="tab-content">
                                <view class="row mb-4">
                                    <view class="col-lg-4 col-md-6"><cwg-combox v-model:value="platformActive"
                                            :clearable="false" :options="platformOptions" /></view>

                                </view>

                                <view class="row">
                                    <AccountCard v-for="acc in accounts" :zhtype="cativeIndex" :key="acc.accountNumber"
                                        :account="acc" :is-grid-layout="isGridLayout" @action="handleAction"
                                        @copy="handleCopy" @change-password="handleChangePassword" />
                                    <view class="table-loading-mask">
                                        <uni-loading v-if="loading" />
                                    </view>
                                    <view v-if="!loading && accounts.length == 0" class="list-empty-state col-12">
                                        <cwg-empty-state />
                                    </view>
                                    <DeleteAccountDialogs ref="deleteAccountDialogRef"
                                        v-model:visible="deleteAccountDialogVisible" />
                                    <cwg-improve-popup v-model:visible="dialogCheck" @confirm="confirm" />

                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, watch, onUnmounted } 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' })
import useGlobalStore from '@/stores/use-global-store'
const globalStore = useGlobalStore()
const isDark = computed(() => globalStore.theme === 'dark')

const isAfterJuly28 = () => {
    const now = new Date();
    const july28 = new Date(2025, 6, 28, 0, 0, 0); // 月份从0开始，所以7月是6
    return now >= july28;
}
const platformActive = ref('All')
const platformOptions = computed(() => ([
    { value: 'All', text: t('State.All') },
    { value: 'MT4', text: 'MT4' },
    { value: 'MT5', text: 'MT5' },
]))
const handleAction = (type) => { /* 处理交易/入金等 */ };
const handleCopy = (text: string) => {
    uni.setClipboardData({
        data: text,
        success: function () {
            uni.showToast({
                title: t('Btn.item8'),
                icon: 'none',
                duration: 2000
            });
        }
    });
}
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('real')
const isGridLayout = ref(true)
const tabs = computed(() => ([
    { value: 'real', text: t('vu.item1') },
    { value: 'demo', text: t('vu.item2') },
    { value: 'del', text: t('vu.account.item1') },
]))

const toggleLayout = () => {
    isGridLayout.value = !isGridLayout.value
}

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));


const loading = ref(false)
let debounceTimer: ReturnType<typeof setTimeout> | null = null

const handleTabClick = (value: string) => {
    if (loading.value) return
    
    if (debounceTimer) {
        clearTimeout(debounceTimer)
    }
    
    debounceTimer = setTimeout(() => {
        cativeIndex.value = value
        debounceTimer = null
    }, 200)
}

// 获取客户登录信息
const dialogCheck = ref(false)
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}`)
            } else {
                dialogCheck.value = true;
            }
        }
    } catch (error) {
        //  console.log(error, 111);
    }
}

const confirm = () => {
    dialogCheck.value = false;
    router.push(`/pages/mine/improveImmediately`)
}

const AccountList = ref([])
const getAccountList = async () => {
    AccountList.value = []
    loading.value = true
    var api
    switch (cativeIndex.value) {
        case 'real':
            api = customApi.AccountAllList
            break;
        case 'demo':
            api = customApi.demoList
            break;
        case 'del':
            api = customApi.deleteAccountList
            break;
    }
    const res = await api({
        page: {
            current: 1,
            size: 100
        }
    })
    if (res.code === 200) {
        AccountList.value = res.data
    }
    loading.value = false
}
  const groupCurrency1 = (type) => {
      if (type == "GBP") {
        return "£";
      } else if (type == "USD") {
        return "$";
      } else if (type == "EUR") {
        return "€";
      } else if (type == "USC") {
        return "￠";
      } else {
        return "$";
      }
    }
// 格式化数值函数
function formatMoney(value,currency) {
    if (value === null || value === undefined) value = 0;
    const sign = value >= 0 ? '' : '-';
    const absoluteValue = Math.abs(value);
    return groupCurrency1(currency) + sign + numberDecimal(absoluteValue);
}

// 转换数组
const accounts = computed(() => {
    if (!AccountList.value || AccountList.value.length == 0) return []
    let filteredAccounts = AccountList.value
    if (platformActive.value !== 'All') {
        filteredAccounts = filteredAccounts.filter(acc =>
            (acc.platform || 'MT4') === platformActive.value
        )
    }
    return filteredAccounts.map((acc, index) => {
        const currency = acc.currency || 'USD';
        const floating = acc.floating ?? 0;
        let labels = [t('vu.item1'), 'MT4', 'Standard'];
        labels[0] = cativeIndex.value == 'demo' ? t('vu.item2') : t('vu.item1');
        labels[1] = acc.platform || 'MT4';
        labels[2] = typeMap.value[acc.type];
        let nickname = typeMap.value[acc.type];
        let fwq
        if (cativeIndex.value != 'demo') {
            fwq = acc.platform == 'MT4' ? 'CWGMarketsLtd-Live' : 'CWGMarketsSVG-Live';
        } else {
            fwq = acc.platform == 'MT4' ? 'CWGMarketsLtd-Demo' : 'CWGMarketsSVG-Demo';
        }
        const balance = acc.balance
        return {
            ...acc,
            labels,
            isExpanded: index == 0,
            balance,
            accountNumber: acc.login.toString(),
            nickname,
            fwq,
            balanceWithSymbol: acc.balanceWithSymbol ?? '$0.00',
            creditWithSymbol: acc.creditWithSymbol ?? '$0.00',
            equityWithSymbol: acc.equityWithSymbol ?? '$0.00',
            currency,
            actualLeverage: '1:' + (acc.leverage ?? 0),
            floatingPL: acc.floatingWithSymbol ?? '$0.00',
            platform: acc.platform || 'MT4',
            server: acc.groupCode || '',
            login: acc.login.toString(),
            listType: cativeIndex.value
        };
    })
})
onMounted(async () => {
    await getAccountList()
})

onUnmounted(() => {
    if (debounceTimer) {
        clearTimeout(debounceTimer)
    }
})

watch(cativeIndex, (newVal) => {
    // search.value.platform = tabs.value[newVal].id
    getAccountList()
    platformActive.value = 'All'
})
// watch(platformActive, (newVal) => {
//     setAccountList()
// })
</script>

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

.btn {
    margin: 0;
}
</style>
