import React, { useState, useRef } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Popconfirm, message, Tag, Popover, Drawer } from 'antd';
import { DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import {
  getOperationRecordList,
  deleteOperationRecord,
  deleteOperationRecordByIds,
} from '@/services/kratos/operationRecord';
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;
}

const OperationRecordPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<OperationRecordItem | null>(null);

  // 格式化 JSON 内容
  const formatJson = (value: string) => {
    try {
      return JSON.stringify(JSON.parse(value), null, 2);
    } catch {
      return value;
    }
  };

  // 删除单条
  const handleDelete = async (record: OperationRecordItem) => {
    try {
      const res = await deleteOperationRecord({ ID: record.ID });
      if (res.code === 0) {
        message.success('删除成功');
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的数据');
      return;
    }
    try {
      const res = await deleteOperationRecordByIds({ ids: selectedRowKeys as number[] });
      if (res.code === 0) {
        message.success('删除成功');
        setSelectedRowKeys([]);
        actionRef.current?.reload();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 查看详情
  const handleViewDetail = (record: OperationRecordItem) => {
    setCurrentRecord(record);
    setDetailVisible(true);
  };

  // 渲染请求/响应内容弹出框
  const renderContentPopover = (content: string, title: string) => {
    if (!content) {
      return <span>无</span>;
    }
    return (
      <Popover
        title={title}
        content={
          <div className={styles.popoverBox}>
            <pre>{formatJson(content)}</pre>
          </div>
        }
        trigger="click"
        placement="left"
      >
        <EyeOutlined style={{ cursor: 'pointer', color: '#1890ff' }} />
      </Popover>
    );
  };

  const columns: ProColumns<OperationRecordItem>[] = [
    {
      title: '操作人',
      dataIndex: 'user',
      width: 140,
      search: false,
      render: (_, record) =>
        record.user ? `${record.user.userName}(${record.user.nickName})` : '-',
    },
    {
      title: '日期',
      dataIndex: 'CreatedAt',
      valueType: 'dateTime',
      width: 180,
      search: false,
      render: (_, record) => formatDate(record.CreatedAt),
    },
    {
      title: '状态码',
      dataIndex: 'status',
      width: 100,
      render: (_, record) => (
        <Tag color={record.status >= 200 && record.status < 300 ? 'success' : 'error'}>
          {record.status}
        </Tag>
      ),
    },
    {
      title: '请求IP',
      dataIndex: 'ip',
      width: 120,
      search: false,
    },
    {
      title: '请求方法',
      dataIndex: 'method',
      width: 100,
    },
    {
      title: '请求路径',
      dataIndex: 'path',
      width: 240,
      ellipsis: true,
    },
    {
      title: '请求',
      dataIndex: 'body',
      width: 80,
      search: false,
      render: (_, record) => renderContentPopover(record.body, '请求内容'),
    },
    {
      title: '响应',
      dataIndex: 'resp',
      width: 80,
      search: false,
      render: (_, record) => renderContentPopover(record.resp, '响应内容'),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除吗？"
          onConfirm={() => handleDelete(record)}
        >
          <Button type="link" size="small" danger>
            删除
          </Button>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<OperationRecordItem>
        actionRef={actionRef}
        columns={columns}
        rowKey="ID"
        scroll={{ x: 1200 }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        request={async (params) => {
          const res = await getOperationRecordList({
            page: params.current,
            pageSize: params.pageSize,
            method: params.method,
            path: params.path,
            status: params.status ? Number(params.status) : undefined,
          });
          return {
            data: res.data?.list || [],
            total: res.data?.total || 0,
            success: res.code === 0,
          };
        }}
        toolBarRender={() => [
          <Popconfirm
            key="batchDelete"
            title="确定要删除选中的数据吗？"
            onConfirm={handleBatchDelete}
            disabled={selectedRowKeys.length === 0}
          >
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRowKeys.length === 0}
            >
              删除
            </Button>
          </Popconfirm>,
        ]}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      <Drawer
        title="操作记录详情"
        open={detailVisible}
        onClose={() => {
          setDetailVisible(false);
          setCurrentRecord(null);
        }}
        width={800}
      >
        {currentRecord && (
          <div className={styles.detailContent}>
            <div className={styles.detailItem}>
              <span className={styles.label}>操作人：</span>
              <span>
                {currentRecord.user
                  ? `${currentRecord.user.userName}(${currentRecord.user.nickName})`
                  : '-'}
              </span>
            </div>
            <div className={styles.detailItem}>
              <span className={styles.label}>操作时间：</span>
              <span>{formatDate(currentRecord.CreatedAt)}</span>
            </div>
            <div className={styles.detailItem}>
              <span className={styles.label}>请求IP：</span>
              <span>{currentRecord.ip}</span>
            </div>
            <div className={styles.detailItem}>
              <span className={styles.label}>请求方法：</span>
              <span>{currentRecord.method}</span>
            </div>
            <div className={styles.detailItem}>
              <span className={styles.label}>请求路径：</span>
              <span>{currentRecord.path}</span>
            </div>
            <div className={styles.detailItem}>
              <span className={styles.label}>状态码：</span>
              <Tag
                color={
                  currentRecord.status >= 200 && currentRecord.status < 300
                    ? 'success'
                    : 'error'
                }
              >
                {currentRecord.status}
              </Tag>
            </div>
            <div className={styles.detailItem}>
              <span className={styles.label}>耗时：</span>
              <span>{currentRecord.latency}</span>
            </div>
            {currentRecord.error_message && (
              <div className={styles.detailItem}>
                <span className={styles.label}>错误信息：</span>
                <span className={styles.errorText}>{currentRecord.error_message}</span>
              </div>
            )}
            <div className={styles.detailSection}>
              <h4>请求内容</h4>
              <div className={styles.codeBlock}>
                <pre>{currentRecord.body ? formatJson(currentRecord.body) : '无'}</pre>
              </div>
            </div>
            <div className={styles.detailSection}>
              <h4>响应内容</h4>
              <div className={styles.codeBlock}>
                <pre>{currentRecord.resp ? formatJson(currentRecord.resp) : '无'}</pre>
              </div>
            </div>
          </div>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default OperationRecordPage;
