<template>
    <cwg-page-wrapper class="create-page" :isHeaderFixed="true">
        <cwg-header :title="t('Home.page_ib.item3')" />
        <view class="info-card">
            <cwg-complex-search :fields="filterFields" v-model="searchParams" @search="handleSearch"
                @reset="handleReset" />
            <cwg-tabel ref="tableRef" :columns="currentColumns" :immediate="false" :queryParams="queryParams" :api="listApi"
                :show-operation="false" :showSummary="true" :summaryMethod="getSummaries">
                <template #equity="{ row }">
                    <view class="equity-cell">
                        <view class="start-equity">{{ formatNumberAll(row.startEquity || '0') }}</view>
                        <view class="end-equity">{{ formatNumberAll(row.endEquity || '0') }}</view>
                    </view>
                </template>
            </cwg-tabel>
        </view>
    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { computed, ref, nextTick, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { documentaryApi } from '@/service/documentary';
import { ibApi } from '@/service/ib';

const { t } = useI18n();

// 搜索参数
const searchParams = ref<any>({
    type: 1,
    agentId: '',
    followLogin: '',
    dealLogin: '',
    date: []
});

const agentLevels = ref<Array<{ key: string, options: any[] }>>([
    {
        key: 'agentId_0',
        options: [
            { value: 0, text: t('news_add_field.IbReport.ALL') },
            { value: -1, text: t('news_add_field.IbReport.DirectlyUnder') },
        ],
    },
]);

const filterFields = ref<any[]>([]);

// 处理传给表格的参数
const queryParams = computed(() => {
    let finalAgentId = searchParams.value.agentId_0 || '';
    for (let i = agentLevels.value.length - 1; i >= 0; i--) {
        const val = searchParams.value[`agentId_${i}`];
        if (val !== undefined && val !== '') {
            finalAgentId = val;
            break;
        }
    }
    
    return {
        type: searchParams.value.type,
        agentId: finalAgentId || '',
        followLogin: searchParams.value.followLogin || '',
        dealLogin: searchParams.value.dealLogin || '',
        date: searchParams.value.date || []
    };
});

const handleAgentChange = async (val: any, levelIndex: number) => {
    // 截断当前层级之后的所有层级
    agentLevels.value.splice(levelIndex + 1);

    // 清理 searchParams 中被移除层级的值
    for (let key in searchParams.value) {
        if (key.startsWith('agentId_')) {
            const idx = parseInt(key.split('_')[1]);
            if (idx > levelIndex) {
                delete searchParams.value[key];
            }
        }
    }
    handleSearch();
    
    if (val === 0 || val === -1 || val === '') {
        return;
    }

    try {
        const res = await ibApi.ibTree({ pid: val });
        if (res.code === 200 && res.data && res.data.length > 0) {
            const nextOptions: any[] = [];
            res.data.forEach((item: any) => {
                if (item.ibNo) {
                    nextOptions.push({
                        value: item.id,
                        text: item.name ? `${item.ibNo} - ${item.name}` : item.ibNo,
                    });
                }
            });
            if (nextOptions.length > 0) {
                agentLevels.value.push({
                    key: `agentId_${levelIndex + 1}`,
                    options: nextOptions,
                });
            }
        }
        setFields();
    } catch (error) {
        console.error(error);
    }
};

const searchIbTree = async () => {
    try {
        const res = await ibApi.ibTree({ pid: 0 });
        if (res.code === 200 && res.data) {
            res.data.forEach((item: any) => {
                if (item.ibNo) {
                    agentLevels.value[0].options.push({
                        value: item.id,
                        text: item.name ? `${item.ibNo} - ${item.name}` : item.ibNo,
                    });
                }
            });
        }
    } catch (e) {
        console.error(e);
    }
};

const setFields = () => {
    const fields: any[] = [
        { key: 'dealLogin', type: 'input', placeholder: t('Documentary.TundManagement.item11') },
        { key: 'followLogin', type: 'input', placeholder: t('Documentary.console.item28') },
    ];
    
    agentLevels.value.forEach((level, index) => {
        fields.push({
            key: level.key,
            type: 'select',
            label: t('State.All'),
            options: level.options,
            placeholder: t('State.All'),
            onChange: (val: any) => handleAgentChange(val, index),
            defaultValue: index === 0 ? 0 : '',
        });
    });
    
    fields.push({ key: 'date', label: t('placeholder.Start') + ' - ' + t('placeholder.End'), type: 'daterange' });
    filterFields.value = fields;
};

onMounted(async () => {
    await searchIbTree();
    setFields();
});

const tableRef = ref();

const handleSearch = () => {
    nextTick(() => {
        tableRef.value?.refreshTable();
    });
};

const handleReset = () => {
    agentLevels.value.splice(1);
    searchParams.value = {
        type: 1,
        agentId: '',
        followLogin: '',
        dealLogin: '',
        date: []
    };
    setFields();
    nextTick(() => {
        tableRef.value?.refreshTable();
    });
};

// 工具方法
const NumberDesensitization = (value: any) => {
    if (!value) return '--';
    const str = String(value);
    if (str.length > 4) {
        return str.substring(0, 2) + '***' + str.substring(str.length - 2);
    }
    return str;
};

const formatNumberAll = (value: any) => {
    if (value === "***") return "***";
    if (isNaN(value)) return '0';
    let value1 = value.toString();
    const isNegative = value1.indexOf("-") > -1;
    if (isNegative) value1 = value1.split("-")[1];

    let num = value1.split(".");
    let interCount = num[0].length;
    if (interCount < 3) {
        return isNegative ? "-" + value1 : value1;
    }
    let index = 0;
    let inter = "";
    for (let i = interCount - 3; i >= 0; i -= 3) {
        inter = num[0].substr(i, 3) + (inter == "" ? "" : ",") + inter;
        index = i;
    }
    if (index > 0) {
        inter = num[0].substr(0, index) + (inter == "" ? "" : ",") + inter;
    }
    const formatted = inter + (num.length == 1 ? "" : "." + num[1]);
    return isNegative ? "-" + formatted : formatted;
};

const groupCurrency1 = (type: string) => {
    if (type === "GBP") return "£";
    if (type === "USD") return "$";
    if (type === "EUR") return "€";
    if (type === "USC") return "￠";
    return "$";
};

const currentColumns = computed(() => [
    {
        prop: 'dealLogin',
        label: t('Documentary.tradingCenter.item18'),
        align: 'left',
        formatter: ({ row }: any) => NumberDesensitization(row.dealLogin)
    },
    {
        prop: 'followLogin',
        label: t('Documentary.console.item28'),
        align: 'left',
        formatter: ({ row }: any) => row.followLogin || '--'
    },
    {
        prop: 'dealCommission',
        label: t('Documentary.Report.item4'),
        align: 'left',
        formatter: ({ row }: any) => formatNumberAll(row.dealCommission || '0')
    },
    {
        prop: 'dealRatio',
        label: t('Documentary.Report.item5'),
        align: 'left',
        formatter: ({ row }: any) => row.dealRatio || '0%'
    },
    {
        prop: 'agentCommission',
        label: t('Documentary.Report.item8'),
        align: 'left',
        formatter: ({ row }: any) => `${groupCurrency1(row.currency)}${formatNumberAll(row.agentCommission || '0')}`
    },
    {
        prop: 'agentRatio',
        label: t('Documentary.Report.item7'),
        align: 'left',
        formatter: ({ row }: any) => row.agentRatio || '0%'
    },
    {
        prop: 'equity',
        label: t('Documentary.Report.item17') + ' / ' + t('Documentary.Report.item18'),
        align: 'left',
        slot: 'equity'
    }
]);

const getSummaries = (param: any) => {
    const { columns, summaryData } = param;
    const sums: string[] = [];
    if (!summaryData || Object.keys(summaryData).length === 0) return sums;

    columns.forEach((column: any, index: number) => {
        if (index === 0) {
            sums[index] = t('Label.Total');
            return;
        }

        const prop = column.prop;
        if (!prop) {
            sums[index] = '';
            return;
        }

        if (['dealCommission', 'agentCommission'].includes(prop)) {
            sums[index] = summaryData[prop] ? formatNumberAll(summaryData[prop]) : '0';
        } else {
            sums[index] = '';
        }
    });

    return sums;
};

const listApi = ref(documentaryApi.followReportCommission);
</script>

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

.equity-cell {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: px2rpx(4);
    
    .start-equity, .end-equity {
        font-size: px2rpx(14);
        line-height: 1.2;
    }
    
    .end-equity {
        color: var(--color-slate-500);
    }
}
</style>
