'use client';

/**
 * 作者: 阿瑞
 * 功能: 店铺成交分析页面
 * 版本: 1.0.0
 */
import React, { useState, useEffect, useCallback } from 'react';
import { DatePicker, Table, Card, Spin, Empty, Button } from 'antd';
import { FundOutlined } from '@ant-design/icons';
import { ShopSalesAnalysis } from '@/lib/db/types';
import dayjs from 'dayjs';
import { formatCurrency } from '@/utils';
import styles from './page.module.css';

/**
 * 店铺成交分析页面组件
 */
export default function ShopSalesAnalysisPage({ params }: { params: Promise<{ teamCode: string }> }) {
  // 使用React.use解包params参数
  const resolvedParams = React.use(params);
  const teamCode = resolvedParams.teamCode;
  
  // 状态管理
  const [loading, setLoading] = useState<boolean>(false);
  const [analyzeDate, setAnalyzeDate] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().startOf('month'),
    dayjs()
  ]);
  const [analyticsData, setAnalyticsData] = useState<ShopSalesAnalysis[]>([]);
  
  /**
   * 表格列定义
   */
  const columns = [
    {
      title: '店铺',
      dataIndex: 'shopName',
      key: 'shopName',
      width: 160,
      fixed: 'left' as const,
    },
    {
      title: '进粉数量',
      dataIndex: 'followers',
      key: 'followers',
      align: 'right' as const,
      render: (text: number) => text.toLocaleString(),
    },
    {
      title: '引流消费',
      dataIndex: 'expenses',
      key: 'expenses',
      align: 'right' as const,
      render: (amount: number) => formatCurrency(amount),
    },
    {
      title: '出单数',
      dataIndex: 'orderCount',
      key: 'orderCount',
      align: 'right' as const,
      render: (text: number) => text.toLocaleString(),
    },
    {
      title: '销售额',
      dataIndex: 'sales',
      key: 'sales',
      align: 'right' as const,
      render: (amount: number) => formatCurrency(amount),
    },
    {
      title: '成本',
      dataIndex: 'cost',
      key: 'cost',
      align: 'right' as const,
      render: (amount: number) => formatCurrency(amount),
    },
    {
      title: '毛利',
      key: 'profit',
      align: 'right' as const,
      render: (_: unknown, record: ShopSalesAnalysis) => formatCurrency(record.sales - record.cost),
    },
    {
      title: '毛利率',
      key: 'profitMargin',
      align: 'right' as const,
      render: (_: unknown, record: ShopSalesAnalysis) => {
        if (record.sales === 0) return '0.00%';
        const margin = ((record.sales - record.cost) / record.sales) * 100;
        return margin.toFixed(2) + '%';
      },
    },
  ];

  /**
   * 加载分析数据
   */
  const loadAnalyticsData = useCallback(async () => {
    if (!analyzeDate[0] || !analyzeDate[1]) return;
    
    setLoading(true);
    
    try {
      const startDate = analyzeDate[0].format('YYYY-MM-DD');
      const endDate = analyzeDate[1].format('YYYY-MM-DD');
      
      const response = await fetch(
        `/api/team/${teamCode}/shop-sales-analysis?startDate=${startDate}&endDate=${endDate}`
      );
      
      if (!response.ok) {
        throw new Error('获取数据失败');
      }
      
      const result = await response.json();
      
      if (result.success) {
        setAnalyticsData(result.data);
      } else {
        console.error('获取分析数据失败:', result.error);
      }
    } catch (error) {
      console.error('获取分析数据出错:', error);
    } finally {
      setLoading(false);
    }
  }, [analyzeDate, teamCode]);

  /**
   * 首次加载时获取数据
   */
  useEffect(() => {
    loadAnalyticsData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [teamCode]); // 不要依赖loadAnalyticsData避免循环依赖

  /**
   * 计算总计行数据
   */
  const calculateSummary = () => {
    const totals = analyticsData.reduce(
      (acc, curr) => {
        acc.followers += curr.followers;
        acc.expenses += curr.expenses;
        acc.orderCount += curr.orderCount;
        acc.sales += curr.sales;
        acc.cost += curr.cost;
        return acc;
      },
      { followers: 0, expenses: 0, orderCount: 0, sales: 0, cost: 0 }
    );

    return [
      {
        shopName: '总计',
        followers: totals.followers,
        expenses: totals.expenses,
        orderCount: totals.orderCount,
        sales: totals.sales,
        cost: totals.cost,
      },
    ];
  };

  return (
    <div className={styles.container}>
      <Card
        title={
          <div className={styles.cardTitle}>
            <FundOutlined className={styles.cardIcon} />
            <span>店铺成交分析</span>
          </div>
        }
        className="shadow-md"
      >
        {/* 日期选择器 */}
        <div className={styles.filterSection}>
          <DatePicker.RangePicker
            allowClear={false}
            value={analyzeDate}
            onChange={(dates) => {
              if (dates) {
                setAnalyzeDate(dates as [dayjs.Dayjs, dayjs.Dayjs]);
              }
            }}
          />
          <Button type="primary" onClick={loadAnalyticsData}>
            分析
          </Button>
        </div>

        {/* 数据表格 */}
        <Spin spinning={loading}>
          {analyticsData.length > 0 ? (
            <Table
              rowKey="shopId"
              columns={columns}
              dataSource={analyticsData}
              pagination={false}
              summary={() => (
                <Table.Summary fixed="bottom">
                  {calculateSummary().map((row, index) => (
                    <Table.Summary.Row key={index} className={styles.tableFooter}>
                      <Table.Summary.Cell index={0}>{row.shopName}</Table.Summary.Cell>
                      <Table.Summary.Cell index={1} align="right">
                        {row.followers.toLocaleString()}
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={2} align="right">
                        {formatCurrency(row.expenses)}
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={3} align="right">
                        {row.orderCount.toLocaleString()}
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={4} align="right">
                        {formatCurrency(row.sales)}
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={5} align="right">
                        {formatCurrency(row.cost)}
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={6} align="right">
                        {formatCurrency(row.sales - row.cost)}
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={7} align="right">
                        {row.sales === 0
                          ? '0.00%'
                          : ((row.sales - row.cost) / row.sales * 100).toFixed(2) + '%'}
                      </Table.Summary.Cell>
                    </Table.Summary.Row>
                  ))}
                </Table.Summary>
              )}
            />
          ) : (
            <Empty description="暂无分析数据" />
          )}
        </Spin>
      </Card>
    </div>
  );
} 