import React, { useState, useEffect, useCallback } from 'react';
import { Table, Card, Form, Input, DatePicker, Button, Space, Tag, message, Select } from 'antd';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import API_BASE_URL from '../config';
import { maskPhone, maskPhonesInText } from '../utils/phoneMask';

const { RangePicker } = DatePicker;
const { Option } = Select;

const SystemLogs = () => {
  const [logs, setLogs] = useState([]);
  const [descriptions, setDescriptions] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });
  const [filters, setFilters] = useState({});
  const [form] = Form.useForm();

  const fetchDescriptions = useCallback(async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/logs/descriptions`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      setDescriptions(response.data);
    } catch (error) {
      console.error('获取操作说明列表失败', error);
    }
  }, []);

  const fetchLogs = useCallback(async (page = 1, pageSize = 20, currentFilters = {}) => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const params = {
        page,
        limit: pageSize,
        ...currentFilters,
      };
      
      // 处理日期范围
      if (currentFilters.dateRange) {
        params.startDate = currentFilters.dateRange[0].format('YYYY-MM-DD 00:00:00');
        params.endDate = currentFilters.dateRange[1].format('YYYY-MM-DD 23:59:59');
        delete params.dateRange;
      }

      const response = await axios.get(`${API_BASE_URL}/api/logs`, {
        headers: { Authorization: `Bearer ${token}` },
        params,
      });

      setLogs(response.data.logs);
      setPagination({
        current: response.data.page,
        pageSize: pageSize,
        total: response.data.total,
      });
    } catch (error) {
      message.error('获取日志失败');
      console.error(error);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchLogs(1, 20);
    fetchDescriptions();
  }, [fetchLogs, fetchDescriptions]);

  const handleTableChange = (newPagination) => {
    fetchLogs(newPagination.current, newPagination.pageSize, filters);
  };

  const onFinish = (values) => {
    setFilters(values);
    fetchLogs(1, pagination.pageSize, values);
  };

  const handleReset = () => {
    form.resetFields();
    setFilters({});
    fetchLogs(1, 20, {});
  };

  const columns = [
    {
      title: '时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (text) => new Date(text).toLocaleString(),
    },
    {
      title: '操作人',
      key: 'user',
      width: 150,
      render: (_, record) => (
        record.real_name ? `${record.real_name} (${maskPhone(record.username)})` : (maskPhone(record.username) || 'Guest')
      ),
    },
    {
      title: 'IP地址',
      dataIndex: 'ip_address',
      key: 'ip_address',
      width: 140,
    },
    {
      title: '方法',
      dataIndex: 'method',
      key: 'method',
      width: 80,
      render: (text) => {
        let color = 'blue';
        if (text === 'GET') color = 'green';
        if (text === 'POST') color = 'blue';
        if (text === 'PUT') color = 'orange';
        if (text === 'DELETE') color = 'red';
        return <Tag color={color}>{text}</Tag>;
      }
    },
    {
      title: '操作说明',
      dataIndex: 'description',
      key: 'description',
      width: 150,
      render: (text) => maskPhonesInText(text) || '-',
    },
    {
      title: '请求路径',
      dataIndex: 'url',
      key: 'url',
      ellipsis: true,
      render: (text) => maskPhonesInText(text),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status) => {
        let color = 'green';
        if (status >= 400) color = 'orange';
        if (status >= 500) color = 'red';
        return <Tag color={color}>{status}</Tag>;
      }
    },
    {
      title: '耗时',
      dataIndex: 'duration',
      key: 'duration',
      width: 100,
      render: (text) => `${text}ms`,
    },
  ];

  return (
    <Card title="系统操作日志">
      <Form form={form} layout="inline" onFinish={onFinish} style={{ marginBottom: 24 }}>
        <Form.Item name="username" label="用户">
          <Input placeholder="姓名或手机号" allowClear />
        </Form.Item>
        <Form.Item name="description" label="操作说明" style={{ width: 200 }}>
          <Select placeholder="请选择操作说明" allowClear showSearch>
            {descriptions.map(desc => (
              <Option key={desc} value={desc}>{desc}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="dateRange" label="时间范围">
          <RangePicker showTime />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              查询
            </Button>
            <Button onClick={handleReset} icon={<ReloadOutlined />}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>

      <Table
        columns={columns}
        dataSource={logs}
        rowKey="id"
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
        loading={loading}
        onChange={handleTableChange}
        size="middle"
      />
    </Card>
  );
};

export default SystemLogs;
