import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Modal,
  message,
  Spin,
  Row,
  Col,
  Typography,
  Divider,
  Space,
  Tag,
  Descriptions,
  Timeline,
  Alert,
} from 'antd';
import {
  SearchOutlined,
  TruckOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  HomeOutlined,
  FieldTimeOutlined,
  EnvironmentOutlined,
} from '@ant-design/icons';

const { Option } = Select;
const { Title, Text, Paragraph } = Typography;

// 模拟物流商数据
const logisticsProviders = [
  { value: 'SF', label: '顺丰速运' },
  { value: 'ZTO', label: '中通快递' },
  { value: 'EMS', label: 'EMS' },
  { value: 'YUNDA', label: '韵达快递' },
  { value: 'DEPPON', label: '德邦物流' },
  { value: 'JD', label: '京东物流' },
  { value: 'STO', label: '申通快递' },
  { value: 'YTO', label: '圆通快递' },
];

// 模拟物流追踪数据
const mockTrackingData = {
  'SF1234567890': {
    trackingNumber: 'SF1234567890',
    provider: '顺丰速运',
    status: 'IN_TRANSIT',
    estimatedDelivery: '2026-03-20',
    sender: '深圳市南山区',
    recipient: '北京市朝阳区',
    timeline: [
      {
        time: '2026-03-18 10:30:00',
        status: 'IN_TRANSIT',
        location: '北京市朝阳区',
        description: '快递正在派送中，派送员：张三，电话：13800138000',
      },
      {
        time: '2026-03-18 08:00:00',
        status: 'IN_TRANSIT',
        location: '北京市朝阳区营业点',
        description: '快递已到达营业点',
      },
      {
        time: '2026-03-17 18:00:00',
        status: 'IN_TRANSIT',
        location: '北京市',
        description: '快递已到达北京市',
      },
      {
        time: '2026-03-17 09:00:00',
        status: 'IN_TRANSIT',
        location: '上海市',
        description: '快递已离开上海市，发往北京市',
      },
      {
        time: '2026-03-16 18:00:00',
        status: 'PICKED_UP',
        location: '深圳市南山区',
        description: '快递已揽收',
      },
      {
        time: '2026-03-16 16:00:00',
        status: 'CREATED',
        location: '深圳市',
        description: '快递已下单',
      },
    ],
  },
  'ZTO9876543210': {
    trackingNumber: 'ZTO9876543210',
    provider: '中通快递',
    status: 'DELIVERED',
    estimatedDelivery: '2026-03-17',
    actualDelivery: '2026-03-17',
    sender: '上海市浦东新区',
    recipient: '广州市天河区',
    timeline: [
      {
        time: '2026-03-17 14:30:00',
        status: 'DELIVERED',
        location: '广州市天河区',
        description: '快递已签收，签收人：李四',
      },
      {
        time: '2026-03-17 10:00:00',
        status: 'IN_TRANSIT',
        location: '广州市天河区营业点',
        description: '快递正在派送中',
      },
      {
        time: '2026-03-17 08:00:00',
        status: 'IN_TRANSIT',
        location: '广州市',
        description: '快递已到达广州市',
      },
      {
        time: '2026-03-16 18:00:00',
        status: 'IN_TRANSIT',
        location: '上海市',
        description: '快递已离开上海市，发往广州市',
      },
      {
        time: '2026-03-16 10:00:00',
        status: 'PICKED_UP',
        location: '上海市浦东新区',
        description: '快递已揽收',
      },
    ],
  },
};

// 模拟历史追踪记录
const mockTrackingHistory = [
  {
    id: 'TRACK-20260318-001',
    trackingNumber: 'SF1234567890',
    provider: '顺丰速运',
    status: 'IN_TRANSIT',
    lastChecked: '2026-03-18T10:30:00Z',
  },
  {
    id: 'TRACK-20260318-002',
    trackingNumber: 'ZTO9876543210',
    provider: '中通快递',
    status: 'DELIVERED',
    lastChecked: '2026-03-17T14:30:00Z',
  },
];

