import React, { useState, useEffect } from 'react';
import { Modal, Table, Card, Tag, Space, Typography, Spin, Empty } from 'antd';
import { getBehaviorLog } from '@/services/mobileusers/list';

const { Text } = Typography;

export type BehaviorLogProps = {
  userId: string | number;
  userName: string;
  open: boolean;
  onCancel: () => void;
};

interface BehaviorLogItem {
  id: string;
  opTime: string;
  content: string;
  userId: string;
  [key: string]: any;
}

const BehaviorLogList: React.FC<BehaviorLogProps> = (props) => {
  const { userId, userName, open, onCancel } = props;

  const [loading, setLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<BehaviorLogItem[]>([]);
  const [total, setTotal] = useState<number>(0);
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);

  // 获取行为日志数据
  const fetchBehaviorLog = async (page: number = 1, size: number = 10) => {
    if (!userId) return;

    setLoading(true);
    try {
      const params = {
        userId: String(userId),
        current: page,
        pageSize: size,
      };

      const res = await getBehaviorLog(params);
      if (res.code === 200) {
        setDataSource(res.rows || []);
        setTotal(Number(res.total) || 0);
      } else {
        setDataSource([]);
        setTotal(0);
      }
    } catch (error) {
      console.error('获取用户行为日志失败:', error);
      setDataSource([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 当userId或open变化时重新获取数据
  useEffect(() => {
    if (open && userId) {
      fetchBehaviorLog(currentPage, pageSize);
    }
  }, [open, userId, currentPage, pageSize]);

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 格式化时间显示
  const formatTime = (timeStr: string) => {
    if (!timeStr) return '-';

    try {
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
      });
    } catch (error) {
      return timeStr;
    }
  };

  // 根据内容获取标签颜色
  const getTagColor = (content: string) => {
    if (!content) return 'default';

    const lowerContent = content.toLowerCase();
    if (lowerContent.includes('登录') || lowerContent.includes('登出')) {
      return 'blue';
    } else if (lowerContent.includes('浏览') || lowerContent.includes('查看')) {
      return 'green';
    } else if (lowerContent.includes('提交') || lowerContent.includes('申请')) {
      return 'purple';
    } else if (lowerContent.includes('修改') || lowerContent.includes('更新')) {
      return 'orange';
    } else if (lowerContent.includes('删除') || lowerContent.includes('取消')) {
      return 'red';
    } else {
      return 'default';
    }
  };

  // 表格列定义
  const columns = [
    {
      title: '序号',
      key: 'index',
      width: 100,
      align: 'center',
      render: (_: any, __: any, index: number) => {
        return (currentPage - 1) * pageSize + index + 1;
      },
    },
    {
      title: '操作时间',
      dataIndex: 'opTime',
      key: 'opTime',
      align: 'center',
      width: 180,
      render: (text: string) => (
        <Text type="secondary" style={{ fontSize: 12 }}>
          {formatTime(text)}
        </Text>
      ),
      sorter: (a: BehaviorLogItem, b: BehaviorLogItem) => {
        return new Date(a.opTime).getTime() - new Date(b.opTime).getTime();
      },
    },
    {
      title: '行为类型',
      key: 'actionType',
      align: 'center',
      width: 180,
      render: (_: any, record: BehaviorLogItem) => {
        const content = record.content || '';
        let type = '其他';

        if (content.includes('登录')) type = '登录';
        else if (content.includes('浏览') || content.includes('查看') ) type = '浏览';
        else if (content.includes('提交')) type = '提交';
        else if (content.includes('申请')) type = '申请';
        else if (content.includes('修改')) type = '修改';
        else if (content.includes('更新')) type = '更新';
        else if (content.includes('删除')) type = '删除';

        return (
          <Tag color={getTagColor(content)} style={{ margin: 0 }}>
            {type}
          </Tag>
        );
      },
    },
    {
      title: '操作行为',
      dataIndex: 'content',
      key: 'content',
      render: (text: string) => (
        <div>
          <Text type="secondary" style={{ lineHeight: 1.5 }}>
            {text}
          </Text>
        </div>
      ),
    },
  ];

  return (
    <Modal
      title={
        <Space>
          <span>用户行为记录</span>
          <Text type="secondary" style={{ fontSize: 14 }}>
            ({userName || '未知用户'})
          </Text>
        </Space>
      }
      open={open}
      onCancel={onCancel}
      width={1100}
      footer={null}
      bodyStyle={{ padding: 0 }}
    >
      <Spin spinning={loading}>
        <Card
          size="small"
          style={{ border: 'none' }}
          styles={{
            body: { padding: '16px 0 0 0' },
          }}
        >
          {/* 统计信息 */}
          {dataSource.length > 0 && (
            <Card
              size="small"
              style={{
                marginBottom: 16,
                backgroundColor: '#fafafa',
                border: '1px solid #f0f0f0',
              }}
            >
              <Space size={24} wrap>
                <div>
                  <Text type="secondary">用户ID：</Text>
                  <Text strong>{userId}</Text>
                </div>
                <div>
                  <Text type="secondary">用户名：</Text>
                  <Text strong>{userName}</Text>
                </div>
                <div>
                  <Text type="secondary">记录总数：</Text>
                  <Text strong style={{ color: '#1890ff' }}>
                    {total} 条
                  </Text>
                </div>
                <div>
                  <Text type="secondary">最近活动：</Text>
                  <Text strong>
                    {dataSource.length > 0 ? formatTime(dataSource[0].opTime) : '暂无'}
                  </Text>
                </div>
              </Space>
            </Card>
          )}
          {dataSource.length > 0 ? (
            <Table
              columns={columns}
              dataSource={dataSource}
              rowKey="id"
              pagination={{
                current: currentPage,
                pageSize: pageSize,
                total: total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `共 ${total} 条记录，显示 ${range[0]}-${range[1]} 条`,
                pageSizeOptions: ['10', '20', '30', '50'],
              }}
              onChange={handleTableChange}
              size="middle"
              scroll={{ y: 400 }}
              locale={{
                emptyText: (
                  <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无行为记录" />
                ),
              }}
              onRow={(record) => {
                return {
                  style: {
                    cursor: 'pointer',
                    transition: 'all 0.2s',
                  },
                  onMouseEnter: (e) => {
                    e.currentTarget.style.backgroundColor = '#f5f5f5';
                  },
                  onMouseLeave: (e) => {
                    e.currentTarget.style.backgroundColor = 'inherit';
                  },
                };
              }}
            />
          ) : (
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={
                <div>
                  <p>暂无行为记录</p>
                  <Text type="secondary">该用户目前没有记录的操作行为</Text>
                </div>
              }
              style={{ margin: '40px 0' }}
            />
          )}
        </Card>
      </Spin>
    </Modal>
  );
};

export default BehaviorLogList;
