<template>
    <a-card title="目的港" :loading="loading">
        <!-- 添加切换按钮组 -->
        <template #extra>
            <span>排序：</span>
            <a-radio-group v-model:value="sortMode" button-style="solid" style="margin-left: 16px;">
                <a-radio-button value="count">交易次数</a-radio-button>
                <a-radio-button value="weight">交易重量</a-radio-button>
                <a-radio-button value="amount">交易金额</a-radio-button>
            </a-radio-group>
        </template>
        <!-- 添加切换按钮组 -->
        <div class="switch-view">
            <a-radio-group v-model:value="viewMode" button-style="solid">
                <a-radio-button value="chart">图表</a-radio-button>
                <a-radio-button value="table">列表</a-radio-button>
            </a-radio-group>
        </div>
        <!-- 图表视图 -->
        <div v-show="viewMode === 'chart'" ref="chartRef" :style="{ height, width }"></div>
        <!-- 表格视图 -->
        <a-table v-show="viewMode === 'table'" :columns="columns" :data-source="tableData" :pagination="{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            pageSizeOptions: ['10', '20'],
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            onShowSizeChange: handleTableChange,
        }" @change="handleTableChange" size="middle">
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'count' || column.dataIndex === 'num_supplier'">
                    {{ formatNumber(record[column.dataIndex]) }}
                </template>
                <template v-if="column.dataIndex === 'sum_weight' || column.dataIndex === 'sum_amount'">
                    {{ formatDecimal(record[column.dataIndex]) }}
                </template>
            </template>
        </a-table>
    </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, Ref, nextTick } from 'vue';
import { useECharts } from '/@/hooks/web/useECharts';
import { getDestPortReport } from '../customsData.api';

const chartRef = ref<HTMLDivElement | null>(null);
const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);

const props = defineProps({
    queryParam: {  // 修改属性名
        type: Object,
        required: true
    },
    width: {
        type: String as PropType<string>,
        default: '100%',
    },
    height: {
        type: String as PropType<string>,
        default: 'calc(50vh - 78px)',
    },
});

const loading = ref(false);
const viewMode = ref('chart');
const sortMode = ref('count');
const allBuckets = ref({});

// 定义表格列
const columns = [
    {
        title: '目的港',
        dataIndex: 'val',
        key: 'val',
    },
    {
        title: '采购商数量',
        dataIndex: 'num_buyer',
        key: 'num_buyer',
        sorter: (a, b) => Number(a.num_buyer) - Number(b.num_buyer),
    },
    {
        title: '重量(KG)',
        dataIndex: 'sum_weight',
        key: 'sum_weight',
        sorter: (a, b) => Number(a.sum_weight) - Number(b.sum_weight),
    },
    {
        title: '金额($)',
        dataIndex: 'sum_amount',
        key: 'sum_amount',
        sorter: (a, b) => Number(a.sum_amount) - Number(b.sum_amount),
    },
    {
        title: '交易次数',
        dataIndex: 'count',
        key: 'count',
    },
    {
      title: '百分比', // 新增百分比列
      dataIndex: 'percentage',
      key: 'percentage',
      customRender: ({ record }) => {
        const percent = (() => {
          const valueKeyMap = {
            count: 'count',
            weight: 'sum_weight',
            amount: 'sum_amount',
          };
          const totalKeyMap = {
            count: 'count',
            weight: 'weight_sum',
            amount: 'amount_sum',
          };

          const selectedValue = record[valueKeyMap[sortMode.value]];
          const total = allBuckets.value[totalKeyMap[sortMode.value]] || 0;

          return total > 0 && selectedValue > 0 ? ((selectedValue / total) * 100).toFixed(2) : 0.0;
        })();

        return `${percent}%`;
      },
    },
];

// 格式化整数
const formatNumber = (num: string | number) => {
    return Number(num).toLocaleString();
};

// 格式化小数（保留两位）
const formatDecimal = (num: string | number) => {
    return Number(num).toLocaleString(undefined, {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
};

// 计算表格数据
const tableData = ref([]);

const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
});

