<template>
    <a-card title="区域分布">
        <div class="product-container">

            <div class="product-section" v-if="origTableData.length">
                <h3>原产国</h3>
                <div class="switch-view">
                    <a-radio-group v-model:value="viewModeOrigin" 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="viewModeOrigin === 'chart'" ref="origChartRef"
                    :style="{ height: '400px', width: '100%' }"></div>

                <!-- 原产国列表视图 -->
                <div v-show="viewModeOrigin === 'table'">
                    <a-table :columns="originColumns" :data-source="origTableData" :loading="loading" :pagination="{
                        current: origPagination.current,
                        pageSize: origPagination.pageSize,
                        total: origPagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`,
                        onShowSizeChange: handleOrigTableChange,
                    }" @change="handleOrigTableChange">
                        <template #bodyCell="{ column, record, text }">
                            <template v-if="column.dataIndex === 'count'">
                                {{ formatNumber(record[column.dataIndex]) }}
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>

            <div class="divider" v-if="origTableData.length && destTableData.length"></div>

            <div class="product-section" v-if="destTableData.length">
                <h3>目的国</h3>
                <div class="switch-view">
                    <a-radio-group v-model:value="viewModeDestination" 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="viewModeDestination === 'chart'" ref="destChartRef"
                    :style="{ height: '400px', width: '100%' }">
                </div>

                <!-- 目的国列表视图 -->
                <div v-show="viewModeDestination === 'table'">
                    <a-table :columns="destinationColumns" :data-source="destTableData" :loading="loading" :pagination="{
                        current: destPagination.current,
                        pageSize: destPagination.pageSize,
                        total: destPagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`,
                        onShowSizeChange: handleDestTableChange,
                    }" @change="handleDestTableChange">
                        <template #bodyCell="{ column, record, text }">
                            <template v-if="column.dataIndex === 'count'">
                                {{ formatNumber(record[column.dataIndex]) }}
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>

        </div>
    </a-card>
</template>

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

const props = defineProps({
    queryParam: {
        type: Object as PropType<any>,
        default: () => ({}),
    },
    comId: {
        type: String as PropType<string>,
        default: '',
    },
});

const origChartRef = ref<HTMLDivElement | null>(null);
const destChartRef = ref<HTMLDivElement | null>(null);
const { setOptions: setOrigChartOptions } = useECharts(origChartRef as Ref<HTMLDivElement>);
const { setOptions: setDestChartOptions } = useECharts(destChartRef as Ref<HTMLDivElement>);
const origPagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
});
const destPagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
});
const loading = ref(false);
const viewModeOrigin = ref('chart');
const viewModeDestination = ref('chart');

const originColumns = [
    {
        title: '原产国',
        dataIndex: 'val_cn',
        key: 'val_cn',
    },
    {
        title: '交易次数',
        dataIndex: 'count',
        key: 'count',
    }
];

const destinationColumns = [
    {
        title: '目的国',
        dataIndex: 'val_cn',
        key: 'val_cn',
    },
    {
        title: '交易次数',
        dataIndex: 'count',
        key: 'count',
    }
];

// Define the formatNumber function
const formatNumber = (num: string | number) => {
    return Number(num).toLocaleString();
};

const origData = ref([]);
const destData = ref([]);

const updateChart = async () => {

    const origRes = await getRegionDistribution({
        com_id: props.comId,
        com_role: 1,
        ...props.queryParam,
    });
    origData.value = origRes.data.result.as_buyer?.orig_country?.buckets || [];

    const origTotal = origRes.data.result.as_buyer?.count;
    const origOtherCount = origTotal - origData.value.reduce((sum, item) => sum + Number(item.count), 0);

    const destRes = await getRegionDistribution({
        com_id: props.comId,
        com_role: 2,
        ...props.queryParam,
    });
    destData.value = destRes.data.result.as_supplier?.dest_country?.buckets || [];
    const destTotal = destRes.data.result.as_supplier?.count;
    const destOtherCount = destTotal - destData.value.reduce((sum, item) => sum + Number(item.count), 0);
    if (origData.value && origData.value.length) {
        setOrigChartOptions({
            tooltip: {
                trigger: 'item',
                formatter: (params) => {
                    const percent = ((params.value / origTotal) * 100).toFixed(2);
                    return `${params.name}<br/>交易次数: ${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 = origTotal > 0 ? ((params.value / origTotal) * 100).toFixed(2) : 0.00;
                            return `${params.name}\n${percent}%`;
                        },
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 14,
                            fontWeight: 'bold',
                        },
                    },
                    data: [
                        ...origData.value.map((item) => ({
                            name: item.val_cn || item.val,
                            value: Number(item.count),
                        })),
                        {
                            name: '其他',
                            value: origOtherCount,
                        },
                    ],
                }
            ]
        }, true, true);
    };
    if (destData.value && destData.value.length) {
        setDestChartOptions({
            tooltip: {
                trigger: 'item',
                formatter: (params) => {
                    const percent = ((params.value / destTotal) * 100).toFixed(2);
                    return `${params.name}<br/>交易次数: ${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 = destTotal > 0 ? ((params.value / destTotal) * 100).toFixed(2) : 0.00;
                            return `${params.name}\n${percent}%`;
                        },
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: 14,
                            fontWeight: 'bold',
                        },
                    },
                    data: [
                        ...destData.value.map((item) => ({
                            name: item.val_cn || item.val,
                            value: Number(item.count),
                        })),
                        {
                            name: '其他',
                            value: destOtherCount,
                        },
                    ],
                }
            ]
        }, true, true);
    }
}

