/**
 * 物流管理页面
 * 作者: 阿瑞
 * 功能: 显示和管理物流记录，提供物流查询和状态更新
 * 版本: 1.0.0
 */

'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { useParams } from 'next/navigation';
import { useTheme } from '@/hooks';
import { useNotification } from '@/components/ui/Notification';
import { MdLocalShipping, MdSearch, MdRefresh, MdOutlineCheckCircleOutline } from 'react-icons/md';
import { ILogisticsRecord, ILogisticsRecordListItem, RecordType } from '@/models/team/types/ILogisticsRecord';
import { Spin, Tag, Table, Button, Input, Select, DatePicker, Modal, Alert, Collapse, Space } from 'antd';
import dayjs from 'dayjs';
import type { RangePickerProps } from 'antd/es/date-picker';

const { Panel } = Collapse;

type LogisticsStatus = '已填单' | '已揽件' | '运输中' | '已签收' | string | null | undefined;

/**
 * 格式化日期显示
 */
const formatDate = (dateStr: string | undefined) => {
  if (!dateStr) return '-';
  return dayjs(dateStr).format('YYYY-MM-DD HH:mm');
};

/**
 * 获取状态标签的类型和颜色
 */
const getStatusTag = (status: LogisticsStatus) => {
  if (!status) return { color: 'default', text: '未知' };
  
  switch (status) {
    case '已填单':
      return { color: 'default', text: '已填单' };
    case '已揽件':
      return { color: 'processing', text: '已揽件' };
    case '运输中':
      return { color: 'processing', text: '运输中' };
    case '已签收':
      return { color: 'success', text: '已签收' };
    default:
      return { color: 'processing', text: status };
  }
};

/**
 * 获取记录类型显示内容
 */
const getRecordTypeDisplay = (type: RecordType) => {
  switch (type) {
    case RecordType.SALES_RECORD:
      return { text: '销售单', color: 'blue' };
    case RecordType.AFTER_SALES_RECORD:
      return { text: '售后单', color: 'orange' };
    default:
      return { text: '未知', color: 'default' };
  }
};

/**
 * 定义物流路由项的接口
 */
interface LogisticsRoute {
  acceptTime?: string;
  time?: string;
  remark?: string;
  content?: string;
  acceptAddress?: string;
  location?: string;
}

/**
 * 定义物流详情的接口
 */
interface LogisticsDetails {
  routes?: LogisticsRoute[];
  msgData?: {
    routeResps?: Array<{
      routes?: LogisticsRoute[];
    }>;
  };
}

/**
 * 物流详情查看弹窗组件
 */
interface LogisticsDetailModalProps {
  visible: boolean;
  logisticsRecord: ILogisticsRecord | null;
  onClose: () => void;
  isDarkMode: boolean;
}

