import { queryLogList } from '@/services/logAudit';
import { EyeOutlined } from '@ant-design/icons';
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProFormDateTimeRangePicker,
  ProFormSelect,
  ProFormText,
  ProTable,
  QueryFilter,
} from '@ant-design/pro-components';
import { useIntl } from '@umijs/max';
import { Button, Tag, theme } from 'antd';
import React, { useRef, useState } from 'react';
import DetailDrawer from './components/DetailDrawer';
import {
  OPERATION_MODULE_COLORS,
  OPERATION_MODULE_LABELS,
  OPERATION_MODULE_OPTIONS,
  OPERATION_TYPE_COLORS,
  OPERATION_TYPE_LABELS,
  OPERATION_TYPE_OPTIONS,
  STATUS_OPTIONS,
} from './constants';
import type { LogItem, LogListParams } from './data';

const { useToken } = theme;

// 表格请求参数类型
type PaginationParams = {
  current?: number;
  pageSize?: number;
};

type SortParams = Record<string, 'ascend' | 'descend' | null>;

type FilterParams = Record<string, (string | number)[] | null>;

const LogAuditPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const intl = useIntl();
  const { token } = useToken();

  // 搜索参数状态
  const [searchParams, setSearchParams] = useState<LogListParams>({});

  // 详情抽屉状态
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [currentLog, setCurrentLog] = useState<LogItem | null>(null);

  // 表格列定义
  const columns: ProColumns<LogItem>[] = [
    {
      title: intl.formatMessage({
        id: 'logAudit.column.createdAt',
        defaultMessage: '操作时间',
      }),
      dataIndex: 'createdAt',
      valueType: 'dateTime',
      width: 160,
      sorter: true,
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.operatorName',
        defaultMessage: '操作人',
      }),
      dataIndex: 'operatorName',
      width: 120,
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.operationType',
        defaultMessage: '操作类型',
      }),
      dataIndex: 'operationType',
      width: 100,
      render: (_, record) => (
        <Tag color={OPERATION_TYPE_COLORS[record.operationType]}>
          {OPERATION_TYPE_LABELS[record.operationType]}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.operationModule',
        defaultMessage: '操作模块',
      }),
      dataIndex: 'operationModule',
      width: 100,
      render: (_, record) => (
        <Tag color={OPERATION_MODULE_COLORS[record.operationModule]}>
          {OPERATION_MODULE_LABELS[record.operationModule]}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.operationDesc',
        defaultMessage: '操作描述',
      }),
      dataIndex: 'operationDesc',
      width: 200,
      ellipsis: true,
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.ipAddress',
        defaultMessage: 'IP地址',
      }),
      dataIndex: 'ipAddress',
      width: 130,
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.executionTime',
        defaultMessage: '执行时长',
      }),
      dataIndex: 'executionTime',
      width: 100,
      render: (_, record) => `${record.executionTime}ms`,
      sorter: true,
    },
    {
      title: intl.formatMessage({
        id: 'logAudit.column.status',
        defaultMessage: '操作结果',
      }),
      dataIndex: 'status',
      width: 90,
      render: (_, record) => (
        <Tag color={record.status === 'success' ? 'success' : 'error'}>
          {record.status === 'success'
            ? intl.formatMessage({
                id: 'logAudit.status.success',
                defaultMessage: '成功',
              })
            : intl.formatMessage({
                id: 'logAudit.status.failure',
                defaultMessage: '失败',
              })}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({
        id: 'common.action',
        defaultMessage: '操作',
      }),
      dataIndex: 'option',
      valueType: 'option',
      width: 100,
      fixed: 'right',
      render: (_, record) => [
        <Button
          type="link"
          key="view"
          size="small"
          icon={<EyeOutlined />}
          onClick={() => {
            setCurrentLog(record);
            setDetailVisible(true);
          }}
        >
          {intl.formatMessage({
            id: 'logAudit.action.viewDetail',
            defaultMessage: '查看详情',
          })}
        </Button>,
      ],
    },
  ];

  // 处理搜索表单提交
  const handleSearchFinish = (values: LogListParams) => {
    // 处理时间范围
    const { timeRange, ...restValues } = values;
    if (timeRange && timeRange.length === 2) {
      setSearchParams({
        ...restValues,
        startTime: timeRange[0],
        endTime: timeRange[1],
      });
    } else {
      setSearchParams(restValues);
    }
    actionRef.current?.reload();
  };

  // 统一的卡片样式 - 使用 ProComponents 默认边距
  const cardStyle: React.CSSProperties = {
    background: token.colorBgContainer,
    borderRadius: token.borderRadius,
    marginBottom: token.marginLG,
  };

  // 表格请求方法
  const fetchLogList = async (
    params: PaginationParams,
    sort: SortParams,
    filter: FilterParams,
  ) => {
    const result = await queryLogList({
      ...searchParams,
      ...params,
      ...sort,
    });
    return {
      data: result.data || [],
      success: result.success,
      total: result.total || 0,
    };
  };

  return (
    <PageContainer
      header={{
        title: intl.formatMessage({
          id: 'logAudit.page.title',
          defaultMessage: '日志审计',
        }),
      }}
    >
      {/* 搜索区域 */}
      <div style={cardStyle}>
        <QueryFilter<LogListParams>
          layout="vertical"
          defaultColsNumber={4}
          onFinish={handleSearchFinish}
          onReset={() => {
            setSearchParams({});
            actionRef.current?.reload();
          }}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({
                id: 'common.search',
                defaultMessage: '查询',
              }),
              resetText: intl.formatMessage({
                id: 'common.reset',
                defaultMessage: '重置',
              }),
            },
          }}
        >
          <ProFormText
            name="operatorName"
            label={intl.formatMessage({
              id: 'logAudit.search.operatorName',
              defaultMessage: '操作人',
            })}
            placeholder={intl.formatMessage({
              id: 'logAudit.search.operatorNamePlaceholder',
              defaultMessage: '请输入操作人姓名',
            })}
          />
          <ProFormSelect
            name="operationType"
            label={intl.formatMessage({
              id: 'logAudit.search.operationType',
              defaultMessage: '操作类型',
            })}
            placeholder={intl.formatMessage({
              id: 'logAudit.search.operationTypePlaceholder',
              defaultMessage: '请选择操作类型',
            })}
            options={OPERATION_TYPE_OPTIONS.map((opt) => ({
              label: opt.label,
              value: opt.value,
            }))}
          />
          <ProFormSelect
            name="operationModule"
            label={intl.formatMessage({
              id: 'logAudit.search.operationModule',
              defaultMessage: '操作模块',
            })}
            placeholder={intl.formatMessage({
              id: 'logAudit.search.operationModulePlaceholder',
              defaultMessage: '请选择操作模块',
            })}
            options={OPERATION_MODULE_OPTIONS.map((opt) => ({
              label: opt.label,
              value: opt.value,
            }))}
          />
          <ProFormSelect
            name="status"
            label={intl.formatMessage({
              id: 'logAudit.search.status',
              defaultMessage: '操作结果',
            })}
            placeholder={intl.formatMessage({
              id: 'logAudit.search.statusPlaceholder',
              defaultMessage: '请选择操作结果',
            })}
            options={STATUS_OPTIONS.map((opt) => ({
              label: opt.label,
              value: opt.value,
            }))}
          />
          <ProFormText
            name="ipAddress"
            label={intl.formatMessage({
              id: 'logAudit.search.ipAddress',
              defaultMessage: 'IP地址',
            })}
            placeholder={intl.formatMessage({
              id: 'logAudit.search.ipAddressPlaceholder',
              defaultMessage: '请输入IP地址',
            })}
          />
          <ProFormDateTimeRangePicker
            name="timeRange"
            label={intl.formatMessage({
              id: 'logAudit.search.timeRange',
              defaultMessage: '时间范围',
            })}
            placeholder={[
              intl.formatMessage({
                id: 'logAudit.search.startTimePlaceholder',
                defaultMessage: '开始时间',
              }),
              intl.formatMessage({
                id: 'logAudit.search.endTimePlaceholder',
                defaultMessage: '结束时间',
              }),
            ]}
            fieldProps={{
              showTime: true,
              format: 'YYYY-MM-DD HH:mm:ss',
            }}
          />
        </QueryFilter>
      </div>

      {/* 表格区域 */}
      <div style={cardStyle}>
        <ProTable<LogItem>
          headerTitle={intl.formatMessage({
            id: 'logAudit.table.title',
            defaultMessage: '操作日志列表',
          })}
          actionRef={actionRef}
          rowKey="id"
          search={false}
          options={{
            reload: true,
            density: true,
            fullScreen: true,
            setting: true,
          }}
          columns={columns}
          request={fetchLogList}
          pagination={{
            pageSize: 20,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total: number) =>
              intl.formatMessage(
                {
                  id: 'logAudit.pagination.total',
                  defaultMessage: '共 {total} 条记录',
                },
                { total },
              ),
          }}
          scroll={{ x: 1200 }}
        />
      </div>

      {/* 详情抽屉 */}
      <DetailDrawer
        visible={detailVisible}
        logItem={currentLog}
        onClose={() => {
          setDetailVisible(false);
          setCurrentLog(null);
        }}
      />
    </PageContainer>
  );
};

export default LogAuditPage;