const initChart = () => {
    if (!chartRef.value) return;
    updateChart();
};

const updateChart = async () => {
    let chartData = [];
    const params = {
        sort: sortMode.value,
        page: 1,
        page_size: 10,
        ...props.queryParam,
    };

    try {
        const res = await getDestPortReport(params);
        if (res.result.data.result && res.result.data.result.buckets) {
            chartData = res.result.data.result.buckets;
            allBuckets.value = res.result.data.result.allBuckets;
        }

        if (chartData.length === 0) {
            console.warn('No data available for chart');
            return;
        }

        const valueKeyMap = {
            count: 'count',
            weight: 'sum_weight',
            amount: 'sum_amount'
        };

        const totalKeyMap = {
            count: 'count',
            weight: 'weight_sum',
            amount: 'amount_sum'
        };

        const total = allBuckets.value[totalKeyMap[sortMode.value]] || 0;
        const data = chartData.sort((a, b) => Number(b[valueKeyMap[sortMode.value]]) - Number(a[valueKeyMap[sortMode.value]]));

        const otherCount = total - data.reduce((sum, item) => sum + Number(item[valueKeyMap[sortMode.value]]), 0);

        const option = {
            tooltip: {
                trigger: 'item',
                formatter: (params) => {
                    const percent = total > 0 ? ((params.value / total) * 100).toFixed(2) : 0.00;
                    return `${params.name}<br/>${sortMode.value === 'count' ? '交易次数' : sortMode.value === 'weight' ? '交易重量' : '交易金额'}: ${formatNumber(params.value)}<br/>占比: ${percent}%`;
                }
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                type: 'scroll'
            },
            series: [
                {
                    name: '交易次数',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: true,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: true,
                        formatter: (params) => {
                            const percent = total > 0 ? ((params.value / total) * 100).toFixed(2) : 0.00;
                            return `${params.name}\n${percent}%`;
                        }
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 14,
                            fontWeight: 'bold'
                        }
                    },
                    data: [
                        ...data.map(item => ({
                            name: item.val_cn || item.val,
                            value: Number(item[valueKeyMap[sortMode.value]])
                        })),
                        {
                            name: '其他',
                            value: otherCount
                        }
                    ]
                }
            ]
        };

        nextTick(() => {
            setOptions(option, true, true); // Ensure options are set after DOM updates
        });
    } catch (error) {
        console.error('Failed to update chart:', error);
    }
};

// Replace registerTransactionTable with this new method
const handleTableChange = async (pag, filters, sorter) => {
    loading.value = true;
    try {
        const params = {
            sort: sortMode.value,
            page: pag.current,
            page_size: pag.pageSize,
            ...props.queryParam,
        };

        const res = await getDestPortReport(params);
        if (res.result.data.result && res.result.data.result.buckets) {
            pagination.value = {
                current: pag.current,
                pageSize: pag.pageSize,
                total: res.result.data.result.numBuckets || 0,
            };
            tableData.value = res.result.data.result.buckets;

        }
    } catch (error) {
        console.error('Failed to fetch data:', error);
    } finally {
        loading.value = false;
    }
};

// 监听数据变化
watch(
    () => props.queryParam,
    () => {
        if (viewMode.value === 'chart') {
            updateChart();
        } else {
            handleTableChange(pagination.value, {}, {});
        }
    },
    { deep: true }
);

// 监听视图模式变化
watch(viewMode, (newValue) => {
    if (newValue === 'chart') {
        updateChart();
    } else {
        handleTableChange(pagination.value, {}, {});
    }
});

watch(sortMode, () => {
    if (viewMode.value === 'chart') {
        updateChart();
    } else {
        handleTableChange(pagination.value, {}, {});
    }
});

onMounted(() => {
    if (viewMode.value === 'chart') {
        initChart();
    }
});

</script>

<style scoped>
.ant-card {
    margin-bottom: 24px;
}

:deep(.ant-table-pagination) {
    margin: 16px 0;
}

.switch-view {
    margin-bottom: 16px;
}
</style>