import React, { useEffect, useState } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Space, Table, Tag } from 'antd';
import { ShoppingOutlined, DollarOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { getOrderList } from '@/api/admin';
import dayjs, { Dayjs } from 'dayjs';

const { RangePicker } = DatePicker;

const statusMap: Record<string, { color: string; label: string }> = {
  pending_pay: { color: 'gold', label: '待支付' },
  pending_confirm: { color: 'blue', label: '待确认' },
  pending_checkin: { color: 'cyan', label: '待入住' },
  checked_in: { color: 'orange', label: '已入住' },
  completed: { color: 'green', label: '已完成' },
  cancelled: { color: 'default', label: '已取消' },
  refunding: { color: 'red', label: '退款中' },
  refunded: { color: 'purple', label: '已退款' },
};

const OrderStatistics: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
    dayjs().subtract(7, 'day'),
    dayjs(),
  ]);
  const [stats, setStats] = useState({
    totalOrders: 0,
    totalAmount: 0,
    completedOrders: 0,
    cancelledOrders: 0,
  });
  const [statusStats, setStatusStats] = useState<any[]>([]);

  const fetchStatistics = async () => {
    setLoading(true);
    try {
      // 获取所有订单数据进行统计
      const res: any = await getOrderList({
        page: 1,
        pageSize: 10000,
        startDate: dateRange[0].format('YYYY-MM-DD'),
        endDate: dateRange[1].format('YYYY-MM-DD'),
      });

      const orders = res.data?.list || [];

      // 计算统计数据
      const totalOrders = orders.length;
      const totalAmount = orders.reduce((sum: number, order: any) => sum + Number(order.payAmount || 0), 0);
      const completedOrders = orders.filter((o: any) => o.status === 'completed').length;
      const cancelledOrders = orders.filter((o: any) => ['cancelled', 'refunded'].includes(o.status)).length;

      setStats({
        totalOrders,
        totalAmount,
        completedOrders,
        cancelledOrders,
      });

      // 按状态统计
      const statusCount: Record<string, number> = {};
      const statusAmount: Record<string, number> = {};

      orders.forEach((order: any) => {
        const status = order.status;
        statusCount[status] = (statusCount[status] || 0) + 1;
        statusAmount[status] = (statusAmount[status] || 0) + Number(order.payAmount || 0);
      });

      const statusStatsData = Object.entries(statusCount).map(([status, count]) => ({
        status,
        statusLabel: statusMap[status]?.label || status,
        color: statusMap[status]?.color || 'default',
        count,
        amount: statusAmount[status] || 0,
        percentage: ((count / totalOrders) * 100).toFixed(2),
      }));

      setStatusStats(statusStatsData);
    } catch (error) {
      console.error('获取统计数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, [dateRange]);

  const columns = [
    {
      title: '订单状态',
      dataIndex: 'statusLabel',
      key: 'statusLabel',
      render: (text: string, record: any) => (
        <Tag color={record.color}>{text}</Tag>
      ),
    },
    {
      title: '订单数量',
      dataIndex: 'count',
      key: 'count',
      sorter: (a: any, b: any) => a.count - b.count,
    },
    {
      title: '订单金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (amount: number) => `¥${amount.toFixed(2)}`,
      sorter: (a: any, b: any) => a.amount - b.amount,
    },
    {
      title: '占比',
      dataIndex: 'percentage',
      key: 'percentage',
      render: (percentage: string) => `${percentage}%`,
      sorter: (a: any, b: any) => parseFloat(a.percentage) - parseFloat(b.percentage),
    },
  ];

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <h2>订单统计报表</h2>
        <Space>
          <span>统计时间：</span>
          <RangePicker
            value={dateRange}
            onChange={(dates) => dates && setDateRange(dates as [Dayjs, Dayjs])}
            format="YYYY-MM-DD"
          />
        </Space>
      </div>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={6}>
          <Card>
            <Statistic
              title="订单总数"
              value={stats.totalOrders}
              prefix={<ShoppingOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="订单总额"
              value={stats.totalAmount}
              prefix={<DollarOutlined />}
              suffix="元"
              precision={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已完成订单"
              value={stats.completedOrders}
              prefix={<CheckCircleOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已取消订单"
              value={stats.cancelledOrders}
              prefix={<CloseCircleOutlined />}
              valueStyle={{ color: '#ff4d4f' }}
            />
          </Card>
        </Col>
      </Row>

      <Card title="订单状态分布">
        <Table
          columns={columns}
          dataSource={statusStats}
          rowKey="status"
          loading={loading}
          pagination={false}
        />
      </Card>
    </div>
  );
};

export default OrderStatistics;
