<template>
    <a-card title="贸易伙伴">
        <div class="product-container">

            <div class="product-section" v-if="importTableData.length">
                <h3>供应商</h3>
                <div class="switch-view">
                    <a-radio-group v-model:value="importViewType" 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="importViewType === 'chart'" ref="importChartRef" :style="{ height, width }"></div>

                <!-- 进口列表视图 -->
                <div v-show="importViewType === 'table'">
                    <a-table :columns="columns" :data-source="importTableData" :pagination="{
                        current: importPagination.current,
                        pageSize: importPagination.pageSize,
                        total: importPagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`,
                        onShowSizeChange: handleImportTableChange,
                    }" @change="handleImportTableChange">
                        <template #bodyCell="{ column, record }">
                            <template v-if="column.dataIndex === 'val'">
                                {{ record.val }}
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>

            <!-- 竖线分割 -->
            <div class="divider" v-if="importTableData.length && exportTableData.length"></div>

            <div class="product-section" v-if="exportTableData.length">
                <h3>采购商</h3>
                <div class="switch-view">
                    <a-radio-group v-model:value="exportViewType" 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="exportViewType === 'chart'" ref="exportChartRef" :style="{ height, width }"></div>

                <!-- 出口列表视图 -->
                <div v-show="exportViewType === 'table'">
                    <a-table :columns="buyerColumns" :data-source="exportTableData" :pagination="{
                        current: exportPagination.current,
                        pageSize: exportPagination.pageSize,
                        total: exportPagination.total,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        showTotal: (total) => `共 ${total} 条`,
                        onShowSizeChange: handleExportTableChange,
                    }" @change="handleExportTableChange" size="middle">
                        <template #bodyCell="{ column, record }">
                            <template v-if="column.dataIndex === 'val'">
                                {{ record.val }}
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>

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

<script lang="ts">
import { defineComponent, PropType, ref, Ref, onMounted, watch, computed, onUpdated } from 'vue';
import { useECharts } from '/@/hooks/web/useECharts';
import { getCompanyPartner } from '../customsData.api';

export default defineComponent({
    props: {
        width: {
            type: String as PropType<string>,
            default: '100%',
        },
        height: {
            type: String as PropType<string>,
            default: '350px',
        },
        queryParam: {
            type: Object as PropType<any>,
            default: () => ({}),
        },
        comId: {
            type: String as PropType<string>,
            default: '',
        },
    },
    setup(props) {
        const importChartRef = ref<HTMLDivElement | null>(null);
        const exportChartRef = ref<HTMLDivElement | null>(null);
        const { setOptions: setImportChartOptions } = useECharts(importChartRef as Ref<HTMLDivElement>);
        const { setOptions: setExportChartOptions } = useECharts(exportChartRef as Ref<HTMLDivElement>);
        const importPagination = ref({
            current: 1,
            pageSize: 10,
            total: 0,
        });
        const exportPagination = ref({
            current: 1,
            pageSize: 10,
            total: 0,
        });

        const totalImportTransactions = ref(0);
        const totalExportTransactions = ref(0);
        const importChartData = ref([]);
        const exportChartData = ref([]);

        // 格式化函数
        const formatNumber = (value: string | number) => {
            if (!value) return '0.00';
            return Number(value).toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
            });
        };

        // 表格列定义
        const columns = [
            {
                title: '供应商',
                dataIndex: 'val',
                key: 'val',
            },
            {
                title: '交易次数',
                dataIndex: 'count',
                key: 'count',
                customRender: ({ text }) => {
                    return text ? Number(text).toLocaleString('en-US') : '0';
                },
            },
        ];

        const buyerColumns = [
            {
                title: '采购商',
                dataIndex: 'val',
                key: 'val',
            },
            {
                title: '交易次数',
                dataIndex: 'count',
                key: 'count',
                customRender: ({ text }) => {
                    return text ? Number(text).toLocaleString('en-US') : '0';
                },
            },
        ];

        async function handleImportTableChange(pag, filters, sorter) {
            // Ensure pagination data is passed to the API
            const res = await getCompanyPartner({
                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) {
                importPagination.value.current = pag.current;
                importPagination.value.pageSize = pag.pageSize;
                importPagination.value.total = res.data.result.as_buyer.supplier?.numBuckets || 0;
                totalImportTransactions.value = res.data.result.as_buyer.count || 0;
                importTableData.value = res.data.result.as_buyer.supplier?.buckets?.map(item => ({
                    ...item
                }));
            }
        }

        async function handleExportTableChange(pag, filters, sorter) {
            // Ensure pagination data is passed to the API
            const res = await getCompanyPartner({
                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) {
                exportPagination.value.current = pag.current;
                exportPagination.value.pageSize = pag.pageSize;
                exportPagination.value.total = res.data.result.as_supplier.buyer?.numBuckets || 0;
                totalExportTransactions.value = res.data.result.as_supplier.count || 0;
                exportTableData.value = res.data.result.as_supplier.buyer?.buckets?.map(item => ({
                    ...item
                }));
            }
        };

        const updateChart = async () => {
            const importRes = await getCompanyPartner({
                com_id: props.comId,
                com_role: 1,
                ...props.queryParam,
            });
            const importChartData = importRes.data.result.as_buyer.supplier?.buckets?.map(item => ({
                ...item
            }));
            const exportRes = await getCompanyPartner({
                com_id: props.comId,
                com_role: 2,
                ...props.queryParam,
            });
            const exportChartData = exportRes.data.result.as_supplier.buyer?.buckets?.map(item => ({
                ...item
            }));

            if (importChartData && importChartData.length) {
                setImportChartOptions({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow',
                        },
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true,
                    },
                    xAxis: {
                        type: 'category',
                        data: importChartData.map(item => item.val),
                        axisLabel: {
                            rotate: 45,
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#ccc',
                            },
                        },
                    },
                    yAxis: [
                        {
                            type: 'value',
                            name: '交易次数',
                            position: 'left',
                            axisLine: {
                                lineStyle: {
                                    color: '#53A2D3',
                                },
                            },
                        }
                    ],
                    series: [
                        {
                            name: '交易次数',
                            type: 'bar',
                            data: importChartData.map(item => item.count),
                        }
                    ],
                }, true, true);
            }

            if (exportChartData && exportChartData.length) {
                setExportChartOptions({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow',
                        },
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true,
                    },
                    xAxis: {
                        type: 'category',
                        data: exportChartData.map(item => item.val),
                        axisLabel: {
                            rotate: 45,
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#ccc',
                            },
                        },
                    },
                    yAxis: [
                        {
                            type: 'value',
                            name: '交易次数',
                            position: 'left',
                            axisLine: {
                                lineStyle: {
                                    color: '#53A2D3',
                                },
                            },
                        }
                    ],
                    series: [
                        {
                            name: '交易次数',
                            type: 'bar',
                            data: exportChartData.map(item => item.count),
                            itemStyle: {
                                color: 'yellow'
                            }
                        }
                    ],
                }, true, true);
            }
        };

        // Reset data to default values
        const resetData = () => {
            importChartData.value = [];
            exportChartData.value = [];
            importTableData.value = [];
            exportTableData.value = [];
            importPagination.value = { current: 1, pageSize: 10, total: 0 };
            exportPagination.value = { current: 1, pageSize: 10, total: 0 };
            totalImportTransactions.value = 0;
            totalExportTransactions.value = 0;
        };

        watch(() => props.queryParam,
            () => {
                importViewType.value = 'chart';
                exportViewType.value = 'chart';
                resetData();
                updateChart();
                handleImportTableChange(importPagination.value, {}, {});
                handleExportTableChange(exportPagination.value, {}, {});
            },
            { deep: true }
        );

        watch(() => props.comId,
            () => {
                importViewType.value = 'chart';
                exportViewType.value = 'chart';
                resetData();
                updateChart();
                handleImportTableChange(importPagination.value, {}, {});
                handleExportTableChange(exportPagination.value, {}, {});
            },
            { deep: true }
        );

        onMounted(() => {
            handleImportTableChange(importPagination.value, {}, {});
            handleExportTableChange(exportPagination.value, {}, {});
            updateChart();
        });

        // 新增进口视图类型
        const importViewType = ref<'chart' | 'table'>('chart');
        const exportViewType = ref<'chart' | 'table'>('chart');

        // 计算进口表格数据
        const importTableData = ref([]);

        // 计算出口表格数据
        const exportTableData = ref([]);

        return {
            importChartRef,
            exportChartRef,
            columns,
            buyerColumns,
            formatNumber,
            importViewType,
            exportViewType,
            importTableData,
            exportTableData,
            importPagination,
            exportPagination,
            handleImportTableChange,
            handleExportTableChange,
            updateChart,
            importChartData,
            exportChartData,
        };
    },
});
</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>