import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Select, DatePicker, message, Card, Typography, Tag, Modal, Form } from 'antd';
import { SearchOutlined, EyeOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
import { merchantDataSource, Merchant, MerchantSettlement } from '@/services/merchantDataSource';

const { Option } = Select;
const { Title, Text } = Typography;
const { RangePicker } = DatePicker;
const { Item } = Form;

const MerchantSettlementManage: React.FC = () => {
  const [settlements, setSettlements] = useState<Settlement[]>([]);
  const [merchants, setMerchants] = useState<{ id: string; companyName: string }[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [merchantFilter, setMerchantFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [dateRange, setDateRange] = useState<[string, string] | null>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedSettlement, setSelectedSettlement] = useState<Settlement | null>(null);
  const [form] = Form.useForm();

  const fetchSettlements = async () => {
    setLoading(true);
    try {
      const response = await getMerchantSettlements();
      setSettlements(response.data);
    } catch (error) {
      message.error('获取结算列表失败');
      console.error('获取结算列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const fetchMerchants = async () => {
    try {
      // 实际项目中应该调用获取商户列表的API
      // 这里模拟数据
      setMerchants([
        { id: '1', companyName: '商户A' },
        { id: '2', companyName: '商户B' },
        { id: '3', companyName: '商户C' },
      ]);
    } catch (error) {
      console.error('获取商户列表失败:', error);
    }
  };

  useEffect(() => {
    fetchMerchants();
    fetchSettlements();
  }, []);

  const handleSearch = (value: string) => {
    setSearchText(value);
  };

  const handleMerchantFilter = (value: string) => {
    setMerchantFilter(value);
  };

  const handleStatusFilter = (value: string) => {
    setStatusFilter(value);
  };

  const handleDateRangeChange = (dates: any) => {
    if (dates) {
      setDateRange([dates[0].format('YYYY-MM-DD'), dates[1].format('YYYY-MM-DD')]);
    } else {
      setDateRange(null);
    }
  };

  const filteredSettlements = settlements.filter(settlement => {
    const matchesSearch = settlement.id.includes(searchText) ||
                        settlement.merchantName.toLowerCase().includes(searchText.toLowerCase());
    const matchesMerchant = merchantFilter ? settlement.merchantId === merchantFilter : true;
    const matchesStatus = statusFilter ? settlement.status === statusFilter : true;
    return matchesSearch && matchesMerchant && matchesStatus;
  });

  const handleView = (settlement: Settlement) => {
    setSelectedSettlement(settlement);
    setIsModalVisible(true);
  };

  const handleProcess = (settlement: Settlement) => {
    // 调用API处理结算
    message.info(`处理结算: ${settlement.id}`);
  };

  const handleDownload = (settlement: Settlement) => {
    // 下载结算单
    message.info(`下载结算单: ${settlement.id}`);
  };

  const handleRefresh = () => {
    fetchSettlements();
  };

  const getStatusTag = (status: string) => {
    const statusConfig: Record<string, { color: string; text: string }> = {
      PENDING: { color: 'blue', text: '待处理' },
      PROCESSING: { color: 'orange', text: '处理中' },
      COMPLETED: { color: 'green', text: '已完成' },
      FAILED: { color: 'red', text: '失败' },
    };
    const config = statusConfig[status] || { color: 'default', text: status };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const columns = [
    {
      title: '结算单ID',
      dataIndex: 'id',
      key: 'id',
      ellipsis: true,
    },
    {
      title: '商户',
      dataIndex: 'merchantName',
      key: 'merchantName',
      ellipsis: true,
    },
    {
      title: '结算周期',
      key: 'period',
      render: (_, settlement: Settlement) => (
        <Text>
          {settlement.periodStart} 至 {settlement.periodEnd}
        </Text>
      ),
    },
    {
      title: '结算金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      render: (amount: number) => <Text>${amount.toFixed(2)}</Text>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      ellipsis: true,
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, settlement: Settlement) => (
        <div>
          <Button 
            icon={<EyeOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleView(settlement)}
          >
            查看
          </Button>
          <Button 
            icon={<DownloadOutlined />} 
            size="small" 
            style={{ marginRight: 8 }}
            onClick={() => handleDownload(settlement)}
          >
            下载
          </Button>
          {settlement.status === 'PENDING' && (
            <Button 
              type="primary" 
              size="small"
              onClick={() => handleProcess(settlement)}
            >
              处理
            </Button>
          )}
        </div>
      ),
    },
  ];

  return (
    <Card>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
        <Title level={4}>多商户结算管理</Title>
        <Button 
          icon={<ReloadOutlined />}
          onClick={handleRefresh}
        >
          刷新
        </Button>
      </div>

      <div style={{ display: 'flex', marginBottom: 16, gap: 16, flexWrap: 'wrap' }}>
        <Input
          placeholder="搜索结算单ID或商户名称"
          prefix={<SearchOutlined />}
          style={{ width: 300 }}
          onChange={(e) => handleSearch(e.target.value)}
        />
        <Select
          placeholder="筛选商户"
          style={{ width: 200 }}
          onChange={handleMerchantFilter}
          allowClear
        >
          {merchants.map(merchant => (
            <Option key={merchant.id} value={merchant.id}>
              {merchant.companyName}
            </Option>
          ))}
        </Select>
        <Select
          placeholder="筛选状态"
          style={{ width: 120 }}
          onChange={handleStatusFilter}
          allowClear
        >
          <Option value="PENDING">待处理</Option>
          <Option value="PROCESSING">处理中</Option>
          <Option value="COMPLETED">已完成</Option>
          <Option value="FAILED">失败</Option>
        </Select>
        <RangePicker
          placeholder={['开始日期', '结束日期']}
          onChange={handleDateRangeChange}
        />
      </div>

      <Table
        columns={columns}
        dataSource={filteredSettlements}
        rowKey="id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          pageSizeOptions: ['10', '20', '50'],
          defaultPageSize: 10,
        }}
      />

      <Modal
        title="结算详情"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setIsModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {selectedSettlement && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>结算单ID:</Text> {selectedSettlement.id}
            </div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>商户:</Text> {selectedSettlement.merchantName}
            </div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>结算周期:</Text> {selectedSettlement.periodStart} 至 {selectedSettlement.periodEnd}
            </div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>结算金额:</Text> ${selectedSettlement.totalAmount.toFixed(2)}
            </div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>状态:</Text> {getStatusTag(selectedSettlement.status)}
            </div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>创建时间:</Text> {selectedSettlement.createdAt}
            </div>
            <div style={{ marginBottom: 16 }}>
              <Text strong>更新时间:</Text> {selectedSettlement.updatedAt}
            </div>
            <div style={{ marginTop: 24 }}>
              <Title level={5}>结算明细</Title>
              <Table
                columns={[
                  { title: '项目', dataIndex: 'item', key: 'item' },
                  { title: '金额', dataIndex: 'amount', key: 'amount', render: (amount: number) => `$${amount.toFixed(2)}` },
                ]}
                dataSource={[
                  { key: '1', item: '商品销售', amount: selectedSettlement.totalAmount * 0.9 },
                  { key: '2', item: '平台服务费', amount: selectedSettlement.totalAmount * 0.1 },
                ]}
                pagination={false}
              />
            </div>
          </div>
        )}
      </Modal>
    </Card>
  );
};

export default MerchantSettlementManage;