const LogisticsTracking: React.FC = () => {
  const [form] = Form.useForm();
  const [isLoading, setIsLoading] = useState(false);
  const [trackingData, setTrackingData] = useState<any>(null);
  const [trackingHistory, setTrackingHistory] = useState(mockTrackingHistory);
  const [showTracking, setShowTracking] = useState(false);

  // 处理物流追踪查询
  const handleTrack = async (values: any) => {
    setIsLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const data = mockTrackingData[values.trackingNumber];
      
      if (data) {
        setTrackingData(data);
        setShowTracking(true);
        message.success('追踪成功');
        
        // 更新历史记录
        const existingRecord = trackingHistory.find(record => record.trackingNumber === values.trackingNumber);
        if (existingRecord) {
          const updatedHistory = trackingHistory.map(record => {
            if (record.trackingNumber === values.trackingNumber) {
              return {
                ...record,
                status: data.status,
                lastChecked: new Date().toISOString(),
              };
            }
            return record;
          });
          setTrackingHistory(updatedHistory);
        } else {
          const newRecord = {
            id: `TRACK-${Date.now()}`,
            trackingNumber: values.trackingNumber,
            provider: data.provider,
            status: data.status,
            lastChecked: new Date().toISOString(),
          };
          setTrackingHistory([newRecord, ...trackingHistory]);
        }
      } else {
        message.error('未找到物流信息');
        setShowTracking(false);
      }
    } catch (error) {
      message.error('追踪失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 获取状态标签
  const getStatusTag = (status: string) => {
    switch (status) {
      case 'CREATED':
        return <Tag color="blue">已下单</Tag>;
      case 'PICKED_UP':
        return <Tag color="processing">已揽收</Tag>;
      case 'IN_TRANSIT':
        return <Tag color="processing">运输中</Tag>;
      case 'OUT_FOR_DELIVERY':
        return <Tag color="processing">派送中</Tag>;
      case 'DELIVERED':
        return <Tag color="success">已送达</Tag>;
      case 'FAILED':
        return <Tag color="error">失败</Tag>;
      default:
        return <Tag>{status}</Tag>;
    }
  };

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'CREATED':
        return <ClockCircleOutlined />;
      case 'PICKED_UP':
        return <TruckOutlined />;
      case 'IN_TRANSIT':
        return <TruckOutlined />;
      case 'OUT_FOR_DELIVERY':
        return <TruckOutlined />;
      case 'DELIVERED':
        return <CheckCircleOutlined />;
      case 'FAILED':
        return <ExclamationCircleOutlined />;
      default:
        return <ClockCircleOutlined />;
    }
  };

  // 历史追踪表格列
  const historyColumns = [
    {
      title: '物流单号',
      dataIndex: 'trackingNumber',
      key: 'trackingNumber',
    },
    {
      title: '物流商',
      dataIndex: 'provider',
      key: 'provider',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '最后查询时间',
      dataIndex: 'lastChecked',
      key: 'lastChecked',
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Button 
          type="primary" 
          onClick={() => {
            form.setFieldsValue({
              trackingNumber: record.trackingNumber,
              provider: record.provider,
            });
            handleTrack({ trackingNumber: record.trackingNumber, provider: record.provider });
          }}
        >
          再次查询
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title={
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={4} style={{ margin: 0 }}>物流追踪</Title>
            <Text type="secondary">物流策略闭环第三步</Text>
          </div>
        }
        extra={
          <Button type="primary" ghost>
            批量追踪
          </Button>
        }
      >
        <Divider orientation="left">追踪查询</Divider>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleTrack}
        >
          <Row gutter={16}>
            <Col span={16}>
              <Form.Item
                name="trackingNumber"
                label="物流单号"
                rules={[{ required: true, message: '请输入物流单号' }]}
              >
                <Input placeholder="请输入物流单号" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="provider"
                label="物流商"
                rules={[{ required: true, message: '请选择物流商' }]}
              >
                <Select placeholder="请选择物流商">
                  {logisticsProviders.map(provider => (
                    <Option key={provider.value} value={provider.value}>
                      {provider.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item>
            <Space style={{ width: '100%', justifyContent: 'flex-end' }}>
              <Button onClick={() => form.resetFields()}>
                重置
              </Button>
              <Button type="primary" htmlType="submit" loading={isLoading}>
                <SearchOutlined style={{ marginRight: 4 }} />
                查询
              </Button>
            </Space>
          </Form.Item>
        </Form>

        {showTracking && trackingData && (
          <>
            <Divider orientation="left">追踪结果</Divider>
            <Card>
              <Row gutter={16}>
                <Col span={12}>
                  <Descriptions column={1}>
                    <Descriptions.Item label="物流单号">{trackingData.trackingNumber}</Descriptions.Item>
                    <Descriptions.Item label="物流商">{trackingData.provider}</Descriptions.Item>
                    <Descriptions.Item label="当前状态">{getStatusTag(trackingData.status)}</Descriptions.Item>
                    <Descriptions.Item label="预计送达时间">{trackingData.estimatedDelivery}</Descriptions.Item>
                    {trackingData.actualDelivery && (
                      <Descriptions.Item label="实际送达时间">{trackingData.actualDelivery}</Descriptions.Item>
                    )}
                    <Descriptions.Item label="寄件地">{trackingData.sender}</Descriptions.Item>
                    <Descriptions.Item label="收件地">{trackingData.recipient}</Descriptions.Item>
                  </Descriptions>
                </Col>
                <Col span={12}>
                  <div style={{ marginBottom: 16 }}>
                    <Text strong>物流状态</Text>
                    <div style={{ marginTop: 8, padding: 16, backgroundColor: '#f0f0f0', borderRadius: 4 }}>
                      {trackingData.status === 'DELIVERED' ? (
                        <Alert
                          message="快递已送达"
                          type="success"
                          showIcon
                        />
                      ) : trackingData.status === 'IN_TRANSIT' ? (
                        <Alert
                          message="快递运输中"
                          type="info"
                          showIcon
                        />
                      ) : trackingData.status === 'PICKED_UP' ? (
                        <Alert
                          message="快递已揽收"
                          type="info"
                          showIcon
                        />
                      ) : (
                        <Alert
                          message="快递已下单"
                          type="info"
                          showIcon
                        />
                      )}
                    </div>
                  </div>
                </Col>
              </Row>

              <Divider orientation="left">物流轨迹</Divider>
              <Timeline
                items={trackingData.timeline.map((item: any, index: number) => ({
                  color: item.status === 'DELIVERED' ? 'green' : 'blue',
                  children: (
                    <div>
                      <Text strong>{item.time}</Text>
                      <div style={{ marginTop: 4 }}>
                        <Text type="secondary">{item.location}</Text>
                      </div>
                      <div style={{ marginTop: 4 }}>{item.description}</div>
                    </div>
                  ),
                }))}
              />
            </Card>
          </>
        )}

        <Divider orientation="left">历史追踪记录</Divider>
        <Table
          columns={historyColumns}
          dataSource={trackingHistory}
          rowKey="id"
          pagination={{ pageSize: 10 }}
        />
      </Card>
    </div>
  );
};

export default LogisticsTracking;