<template>
  <a-card title="月度趋势">
    <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" :pagination="false">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'date'">
              {{ record.date }}
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </a-card>
</template>

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

export default defineComponent({
  props: {
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: '350px',
    },
    monthlyTrendData:{
      default: () => ({}),
    },
  },
  setup(props) {
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
    const viewType = ref<'chart' | 'table'>('chart');

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

    // 日期格式化函数
    const formatDate = (dateStr: string) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
    };

    // 表格列定义
    const columns = [
      {
        title: '日期',
        dataIndex: 'val',
        key: 'val',
        customRender: ({ text }) => text === '合计' ? text : formatDate(text),
      },
      {
        title: '供应商',
        dataIndex: 'num_supplier',
        key: 'num_supplier',
        customRender: ({ text }) => {
          return text ? text.toLocaleString('en-US') : '0';
        },
      },
      {
        title: '采购商',
        dataIndex: 'num_buyer',
        key: 'num_buyer',
        customRender: ({ text }) => {
          return text ? text.toLocaleString('en-US') : '0';
        },
      },
      {
        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 ? text.toLocaleString('en-US') : '0';
        },
      },
    ];

    // 计算表格数据
    const tableData = computed(() => {
      const data = props.monthlyTrendData;
      const total = {
        val: '合计',
        num_supplier: data.reduce((sum, item) => sum + (item.num_supplier || 0), 0),
        num_buyer: data.reduce((sum, item) => sum + (item.num_buyer || 0), 0),
        sum_weight: data.reduce((sum, item) => sum + (item.sum_weight || 0), 0),
        sum_amount: data.reduce((sum, item) => sum + (item.sum_amount || 0), 0),
        count: data.reduce((sum, item) => sum + (item.count || 0), 0),
      };
      return [...data, total]; // 添加合计行
    });

    const updateChart = () => {
      const chartData = props.monthlyTrendData;
      
      setOptions({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            label: {
              show: true,
              backgroundColor: '#333',
            },
          },
        },
        legend: {
          data: ['供应商数量', '采购商数量', '交易次数'],
          textStyle: {
            color: '#ccc',
          },
        },
        xAxis: {
          type: 'category',
          data: chartData.map(item => formatDate(item.val)),
          axisLine: {
            lineStyle: {
              color: '#ccc',
            },
          },
        },
        yAxis: [
          {
            type: 'value',
            name: '数量',
            splitLine: { show: true },
            axisLine: {
              lineStyle: {
                color: '#ccc',
              },
            },
          },
          {
            type: 'value',
            name: '交易次数',
            splitLine: { show: false },
            axisLine: {
              lineStyle: {
                color: '#ccc',
              },
            },
          }
        ],
        series: [
          {
            name: '供应商数量',
            type: 'line',
            yAxisIndex: 0,
            smooth: false,
            symbol: 'circle',
            showAllSymbol: 'auto',
            symbolSize: 6,
            lineStyle: {
              color: '#53A2D3',
            },
            itemStyle: {
              color: '#53A2D3',
            },
            data: chartData.map(item => item.num_supplier),
          },
          {
            name: '采购商数量',
            type: 'line',
            yAxisIndex: 0,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#FF951A',
            },
            itemStyle: {
              color: '#FF951A',
            },
            data: chartData.map(item => item.num_buyer),
          },
          {
            name: '交易次数',
            type: 'line',
            yAxisIndex: 1,
            symbol: 'circle',
            z: -12,
            lineStyle: {
              color: '#399C5C',
            },
            itemStyle: {
              color: '#399C5C',
            },
            data: chartData.map(item => item.count),
          }
        ],
      });
    };

    watch(
      () => props.monthlyTrendData,
      () => {
        updateChart();
      },
      { deep: true }
    );

    onMounted(() => {
      updateChart();
    });

    return {
      chartRef,
      viewType,
      columns,
      tableData,
      formatNumber,
    };
  },
});
</script>

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