<template>
    <a-card title="产品">
        <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="product-container">

            <div class="product-section" v-if="importTableData.length > 0">
                <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="exportTableData.length > 0 && importTableData.length > 0"></div>

            <div class="product-section" v-if="exportTableData.length > 0">
                <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="columns" :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, onUnmounted } from 'vue';
import { useECharts } from '/@/hooks/web/useECharts';
import { getCompanyHsCode } from '../customsData.api';

export default defineComponent({
    props: {
        width: {
            type: String as PropType<string>,
            default: '100%',
        },
        height: {
            type: String as PropType<string>,
            default: '350px',
        },
        queryParam: {
            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 importViewType = ref<'chart' | 'table'>('chart');
        const exportViewType = ref<'chart' | 'table'>('chart');
        const importChartData = ref<any[]>([]);
        const exportChartData = ref<any[]>([]);
        const sortMode = ref('count');
        // 新增进口视图类型
        const importPagination = ref({
            current: 1,
            pageSize: 10,
            total: 0,
        });
        const exportPagination = ref({
            current: 1,
            pageSize: 10,
            total: 0,
        });

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

        // 表格列定义
        const columns = [
            {
                title: 'HS编码',
                dataIndex: 'val',
                key: 'val',
            },
            {
                title: '重量（KG）',
                dataIndex: 'sum_weight',
                key: 'sum_weight',
                customRender: ({ text }) => formatNumber(text),
            },
            {
                title: '金额（$）',
                dataIndex: 'sum_amount',
                key: 'sum_amount',
                customRender: ({ text }) => formatNumber(text),
            },
            {
                title: '交易次数',
                dataIndex: 'count',
                key: 'count',
                customRender: ({ text }) => {
                    return text ? Number(text).toLocaleString('en-US') : '0';
                },
            },
            {
                title: '百分比',
                dataIndex: 'percent',
                key: 'percent',

            }
        ];

        const updateImportChart = async () => {
            const params1 = {
                sort: sortMode.value,
                com_id: props.comId,
                com_role: 1,
                ...props.queryParam,
            };
            const res = await getCompanyHsCode(params1);
            importChartData.value = res.data.result.as_buyer?.hs_code?.buckets || [];
            if (importChartData.value.length) {
                setImportChartOptions({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow',
                        },
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true,
                    },
                    xAxis: {
                        type: 'category',
                        data: importChartData.value.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.value.map(item => item.count),
                        }
                    ],
                }, true, true);
            }
        };

        const updateExportChart = async () => {
            const params2 = {
                sort: sortMode.value,
                com_id: props.comId,
                com_role: 2,
                ...props.queryParam,
            };
            const res2 = await getCompanyHsCode(params2);
            exportChartData.value = res2.data.result.as_supplier?.hs_code?.buckets || [];
            if (exportChartData.value.length) {
                setExportChartOptions({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow',
                        },
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true,
                    },
                    xAxis: {
                        type: 'category',
                        data: exportChartData.value.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.value.map(item => item.count),
                            itemStyle: {
                                color: 'yellow'
                            }
                        }
                    ],
                }, true, true);
            }
        };

        // 计算进口表格数据
        const importTableData = ref([]);
        async function handleImportTableChange(pag, filters, sorter) {
            // Ensure pagination data is passed to the API
            const res = await getCompanyHsCode({
                sort: sortMode.value,
                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.hs_code?.numBuckets || 0;
                totalImportTransactions.value = res.data.result.as_buyer.count || 0;
                importTableData.value = res.data.result.as_buyer.hs_code?.buckets?.map(item => ({
                    ...item,
                    percent: ((item.count / totalImportTransactions.value) * 100).toFixed(2) + '%',
                }));
            }
        }

        // 计算出口表格数据
        const exportTableData = ref([]);
        async function handleExportTableChange(pag, filters, sorter) {
            // Ensure pagination data is passed to the API
            const res = await getCompanyHsCode({
                sort: sortMode.value,
                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.hs_code.numBuckets || 0;
                totalExportTransactions.value = res.data.result.as_supplier.count || 0;
                exportTableData.value = res.data.result.as_supplier.hs_code.buckets.map(item => ({
                    ...item,
                    percent: ((item.count / totalExportTransactions.value) * 100).toFixed(2) + '%',
                }));
            }
        };

        // Watch for changes in sortMode to update data
        watch(sortMode, () => {
            resetData();
            updateImportChart();
            handleImportTableChange(importPagination.value, {}, {});
            updateExportChart();
            handleExportTableChange(exportPagination.value, {}, {});
        });

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

        watch(() => props.comId,
            () => {
                importViewType.value = 'chart';
                exportViewType.value = 'chart';
                resetData();
                updateImportChart();
                handleImportTableChange(importPagination.value, {}, {});
                updateExportChart();
                handleExportTableChange(exportPagination.value, {}, {});
            },
            { deep: 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;
        };

        // Load data when the component is mounted
        onMounted(() => {
            importViewType.value = 'chart';
            exportViewType.value = 'chart';
            resetData();
            updateImportChart();
            handleImportTableChange(importPagination.value, {}, {});
            updateExportChart();
            handleExportTableChange(exportPagination.value, {}, {});
        });

        // Reset data when the component is unmounted
        onUnmounted(() => {
            resetData();
        });

        // Computed properties to calculate total transactions for import and export
        const totalImportTransactions = ref(0);
        const totalExportTransactions = ref(0);

        return {
            importChartRef,
            exportChartRef,
            columns,
            formatNumber,
            importViewType,
            exportViewType,
            importTableData,
            exportTableData,
            sortMode,
            importPagination,
            exportPagination,
            handleImportTableChange,
            handleExportTableChange,
            getCompanyHsCode,
            totalImportTransactions,
            totalExportTransactions,
            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>