<template>
  <div class="order-statistics">
    <a-space direction="vertical" size="large" fill>
      <!-- 订单统计卡片 -->
      <!-- <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>今日订单数</template>
            <div class="stat-value text-primary">
              {{ formatNumber(orderData.todayOrders) }}
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>今日订单金额</template>
            <div class="stat-value text-success">
              ${{ formatNumber(orderData.todayAmount) }}
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>平均订单金额</template>
            <div class="stat-value text-warning">
              ${{ formatNumber(orderData.averageAmount) }}
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card general-card">
            <template #title>成功率</template>
            <div class="stat-value text-info">
              {{ formatNumber(orderData.successRate) }}%
            </div>
          </a-card>
        </a-col>
      </a-row> -->

      <!-- 图表区域 -->
      <!-- <a-row :gutter="16">
        <a-col :span="12">
          <a-card class="chart-card general-card">
            <template #title>订单金额分布</template>
            <v-chart
              class="chart"
              :option="orderAmountDistributionOption"
              autoresize
            />
          </a-card>
        </a-col>
        <a-col :span="12">
          <a-card class="chart-card general-card">
            <template #title>订单状态分布</template>
            <v-chart
              class="chart"
              :option="orderStatusDistributionOption"
              autoresize
            />
          </a-card>
        </a-col>
      </a-row> -->

      <!-- 订单列表 -->
      <a-card class="mt-4 general-card">
        <template #title>订单详情</template>
        <a-table
          :data="orderList"
          :loading="loading"
          :pagination="pagination"
          @page-change="onPageChange"
          @page-size-change="onPageSizeChange"
        >
          <template #columns>
            <a-table-column title="订单ID" data-index="id" />
            <a-table-column title="账号" data-index="accountName" />
            <a-table-column title="金额" data-index="amount">
              <template #cell="{ record }">
                ${{ formatNumber(record.amount) }}
              </template>
            </a-table-column>
            <a-table-column title="状态" data-index="status">
              <template #cell="{ record }">
                <a-tag :color="getStatusColor(record.status)">
                  {{ getStatusText(record.status) }}
                </a-tag>
              </template>
            </a-table-column>
            <a-table-column title="创建时间" data-index="createdAt" />
            <a-table-column title="完成时间" data-index="completedAt" />
            <a-table-column title="操作" fixed="right" :width="120">
              <template #cell="{ record }">
                <a-button
                  type="text"
                  size="small"
                  @click="handleViewDetail(record)"
                >
                  查看详情
                </a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </a-card>
    </a-space>

    <!-- 订单详情抽屉 -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { use } from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { BarChart, PieChart } from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
} from 'echarts/components';
import VChart from 'vue-echarts';
import { apiClient } from '@/api/index.ts';
import { Message } from '@arco-design/web-vue';
import { KamiApiCardInfoWalmartV1ListOutput } from '@/api/generated';

use([
  CanvasRenderer,
  BarChart,
  PieChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent
]);

const props = defineProps<{
  groupId?: number;
}>();

const loading = ref(false);
const orderData = ref({
  todayOrders: 0,
  todayAmount: 0,
  averageAmount: 0,
  successRate: 0
});

const orderList = ref<KamiApiCardInfoWalmartV1ListOutput[]>([]);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
});

// 订单详情相关
const detailVisible = ref(false);
const currentOrder = ref(null);

// 订单金额分布图表配置
const orderAmountDistributionOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value',
    name: '订单数'
  },
  series: [
    {
      type: 'bar',
      data: []
    }
  ]
});

// 订单状态分布图表配置
const orderStatusDistributionOption = ref({
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      type: 'pie',
      radius: '50%',
      data: [],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
});

// 格式化数字
const formatNumber = (num: number) => {
  return new Intl.NumberFormat('en-US').format(num);
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap = {
    success: 'green',
    failed: 'red',
    pending: 'orange',
    processing: 'blue'
  };
  return colorMap[status] || 'default';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap = {
    success: '成功',
    failed: '失败',
    pending: '待处理',
    processing: '处理中'
  };
  return textMap[status] || status;
};

// 获取订单详情数据
const getOrderDetailData = () => {
  if (!currentOrder.value) return [];
  return [
    {
      label: '订单ID',
      value: currentOrder.value.id
    },
    {
      label: '账号',
      value: currentOrder.value.accountName
    },
    {
      label: '金额',
      value: `$${formatNumber(currentOrder.value.amount)}`
    },
    {
      label: '状态',
      value: getStatusText(currentOrder.value.status)
    },
    {
      label: '创建时间',
      value: currentOrder.value.createdAt
    },
    {
      label: '完成时间',
      value: currentOrder.value.completedAt || '-'
    }
  ];
};

// 查看订单详情
const handleViewDetail = record => {
  currentOrder.value = record;
  detailVisible.value = true;
};

// 获取订单统计数据
const fetchOrderData = async () => {
  loading.value = true;
  try {
    const res = await apiClient.apiCardInfoWalmartOrderListGet({
      groupId: props.groupId,
      current: pagination.value.current,
      pageSize: pagination.value.pageSize
    });
    orderList.value = res.data.list;
    pagination.value.total = res.data.total;

    // 更新图表数据
    updateCharts(res.data);
  } catch (error) {
    Message.error('获取订单统计数据失败');
  } finally {
    loading.value = false;
  }
};

// 更新图表数据
const updateCharts = (data: any) => {
  // 更新订单金额分布图表
  orderAmountDistributionOption.value.xAxis.data =
    data.amountDistribution.ranges;
  orderAmountDistributionOption.value.series[0].data =
    data.amountDistribution.counts;

  // 更新订单状态分布图表
  orderStatusDistributionOption.value.series[0].data = data.statusDistribution;
};

// 分页处理
const onPageChange = (current: number) => {
  pagination.value.current = current;
  fetchOrderData();
};

const onPageSizeChange = (pageSize: number) => {
  pagination.value.pageSize = pageSize;
  fetchOrderData();
};

onMounted(() => {
  fetchOrderData();
});
</script>

<style scoped>
.order-statistics {
  padding: 16px;
}

.stat-card {
  height: 100%;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  line-height: 1.5;
}

.chart-card {
  height: 100%;
}

.chart {
  height: 400px;
}

.mt-4 {
  margin-top: 16px;
}

.order-detail {
  padding: 16px;
}

.text-primary {
  color: rgb(var(--primary-6));
}

.text-success {
  color: rgb(var(--success-6));
}

.text-warning {
  color: rgb(var(--warning-6));
}

.text-info {
  color: rgb(var(--info-6));
}
</style>