const LogisticsDetailModal: React.FC<LogisticsDetailModalProps> = ({ 
  visible, 
  logisticsRecord, 
  onClose,
  isDarkMode
}) => {
  const [parsedDetails, setParsedDetails] = useState<LogisticsDetails | null>(null);
  const [parseError, setParseError] = useState<string | null>(null);
  
  useEffect(() => {
    if (logisticsRecord?.details) {
      try {
        const details = JSON.parse(logisticsRecord.details) as LogisticsDetails;
        console.log('解析的物流详情数据:', details);
        setParsedDetails(details);
        setParseError(null);
      } catch (error) {
        console.error('解析物流详情失败:', error, logisticsRecord.details);
        setParsedDetails(null);
        setParseError(`解析物流详情失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    } else {
      setParsedDetails(null);
      setParseError(null);
    }
  }, [logisticsRecord]);
  
  // 判断是否有物流路由数据
  const hasRoutesData = parsedDetails?.routes && parsedDetails.routes.length > 0;
  
  return (
    <Modal
      title={
        <div className="flex items-center">
          <MdLocalShipping className="mr-2 text-blue-500" size={20} />
          <span>物流详情</span>
        </div>
      }
      open={visible}
      onCancel={onClose}
      footer={[
        <Button key="close" onClick={onClose}>
          关闭
        </Button>
      ]}
      width={700}
    >
      {logisticsRecord ? (
        <div className="space-y-4">
          <div className={`p-4 rounded-lg ${isDarkMode ? 'bg-gray-800' : 'bg-gray-50'}`}>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <div className="text-gray-500 text-sm">物流单号:</div>
                <div className="font-medium">{logisticsRecord.tracking_number || '-'}</div>
              </div>
              <div>
                <div className="text-gray-500 text-sm">物流公司:</div>
                <div className="font-medium">{logisticsRecord.company || '-'}</div>
              </div>
              <div>
                <div className="text-gray-500 text-sm">状态:</div>
                <div>
                  <Tag color={getStatusTag(logisticsRecord.status).color}>
                    {getStatusTag(logisticsRecord.status).text}
                  </Tag>
                </div>
              </div>
              <div>
                <div className="text-gray-500 text-sm">发货时间:</div>
                <div className="font-medium">{formatDate(logisticsRecord.created_at)}</div>
              </div>
              <div>
                <div className="text-gray-500 text-sm">客户手机尾号:</div>
                <div className="font-medium">{logisticsRecord.customer_tail_number || '-'}</div>
              </div>
              <div>
                <div className="text-gray-500 text-sm">记录类型:</div>
                <div>
                  <Tag color={getRecordTypeDisplay(logisticsRecord.record_type).color}>
                    {getRecordTypeDisplay(logisticsRecord.record_type).text}
                  </Tag>
                </div>
              </div>
            </div>
          </div>
          
          {/* 原始数据查看 */}
          <Collapse>
            <Panel header="查看原始数据" key="1">
              <pre className={`p-3 rounded text-xs overflow-auto ${isDarkMode ? 'bg-gray-900 text-gray-300' : 'bg-gray-100 text-gray-800'}`} style={{ maxHeight: '200px' }}>
                {JSON.stringify(logisticsRecord, null, 2)}
              </pre>
            </Panel>
          </Collapse>
          
          {/* 解析错误提示 */}
          {parseError && (
            <Alert
              message="解析错误"
              description={parseError}
              type="error"
              showIcon
            />
          )}
          
          {/* 物流详情 */}
          <div className={`p-4 rounded-lg ${isDarkMode ? 'bg-gray-800' : 'bg-gray-50'}`}>
            <h3 className="font-medium mb-3 flex items-center">
              <MdOutlineCheckCircleOutline className="mr-1 text-green-500" />
              物流跟踪信息
            </h3>
            
            {hasRoutesData ? (
              <div className="relative pl-6">
                {/* 时间轴线 */}
                <div className="absolute left-3 top-2 bottom-2 w-0.5 bg-gray-300 dark:bg-gray-600"></div>
                
                <div className="space-y-4">
                  {parsedDetails?.routes?.map((route, index) => {
                    // 提取路由节点显示数据
                    const time = route.acceptTime || route.time || '-';
                    const content = route.remark || route.content || '未知状态';
                    const location = route.acceptAddress || route.location || null;
                    
                    return (
                      <div key={index} className="relative">
                        {/* 时间轴节点 */}
                        <div className={`absolute -left-6 top-1 z-10 w-3 h-3 rounded-full ${
                          index === 0 ? 'bg-green-500' : 'bg-blue-500'
                        }`}></div>
                        
                        <div className={`p-3 rounded ${isDarkMode ? 'bg-gray-700' : 'bg-white border border-gray-200'}`}>
                          <div className="text-xs text-gray-500">
                            {time}
                          </div>
                          <div className="font-medium mb-1">
                            {content}
                          </div>
                          {location && (
                            <div className="text-sm text-gray-500">
                              {location}
                            </div>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            ) : (
              <div className="py-6 text-center text-gray-500">
                {logisticsRecord.is_queryable ? '暂无物流跟踪信息' : '该物流单号不支持查询'}
              </div>
            )}
          </div>
        </div>
      ) : (
        <div className="py-8 text-center">
          <Spin tip="加载中..." />
        </div>
      )}
    </Modal>
  );
};

/**
 * 修改调试信息类型
 */
interface DebugInfo {
  lastQuery: string | null;
  lastResponse: Record<string, unknown> | null;
  error: string | null;
  showDebug: boolean;
}

/**
 * 物流管理页面组件
 */
export default function LogisticsPage() {
  const params = useParams();
  const teamCode = params?.teamCode as string;
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [logisticsRecords, setLogisticsRecords] = useState<ILogisticsRecordListItem[]>([]);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<ILogisticsRecord | null>(null);
  const [queryLoading, setQueryLoading] = useState<number | null>(null);
  const [searchParams, setSearchParams] = useState({
    trackingNumber: '',
    status: '',
    dateRange: null as [dayjs.Dayjs, dayjs.Dayjs] | null,
    customerTailNumber: ''
  });
  
  // 在组件内使用该类型
  const [debugInfo, setDebugInfo] = useState<DebugInfo>({
    lastQuery: null,
    lastResponse: null,
    error: null,
    showDebug: false
  });
  
  const notification = useNotification();
  const { isDarkMode } = useTheme();
  
  /**
   * 加载物流记录列表
   */
  const loadLogisticsRecords = useCallback(async (showLoading = true) => {
    if (showLoading) {
      setLoading(true);
    } else {
      setRefreshing(true);
    }
    
    try {
      // 构建查询参数
      const queryParams = new URLSearchParams();
      
      if (searchParams.trackingNumber) {
        queryParams.append('trackingNumber', searchParams.trackingNumber);
      }
      
      if (searchParams.status) {
        queryParams.append('status', searchParams.status);
      }
      
      if (searchParams.customerTailNumber) {
        queryParams.append('customerTailNumber', searchParams.customerTailNumber);
      }
      
      if (searchParams.dateRange && searchParams.dateRange[0] && searchParams.dateRange[1]) {
        queryParams.append('startDate', searchParams.dateRange[0].format('YYYY-MM-DD'));
        queryParams.append('endDate', searchParams.dateRange[1].format('YYYY-MM-DD'));
      }
      
      const url = `/api/team/${teamCode}/logistics?${queryParams.toString()}`;
      setDebugInfo(prev => ({ ...prev, lastQuery: url, error: null }));
      
      const response = await fetch(url);
      const data = await response.json();
      
      setDebugInfo(prev => ({ ...prev, lastResponse: data }));
      
      if (!response.ok) {
        throw new Error(data.error || '获取物流记录失败');
      }
      
      setLogisticsRecords(data.records || []);
      
    } catch (error) {
      console.error('加载物流记录失败:', error);
      notification.error('加载物流记录失败，请稍后重试');
      setDebugInfo(prev => ({ 
        ...prev, 
        error: error instanceof Error ? error.message : String(error) 
      }));
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [teamCode, searchParams, notification]);
  
  /**
   * 查询单个物流详情
   */
  const queryLogisticsDetails = async (record: ILogisticsRecordListItem) => {
    if (!record.tracking_number || !record.customer_tail_number) {
      notification.warning('物流单号或客户手机尾号缺失，无法查询物流信息');
      return;
    }
    
    // 设置当前记录为查询中状态
    setQueryLoading(record.id);
    
    try {
      const url = `/api/team/${teamCode}/logistics/query`;
      setDebugInfo(prev => ({ ...prev, lastQuery: url, error: null }));
      
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          id: record.id,
          trackingNumber: record.tracking_number,
          phoneLast4Digits: record.customer_tail_number
        })
      });
      
      const data = await response.json();
      setDebugInfo(prev => ({ ...prev, lastResponse: data }));
      
      if (!response.ok) {
        // 提取详细错误信息
        const errorDetails = data.details || {};
        const errorMessage = data.error || '查询物流信息失败';
        const apiErrorCode = errorDetails.apiResultCode || 'UNKNOWN';
        const apiErrorMsg = errorDetails.apiErrorMsg || '未知错误';
        
        throw new Error(`${errorMessage}\n错误码: ${apiErrorCode}\n详情: ${apiErrorMsg}`);
      }
      
      // 查询成功，显示结果弹窗
      setSelectedRecord(data.data);
      setDetailModalVisible(true);
      
      // 刷新列表数据
      loadLogisticsRecords(false);
      
      notification.success('物流信息查询成功');
      
    } catch (error) {
      console.error('查询物流信息失败:', error);
      notification.error(
        error instanceof Error ? error.message : '查询物流信息失败'
      );
      
      setDebugInfo(prev => ({ 
        ...prev, 
        error: error instanceof Error ? error.message : String(error) 
      }));
    } finally {
      setQueryLoading(null);
    }
  };
  
  /**
   * 处理表单字段变更
   */
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleSearchChange = (field: string, value: any) => {
    // 处理日期范围类型，确保格式一致
    if (field === 'dateRange' && Array.isArray(value) && value[0] && value[1]) {
      // 只有当两个日期都有效时才设置日期范围
      setSearchParams(prev => ({
        ...prev,
        dateRange: [value[0], value[1]]
      }));
    } else {
      setSearchParams(prev => ({
        ...prev,
        [field]: value
      }));
    }
  };
  
  /**
   * 处理表单重置
   */
  const handleResetSearch = () => {
    setSearchParams({
      trackingNumber: '',
      status: '',
      dateRange: null,
      customerTailNumber: ''
    });
  };
  
  /**
   * 处理表单提交
   */
  const handleSubmitSearch = () => {
    loadLogisticsRecords();
  };
  
  /**
   * 更新所有物流状态
   */
  const updateAllLogisticsStatus = async () => {
    setRefreshing(true);
    try {
      const url = `/api/team/${teamCode}/logistics/update-status`;
      setDebugInfo(prev => ({ ...prev, lastQuery: url, error: null }));
      
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      const data = await response.json();
      setDebugInfo(prev => ({ ...prev, lastResponse: data }));
      
      if (!response.ok) {
        throw new Error(data.error || '更新物流状态失败');
      }
      
      notification.success('物流状态更新成功！');
      
      // 重新加载物流记录
      loadLogisticsRecords(false);
      
    } catch (error) {
      console.error('更新物流状态失败:', error);
      notification.error('更新物流状态失败，请稍后重试');
      setDebugInfo(prev => ({ 
        ...prev, 
        error: error instanceof Error ? error.message : String(error) 
      }));
    } finally {
      setRefreshing(false);
    }
  };
  
  /**
   * 初始加载物流记录
   */
  useEffect(() => {
    if (teamCode) {
      loadLogisticsRecords();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [teamCode]);
  
  /**
   * 表格列定义
   */
  const columns = [
    {
      title: '物流单号',
      dataIndex: 'tracking_number',
      key: 'tracking_number',
      render: (text: string) => text || '-'
    },
    {
      title: '物流公司',
      dataIndex: 'company',
      key: 'company',
      render: (text: string) => text || '-'
    },
    {
      title: '客户手机尾号',
      dataIndex: 'customer_tail_number',
      key: 'customer_tail_number',
      render: (text: string) => text || '-'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: string | null | undefined) => (
        <Tag color={getStatusTag(status).color}>
          {getStatusTag(status).text}
        </Tag>
      )
    },
    {
      title: '记录类型',
      dataIndex: 'record_type',
      key: 'record_type',
      render: (type: RecordType) => (
        <Tag color={getRecordTypeDisplay(type).color}>
          {getRecordTypeDisplay(type).text}
        </Tag>
      )
    },
    {
      title: '物流详情',
      dataIndex: 'details',
      key: 'details',
      render: (details: string) => {
        if (!details) return '-';
        try {
          const parsedDetails = JSON.parse(details);
          // 检查是否有路由信息，适配不同格式
          const routes = parsedDetails?.routes || [];
          
          if (routes.length > 0) {
            // 获取最新的物流节点信息
            const latestRoute = routes[0];
            // 适配不同的字段名
            const content = latestRoute.remark || latestRoute.content || '';
            
            return (
              <div>
                <Tag color="blue">{routes.length}条记录</Tag>
                <div className="text-xs text-gray-500 mt-1 truncate" style={{ maxWidth: '150px' }}>
                  {content}
                </div>
              </div>
            );
          } else {
            return <Tag color="default">无详情</Tag>;
          }
        } catch (e) {
          console.error('解析物流详情失败:', e, details);
          return <Tag color="red">格式错误</Tag>;
        }
      }
    },
    {
      title: '可查询',
      dataIndex: 'is_queryable',
      key: 'is_queryable',
      render: (isQueryable: boolean) => (
        isQueryable ? 
          <Tag color="success">可查询</Tag> : 
          <Tag color="default">不可查询</Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => formatDate(date)
    },
    {
      title: '操作',
      key: 'action',
      render: (_: unknown, record: ILogisticsRecordListItem) => (
        <div className="space-x-2">
          <Button 
            type="primary" 
            size="small"
            icon={<MdSearch />}
            loading={queryLoading === record.id}
            disabled={!record.is_queryable || !record.customer_tail_number}
            onClick={() => queryLogisticsDetails(record)}
          >
            查询物流
          </Button>
        </div>
      )
    }
  ];
  
  return (
    <div className="pb-8">
      <div className="flex justify-between items-center mb-6">
        <div>
          <h1 className="text-2xl font-bold flex items-center">
            <MdLocalShipping className="mr-2 text-blue-500" />
            物流管理
          </h1>
          <p className={`mt-1 ${isDarkMode ? 'text-gray-400' : 'text-gray-500'}`}>
            管理和查询物流信息，跟踪物流状态
          </p>
        </div>
        
        <Space>
          <Button
            type="primary"
            icon={<MdRefresh />}
            loading={refreshing}
            onClick={updateAllLogisticsStatus}
          >
            {refreshing ? '更新中...' : '更新物流状态'}
          </Button>
        </Space>
      </div>
      
      {/* 搜索面板 */}
      <div className={`p-4 mb-6 rounded-lg ${isDarkMode ? 'bg-gray-800' : 'bg-white border border-gray-200'}`}>
        <div className="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-5 gap-4">
          <div>
            <div className="mb-1 text-sm">物流单号</div>
            <Input
              placeholder="输入物流单号"
              value={searchParams.trackingNumber}
              onChange={(e) => handleSearchChange('trackingNumber', e.target.value)}
              allowClear
            />
          </div>
          
          <div>
            <div className="mb-1 text-sm">物流状态</div>
            <Select
              placeholder="选择物流状态"
              value={searchParams.status}
              onChange={(value) => handleSearchChange('status', value)}
              style={{ width: '100%' }}
              allowClear
            >
              <Select.Option value="已填单">已填单</Select.Option>
              <Select.Option value="已揽件">已揽件</Select.Option>
              <Select.Option value="运输中">运输中</Select.Option>
              <Select.Option value="已签收">已签收</Select.Option>
            </Select>
          </div>
          
          <div>
            <div className="mb-1 text-sm">客户手机尾号</div>
            <Input
              placeholder="输入客户手机尾号"
              value={searchParams.customerTailNumber}
              onChange={(e) => handleSearchChange('customerTailNumber', e.target.value)}
              allowClear
            />
          </div>
          
          <div>
            <div className="mb-1 text-sm">日期范围</div>
            <DatePicker.RangePicker
              value={searchParams.dateRange}
              onChange={(dates) => handleSearchChange('dateRange', dates as RangePickerProps['value'])}
              style={{ width: '100%' }}
            />
          </div>
          
          <div className="flex items-end space-x-2">
            <Button type="primary" onClick={handleSubmitSearch}>
              搜索
            </Button>
            <Button onClick={handleResetSearch}>
              重置
            </Button>
          </div>
        </div>
      </div>
      
      {/* 物流列表 */}
      <div className={`rounded-lg overflow-hidden ${isDarkMode ? '' : 'border border-gray-200'}`}>
        <Table
          columns={columns}
          dataSource={logisticsRecords}
          rowKey="id"
          loading={loading}
          pagination={{
            defaultPageSize: 10,
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条记录`
          }}
          locale={{
            emptyText: <div className="py-8 text-center text-gray-500">
              <MdLocalShipping size={32} className="mx-auto mb-2 opacity-50" />
              {debugInfo.error ? '加载物流记录出错' : '暂无物流记录'} 
              {logisticsRecords.length === 0 && !loading && !debugInfo.error && (
                <div className="mt-2">
                  <Button type="link" onClick={() => loadLogisticsRecords()}>点击重新加载</Button>
                </div>
              )}
            </div>
          }}
        />
      </div>
      
      {/* 物流详情弹窗 */}
      <LogisticsDetailModal
        visible={detailModalVisible}
        logisticsRecord={selectedRecord}
        onClose={() => setDetailModalVisible(false)}
        isDarkMode={isDarkMode}
      />
    </div>
  );
}
