// src/pages/customer/sales-record.tsx
import React, { useState, useEffect } from 'react';
import { Card, List, Descriptions, App } from 'antd';

const { useApp } = App;

interface SalesRecordPageProps {
  initialPhone?: string; // 用于传递初始手机号
}

const SalesRecordPage: React.FC<SalesRecordPageProps> = ({ initialPhone }) => {
  const [loading, setLoading] = useState(false);
  const [salesRecords, setSalesRecords] = useState<any[]>([]);
  const [afterSalesRecords, setAfterSalesRecords] = useState<any[]>([]);
  const [totalIncome, setTotalIncome] = useState<number>(0); // 新增的本单收入状态
  const { message } = useApp(); // 使用 useApp hook 获取 message 实例

  const handleSearch = async () => {
    if (!initialPhone) {
      message.error('手机号缺失');
      return;
    }

    setLoading(true);

    try {
      const response = await fetch(`/api/backstage/customers/sales/${initialPhone}`);
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      
      const data = await response.json();

      if (data.salesRecords) {
        setSalesRecords(data.salesRecords);
      }

      if (data.afterSalesRecords) {
        setAfterSalesRecords(data.afterSalesRecords);
      }

      message.success('查询成功');
    } catch (error: unknown) {
      console.error(error);
      message.error('查询失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 自动搜索初始手机号的销售记录
  useEffect(() => {
    if (initialPhone) {
      handleSearch();
    }
  }, [initialPhone]);

  // 计算本单收入
  useEffect(() => {
    const calculateTotalIncome = () => {
      let totalSalesIncome = 0; // 收款金额总和
      let totalPendingIncome = 0; // 待收款总和
      let totalAfterSalesIncome = 0; // 售后收入总和
      let totalAfterSalesExpenditure = 0; // 售后支出总和

      // 计算销售记录中的收款金额和待收款
      salesRecords.forEach((record) => {
        totalSalesIncome += record.收款金额 || 0;
        totalPendingIncome += record.待收款 || 0;
      });

      // 计算售后记录中的收入和支出
      afterSalesRecords.forEach((record) => {
        if (record.收支类型 === '收入') {
          totalAfterSalesIncome += record.收支金额 || 0;
        } else if (record.收支类型 === '支出') {
          totalAfterSalesExpenditure += record.收支金额 || 0;
        }
      });

      // 本单收入 = 收款金额总和 + 待收款总和 + 售后收入 - 售后支出
      const calculatedIncome = totalSalesIncome + totalPendingIncome + totalAfterSalesIncome - totalAfterSalesExpenditure;
      setTotalIncome(calculatedIncome);
    };

    calculateTotalIncome();
  }, [salesRecords, afterSalesRecords]);

  return (
    <div 
    //固定高度，超出部分滚动
    style={{height: '90vh', overflow: 'auto'}}

    className="container mx-auto p-4"
    >
      {/* 销售记录展示 */}
      <Card title="销售记录" loading={loading}>
        <List
          dataSource={salesRecords}
          renderItem={(record: any) => (
            <List.Item>
              <Descriptions title={`订单号: ${record._id}`} column={2} bordered>
                <Descriptions.Item label="成交日期">{record.成交日期}</Descriptions.Item>
                <Descriptions.Item label="应收金额">¥{record.应收金额}</Descriptions.Item>
                <Descriptions.Item label="收款金额">¥{record.收款金额}</Descriptions.Item>
                <Descriptions.Item label="待收款">¥{record.待收款}</Descriptions.Item>
                <Descriptions.Item label="收款状态">{record.收款状态}</Descriptions.Item>
                <Descriptions.Item label="订单状态">{record.订单状态.join(', ')}</Descriptions.Item>
                <Descriptions.Item label="货款状态">{record.货款状态}</Descriptions.Item>
                <Descriptions.Item label="备注">{record.备注 || '无'}</Descriptions.Item>
              </Descriptions>
            </List.Item>
          )}
        />
      </Card>

      {/* 售后记录展示 */}
      <Card title="售后记录" className="mt-4" loading={loading}>
        <List
          dataSource={afterSalesRecords}
          renderItem={(record: any) => (
            <List.Item>
              <Descriptions title={`售后记录号: ${record._id}`} column={2} bordered>
                <Descriptions.Item label="售后类型">{record.类型}</Descriptions.Item>
                <Descriptions.Item label="售后日期">{record.日期}</Descriptions.Item>
                <Descriptions.Item label="售后进度">{record.售后进度}</Descriptions.Item>
                <Descriptions.Item label="原因">{record.原因}</Descriptions.Item>
                <Descriptions.Item label="收支金额">¥{record.收支金额}</Descriptions.Item>
                <Descriptions.Item label="收支平台">{record.收支平台 || '无'}</Descriptions.Item>
                <Descriptions.Item label="备注">{record.备注 || '无'}</Descriptions.Item>
              </Descriptions>
            </List.Item>
          )}
        />
      </Card>

      {/* 本单收入展示 */}
      <Card title="本单收入" className="mt-4">
        <Descriptions bordered>
          <Descriptions.Item label="本单收入总和" span={2}>
            ¥{totalIncome.toFixed(2)}
          </Descriptions.Item>
        </Descriptions>
      </Card>
    </div>
  );
};

export default SalesRecordPage;
