import React, { useState, useEffect } from 'react';
import { Card, Table, DatePicker, Space, Statistic, Row, Col, Tag, message } from 'antd';
import { ArrowUpOutlined, ArrowDownOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { formatMoney, formatDateTime } from '@rent/shared-utils';
import { getFinancialOverview, getWeeklyReport } from '@/api/finance';
import type { Dayjs } from 'dayjs';

const { RangePicker } = DatePicker;

interface EarningRecord {
  id: number;
  date: string;
  startDate?: string;
  endDate?: string;
  orderCount: number;
  totalAmount: number;
  platformCommission: number;
  withdrawalFee: number;
  totalIncome: number;
  totalExpense: number;
  profit: number;
}

const Earnings: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [dataSource, setDataSource] = useState<EarningRecord[]>([]);
  const [dateRange, setDateRange] = useState<[Dayjs | null, Dayjs | null] | null>(null);
  const [overview, setOverview] = useState({
    todayIncome: 0,
    monthIncome: 0,
    totalIncome: 0,
    monthProfit: 0,
    platformCommission: 0,
    withdrawalFee: 0,
    pendingSettlement: 0,
    balance: 0,
    growthRate: 0,
  });

  useEffect(() => {
    fetchOverview();
    fetchData();
  }, []);

  const fetchOverview = async () => {
    try {
      const res = await getFinancialOverview({});
      if (res?.data) {
        setOverview({
          todayIncome: res.data?.todayIncome || 0,
          monthIncome: res.data?.monthIncome || 0,
          totalIncome: res.data?.totalIncome || 0,
          monthProfit: res.data?.monthProfit || 0,
          platformCommission: res.data?.platformCommission || 0,
          withdrawalFee: res.data?.withdrawalFee || 0,
          pendingSettlement: res.data?.pendingSettlement || 0,
          balance: res.data?.balance || 0,
          growthRate: res.data?.growthRate || 0,
        });
      }
    } catch (error) {
      console.error('获取财务概览失败:', error);
    }
  };

  const fetchData = async () => {
    setLoading(true);
    try {
      const params: any = {};

      if (dateRange && dateRange[0] && dateRange[1]) {
        params.startDate = dateRange[0].format('YYYY-MM-DD');
        params.endDate = dateRange[1].format('YYYY-MM-DD');
      }

      // 使用周报表接口获取数据
      const res = await getWeeklyReport(params);
      if (res?.data) {
        // 将单条数据转换为数组格式
        const data = res.data;
        if (data) {
          setDataSource([{
            id: 1,
            date: data.startDate,
            startDate: data.startDate,
            endDate: data.endDate,
            orderCount: data.orderCount || 0,
            totalAmount: data.orderAmount || 0,
            platformCommission: data.serviceFee || 0,
            withdrawalFee: 0,
            totalIncome: data.totalIncome || 0,
            totalExpense: data.totalExpense || 0,
            profit: data.netAmount || 0,
          }]);
        } else {
          setDataSource([]);
        }
      }
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDateChange = (dates: [Dayjs | null, Dayjs | null] | null) => {
    setDateRange(dates);
    if (dates) {
      fetchData();
    }
  };

  const columns: ColumnsType<EarningRecord> = [
    {
      title: '日期范围',
      dataIndex: 'date',
      key: 'date',
      render: (date: string, record: EarningRecord) => {
        if (record.startDate && record.endDate) {
          return `${formatDateTime(record.startDate).split(' ')[0]} ~ ${formatDateTime(record.endDate).split(' ')[0]}`;
        }
        return formatDateTime(date).split(' ')[0];
      },
    },
    {
      title: '订单数',
      dataIndex: 'orderCount',
      key: 'orderCount',
    },
    {
      title: '订单总额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => formatMoney(amount),
    },
    {
      title: '平台佣金',
      dataIndex: 'platformCommission',
      key: 'platformCommission',
      render: (commission: number) => (
        <span style={{ color: '#52c41a', fontWeight: 600 }}>
          {formatMoney(commission)}
        </span>
      ),
    },
    {
      title: '提现手续费',
      dataIndex: 'withdrawalFee',
      key: 'withdrawalFee',
      render: (fee: number) => (
        <span style={{ color: '#52c41a' }}>
          {formatMoney(fee)}
        </span>
      ),
    },
    {
      title: '总收入',
      dataIndex: 'totalIncome',
      key: 'totalIncome',
      render: (income: number) => (
        <span style={{ color: '#52c41a', fontWeight: 600 }}>
          {formatMoney(income)}
        </span>
      ),
    },
    {
      title: '总支出',
      dataIndex: 'totalExpense',
      key: 'totalExpense',
      render: (expense: number) => (
        <span style={{ color: '#ff4d4f' }}>
          {formatMoney(expense)}
        </span>
      ),
    },
    {
      title: '净利润',
      dataIndex: 'profit',
      key: 'profit',
      render: (profit: number) => (
        <span style={{ color: profit >= 0 ? '#52c41a' : '#ff4d4f', fontWeight: 700 }}>
          {formatMoney(profit)}
        </span>
      ),
    },
  ];

  return (
    <div>
      <Card style={{ marginBottom: 16 }} title="平台财务概览">
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="今日收益"
              value={overview.todayIncome}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#52c41a' }}
              suffix={
                <span style={{ fontSize: 14, color: '#999' }}>
                  {overview.growthRate >= 0 ? (
                    <><ArrowUpOutlined style={{ color: '#52c41a' }} /> {overview.growthRate.toFixed(1)}%</>
                  ) : (
                    <><ArrowDownOutlined style={{ color: '#ff4d4f' }} /> {Math.abs(overview.growthRate).toFixed(1)}%</>
                  )}
                </span>
              }
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="本月收益"
              value={overview.monthIncome}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#52c41a' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="累计收益"
              value={overview.totalIncome}
              prefix="¥"
              precision={2}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="本月利润"
              value={overview.monthProfit}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
        </Row>
        <Row gutter={16} style={{ marginTop: 24 }}>
          <Col span={6}>
            <Statistic
              title="平台佣金收入"
              value={overview.platformCommission}
              prefix="¥"
              precision={2}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="提现手续费收入"
              value={overview.withdrawalFee}
              prefix="¥"
              precision={2}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="待结算金额"
              value={overview.pendingSettlement}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#faad14' }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="资金池余额"
              value={overview.balance}
              prefix="¥"
              precision={2}
              valueStyle={{ color: '#1890ff' }}
            />
          </Col>
        </Row>
      </Card>

      <Card
        title="收益明细"
        extra={
          <Space>
            <RangePicker value={dateRange} onChange={handleDateChange} />
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={dataSource}
          rowKey="id"
          loading={loading}
          pagination={false}
          summary={(pageData) => {
            if (pageData.length === 0) return null;

            const totalOrders = pageData.reduce((sum, record) => sum + record.orderCount, 0);
            const totalAmount = pageData.reduce((sum, record) => sum + record.totalAmount, 0);
            const totalCommission = pageData.reduce((sum, record) => sum + record.platformCommission, 0);
            const totalFee = pageData.reduce((sum, record) => sum + record.withdrawalFee, 0);
            const totalIncome = pageData.reduce((sum, record) => sum + record.totalIncome, 0);
            const totalExpense = pageData.reduce((sum, record) => sum + record.totalExpense, 0);
            const totalProfit = pageData.reduce((sum, record) => sum + record.profit, 0);

            return (
              <Table.Summary fixed>
                <Table.Summary.Row style={{ fontWeight: 600 }}>
                  <Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
                  <Table.Summary.Cell index={1}>{totalOrders}</Table.Summary.Cell>
                  <Table.Summary.Cell index={2}>{formatMoney(totalAmount)}</Table.Summary.Cell>
                  <Table.Summary.Cell index={3}>
                    <span style={{ color: '#52c41a' }}>{formatMoney(totalCommission)}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={4}>
                    <span style={{ color: '#52c41a' }}>{formatMoney(totalFee)}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={5}>
                    <span style={{ color: '#52c41a' }}>{formatMoney(totalIncome)}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={6}>
                    <span style={{ color: '#ff4d4f' }}>{formatMoney(totalExpense)}</span>
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={7}>
                    <span style={{ color: totalProfit >= 0 ? '#52c41a' : '#ff4d4f' }}>
                      {formatMoney(totalProfit)}
                    </span>
                  </Table.Summary.Cell>
                </Table.Summary.Row>
              </Table.Summary>
            );
          }}
        />
      </Card>
    </div>
  );
};

export default Earnings;