const totalOrigTransactions = ref(0);
const origTableData = ref([]);
const handleOrigTableChange = async (pag, filters, sorter) => {
    // Ensure pagination data is passed to the API
    const res = await getRegionDistribution({
        page: pag.current,
        page_size: pag.pageSize,
        com_id: props.comId,
        com_role: 1,
        ...props.queryParam,
    });
    if (res.status_code === 200 && res.data.result.as_buyer.count !== 0) {
        origPagination.value.current = pag.current;
        origPagination.value.pageSize = pag.pageSize;
        origPagination.value.total = res.data.result.as_buyer?.orig_country?.numBuckets || 0;
        totalOrigTransactions.value = res.data.result.as_buyer.count || 0;
        origTableData.value = res.data.result.as_buyer.orig_country?.buckets.map(item => ({
            ...item
        }));
    }
}

const totalDestTransactions = ref(0);
const destTableData = ref([]);
const handleDestTableChange = async (pag, filters, sorter) => {
    const res = await getRegionDistribution({
        page: pag.current,
        page_size: pag.pageSize,
        com_id: props.comId,
        com_role: 2,
        ...props.queryParam,
    });
    if (res.status_code === 200 && res.data.result.as_supplier.count !== 0) {
        destPagination.value.current = pag.current;
        destPagination.value.pageSize = pag.pageSize;
        destPagination.value.total = res.data.result.as_supplier?.dest_country?.numBuckets || 0;
        totalDestTransactions.value = res.data.result.as_supplier.count || 0;
        destTableData.value = res.data.result.as_supplier.dest_country?.buckets.map(item => ({
            ...item
        }));
    }
}
const resetData = () => {
    origData.value = [];
    destData.value = [];
    origTableData.value = [];
    destTableData.value = [];
    origPagination.value = { current: 1, pageSize: 10, total: 0 };
    destPagination.value = { current: 1, pageSize: 10, total: 0 };
    totalOrigTransactions.value = 0;
    totalDestTransactions.value = 0;
}
watch(
    () => props.queryParam,
    () => {
        resetData();
        updateChart();
        handleOrigTableChange(origPagination.value, {}, {});
        handleDestTableChange(destPagination.value, {}, {});
    },
    { deep: true }
);

watch(() => props.comId,
    () => {
        viewModeOrigin.value = 'chart';
        viewModeDestination.value = 'chart';
        resetData();
        updateChart();
        handleOrigTableChange(origPagination.value, {}, {});
        handleDestTableChange(destPagination.value, {}, {});
    },
    { deep: true }
);

onMounted(() => {
    handleOrigTableChange(origPagination.value, {}, {});
    handleDestTableChange(destPagination.value, {}, {});
    updateChart();
});
</script>

<style scoped>
.product-container {
    display: flex;
    justify-content: space-between;
}

.product-section {
    width: 48%;
    /* Adjust width as needed */
}

.switch-view {
    text-align: right;
    margin-bottom: 16px;
}

/* 新增竖线分割样式 */
.divider {
    width: 1px;
    /* 竖线的宽度 */
    background-color: #ccc;
    /* 竖线的颜色 */
    height: auto;
    /* 根据内容自动调整高度 */
    margin: 0 16px;
    /* 左右间距 */
}
</style>