import React from 'react';
import { Drawer, Tag, Descriptions } from 'antd';
import { formatDate } from '@/utils/date';
import styles from '../index.less';

interface UserInfo {
  userName: string;
  nickName: string;
}

interface OperationRecordItem {
  ID: number;
  CreatedAt: string;
  ip: string;
  method: string;
  path: string;
  status: number;
  latency: string;
  agent: string;
  error_message: string;
  body: string;
  resp: string;
  user_id: number;
  user: UserInfo;
}

interface RecordDetailProps {
  visible: boolean;
  record: OperationRecordItem | null;
  onClose: () => void;
}

const RecordDetail: React.FC<RecordDetailProps> = ({ visible, record, onClose }) => {
  // 格式化 JSON 内容
  const formatJson = (value: string) => {
    try {
      return JSON.stringify(JSON.parse(value), null, 2);
    } catch {
      return value;
    }
  };

  if (!record) return null;

  return (
    <Drawer
      title="操作记录详情"
      open={visible}
      onClose={onClose}
      width={800}
    >
      <Descriptions column={2} bordered size="small">
        <Descriptions.Item label="操作人">
          {record.user ? `${record.user.userName}(${record.user.nickName})` : '-'}
        </Descriptions.Item>
        <Descriptions.Item label="操作时间">
          {formatDate(record.CreatedAt)}
        </Descriptions.Item>
        <Descriptions.Item label="请求IP">{record.ip}</Descriptions.Item>
        <Descriptions.Item label="请求方法">{record.method}</Descriptions.Item>
        <Descriptions.Item label="请求路径" span={2}>
          {record.path}
        </Descriptions.Item>
        <Descriptions.Item label="状态码">
          <Tag
            color={record.status >= 200 && record.status < 300 ? 'success' : 'error'}
          >
            {record.status}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="耗时">{record.latency}</Descriptions.Item>
        {record.error_message && (
          <Descriptions.Item label="错误信息" span={2}>
            <span style={{ color: '#ff4d4f' }}>{record.error_message}</span>
          </Descriptions.Item>
        )}
      </Descriptions>

      <div className={styles.detailSection} style={{ marginTop: 24 }}>
        <h4>请求内容</h4>
        <div className={styles.codeBlock}>
          <pre>{record.body ? formatJson(record.body) : '无'}</pre>
        </div>
      </div>

      <div className={styles.detailSection}>
        <h4>响应内容</h4>
        <div className={styles.codeBlock}>
          <pre>{record.resp ? formatJson(record.resp) : '无'}</pre>
        </div>
      </div>
    </Drawer>
  );
};

export default RecordDetail;
