/**
 * 设备日志页面
 * - 顶部过滤：柜子下拉 + 日志类型 + 时间范围
 * - 列表：分页展示设备日志
 */

import { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Select,
  DatePicker,
  Tag,
  Message,
} from '@arco-design/web-react';
import { IconSearch } from '@arco-design/web-react/icon';
import { api } from '@/api/request';

const { RangePicker } = DatePicker;

/** 设备日志项 */
interface DeviceLog {
  id: number;
  cabinet_id: number;
  cabinet_name: string | null;
  log_type: number;
  log_type_text: string;
  content: string | null;
  created_at: string | null;
}

/** 下拉选项 */
interface Option {
  id: number;
  name?: string;
  abstract_id?: string;
}

/** 日志类型选项 */
const LOG_TYPE_OPTIONS = [
  { label: '状态上报', value: 1 },
  { label: '故障', value: 2 },
  { label: '告警', value: 3 },
  { label: '停电', value: 4 },
];

/** 日志类型标签颜色 */
const LOG_TYPE_COLOR: Record<number, string> = {
  1: 'blue',
  2: 'red',
  3: 'orange',
  4: 'gray',
};

export default function DeviceLogs() {
  // 过滤条件
  const [cabinetId, setCabinetId] = useState<number | undefined>();
  const [logType, setLogType] = useState<number | undefined>();
  const [timeRange, setTimeRange] = useState<string[]>([]);

  // 下拉数据
  const [cabinets, setCabinets] = useState<Option[]>([]);

  // 列表数据
  const [data, setData] = useState<DeviceLog[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const pageSize = 20;

  /** 加载柜子下拉 */
  useEffect(() => {
    api.get<Option[]>('/cabinets/options')
      .then((res) => setCabinets(res.data || []))
      .catch(() => {});
  }, []);

  /** 构建查询参数 */
  const buildQuery = useCallback(() => {
    const params = new URLSearchParams();
    if (cabinetId) params.set('cabinet_id', String(cabinetId));
    if (logType) params.set('log_type', String(logType));
    if (timeRange[0]) params.set('start_time', timeRange[0]);
    if (timeRange[1]) params.set('end_time', timeRange[1]);
    params.set('page', String(page));
    params.set('page_size', String(pageSize));
    return params.toString();
  }, [cabinetId, logType, timeRange, page]);

  /** 加载列表数据 */
  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<{
        list: DeviceLog[];
        total: number;
      }>(`/device-logs?${buildQuery()}`);
      setData(res.data.list || []);
      setTotal(res.data.total || 0);
    } catch {
      Message.error('加载设备日志失败');
    } finally {
      setLoading(false);
    }
  }, [buildQuery]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  /** 查询按钮 */
  const handleSearch = () => {
    setPage(1);
    fetchData();
  };

  /** 截断内容摘要 */
  const truncateContent = (content: string | null, maxLen = 60): string => {
    if (!content) return '-';
    return content.length > maxLen ? `${content.slice(0, maxLen)}...` : content;
  };

  /** 表格列定义 */
  const columns = [
    {
      title: '柜子',
      dataIndex: 'cabinet_name',
      width: 160,
      render: (val: string | null, record: DeviceLog) =>
        val || `柜#${record.cabinet_id}`,
    },
    {
      title: '类型',
      dataIndex: 'log_type',
      width: 100,
      render: (type: number, record: DeviceLog) => (
        <Tag color={LOG_TYPE_COLOR[type] || 'gray'}>
          {record.log_type_text}
        </Tag>
      ),
    },
    {
      title: '内容摘要',
      dataIndex: 'content',
      width: 400,
      render: (val: string | null) => truncateContent(val),
    },
    {
      title: '时间',
      dataIndex: 'created_at',
      width: 170,
    },
  ];

  return (
    <Card>
      {/* 过滤区域 */}
      <Space wrap style={{ marginBottom: 16 }}>
        <Select
          placeholder="选择柜子"
          allowClear
          style={{ width: 200 }}
          value={cabinetId}
          onChange={(val) => setCabinetId(val || undefined)}
          options={cabinets.map((c) => ({
            label: c.name || c.abstract_id || `柜#${c.id}`,
            value: c.id,
          }))}
        />
        <Select
          placeholder="日志类型"
          allowClear
          style={{ width: 140 }}
          value={logType}
          onChange={(val) => setLogType(val || undefined)}
          options={LOG_TYPE_OPTIONS}
        />
        <RangePicker
          onChange={(dateString) => {
            setTimeRange(dateString as string[]);
          }}
        />
        <Button type="primary" icon={<IconSearch />} onClick={handleSearch}>
          查询
        </Button>
      </Space>

      {/* 数据表格 */}
      <Table
        rowKey="id"
        columns={columns}
        data={data}
        loading={loading}
        pagination={{
          current: page,
          total,
          pageSize,
          onChange: setPage,
          showTotal: true,
        }}
        size="default"
      />
    </Card>
  );
}
