<!-- src/views/adweb/data/components/HsCodeAnalysis.vue -->
<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>
      <div class="switch-view">
        <a-radio-group v-model:value="viewType" 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="viewType === 'chart'" ref="chartRef" :style="{ height, width }"></div>

      <!-- 列表视图 -->
      <div v-show="viewType === 'table'">
        <a-table :columns="columns" :data-source="tableData" :loading="loading" row-key="fk" :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          pageSizeOptions: ['10', '20'],
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          onShowSizeChange: handleTableChange,
        }" @change="handleTableChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'val'">
              {{ record.val }}
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </a-card>
</template>

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

export default defineComponent({
  props: {
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '350px',
    },
    queryParam: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props) {
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions } = useECharts(chartRef);
    const viewType = ref<'chart' | 'table'>('chart');
    const sortMode = ref('count');
    const loading = ref(false);

    // 格式化函数
    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';
        },
      },
    ];

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

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

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

      const res = await getHsCodeReport(params);
      if (res.result.data.result && res.result.data.result.buckets) {
        chartData = res.result.data.result.buckets;
      }
      if (!chartData.length) return;

      // 取前10条数据展示
      const top10Data = chartData.slice(0, 10);

      const colors = ['#53A2D3', '#FF6B6B', '#4ECDC4', '#45B7AF', '#96CEB4', '#FFEEAD', '#D4A5A5', '#9B59B6', '#3498DB', '#E67E22'];

      // 根据排序方式选择数据
      const seriesData = top10Data.map((item, index) => {
        let value;
        switch (sortMode.value) {
          case 'count':
            value = Number(item.count);
            break;
          case 'weight':
            value = Number(item.sum_weight);
            break;
          case 'amount':
            value = Number(item.sum_amount);
            break;
          default:
            value = 0;
        }
        return {
          value,
          itemStyle: {
            color: colors[index]
          }
        };
      });

      setOptions({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          data: top10Data.map(item => item.val),
          axisLabel: {
            rotate: 45,
          },
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
        },
        yAxis: [
          {
            type: 'value',
            name: sortMode.value === 'count' ? '交易次数' : (sortMode.value === 'weight' ? '交易重量（KG）' : '金额（$）'),
            position: 'left',
            axisLine: {
              lineStyle: {
                color: '#53A2D3',
              },
            },
          }
        ],
        series: [
          {
            name: sortMode.value === 'count' ? '交易次数' : (sortMode.value === 'weight' ? '交易重量' : '交易金额'),
            type: 'bar',
            yAxisIndex: 0,
            data: seriesData,
          }
        ],
      });
    };

    // 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 getHsCodeReport(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,
      () => {
        updateChart();
      },
      { deep: true }
    );

    watch(
      () => sortMode.value,
      () => {
        updateChart();
        handleTableChange(pagination.value, {}, {});
      }
    );

    onMounted(() => {
      updateChart();

    });
    onMounted(async () => {
      // 这里可以添加获取数据的逻辑
      await handleTableChange(pagination.value.current, pagination.value.pageSize, sortMode.value);
    });

    return {
      chartRef,
      viewType,
      sortMode,
      columns,
      tableData,
      formatNumber,
      pagination,
      loading,
      handleTableChange,
      getHsCodeReport
    };
  },
});
</script>

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