
import React, { useState, useEffect } from 'react';
import { 
  Button, Table, Space,
  Form, Input, Select, message, 
  Card,  DatePicker, 
} from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
// 从share/types.ts导入所有类型，包括MapMode
import type { 
  AlertHandleLog, Attachment, 
} from '../share/monitorTypes.ts';

import {
  HandleType, ProblemType, 
  HandleTypeNameMap, ProblemTypeNameMap,
} from '../share/monitorTypes.ts';

import { AlertHandleAPI } from './api/index.ts';

// 告警处理记录页面
export const AlertHandleLogsPage = () => {
    const [loading, setLoading] = useState(false);
    const [alertHandleData, setAlertHandleData] = useState<AlertHandleLog[]>([]);
    const [pagination, setPagination] = useState({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    const [formRef] = Form.useForm();
    
    useEffect(() => {
      fetchAlertHandleData();
    }, [pagination.current, pagination.pageSize]);
  
    const fetchAlertHandleData = async () => {
      setLoading(true);
      try {
        const values = formRef.getFieldsValue();
        const params = {
          page: pagination.current,
          pageSize: pagination.pageSize,
          alert_id: values.alert_id,
          handler_id: values.handler_id,
          handle_type: values.handle_type,
          problem_type: values.problem_type,
          start_time: values.time?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
          end_time: values.time?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
        };
        
        const response = await AlertHandleAPI.getAlertHandleData(params);
        
        if (response) {
          setAlertHandleData(response.data || []);
          setPagination({
            ...pagination,
            total: response.total || 0,
          });
        }
      } catch (error) {
        console.error('获取告警处理记录失败:', error);
        message.error('获取告警处理记录失败');
      } finally {
        setLoading(false);
      }
    };
  
    const handleSearch = (values: any) => {
      setPagination({
        ...pagination,
        current: 1,
      });
      fetchAlertHandleData();
    };
  
    const handleTableChange = (newPagination: any) => {
      setPagination({
        ...pagination,
        current: newPagination.current,
        pageSize: newPagination.pageSize,
      });
    };
  
    const handleTypeOptions = [
      { label: '确认', value: HandleType.CONFIRM },
      { label: '解决', value: HandleType.RESOLVE },
      { label: '忽略', value: HandleType.IGNORE },
    ];
    
    const problemTypeOptions = [
      { label: '设备故障', value: ProblemType.DEVICE },
      { label: '网络故障', value: ProblemType.NETWORK },
      { label: '电源故障', value: ProblemType.POWER },
      { label: '施工影响', value: ProblemType.CONSTRUCTION },
      { label: '其他原因', value: ProblemType.OTHER },
    ];
  
    const columns = [
      {
        title: '记录ID',
        dataIndex: 'id',
        key: 'id',
        width: 80,
      },
      {
        title: '告警ID',
        dataIndex: 'alert_id',
        key: 'alert_id',
        width: 80,
      },
      {
        title: '处理人',
        dataIndex: 'handler_id',
        key: 'handler_id',
      },
      {
        title: '处理类型',
        dataIndex: 'handle_type',
        key: 'handle_type',
        render: (type: HandleType) => HandleTypeNameMap[type] || type,
      },
      {
        title: '问题类型',
        dataIndex: 'problem_type',
        key: 'problem_type',
        render: (type: ProblemType) => ProblemTypeNameMap[type] || type,
      },
      {
        title: '处理结果',
        dataIndex: 'handle_result',
        key: 'handle_result',
        ellipsis: true,
      },
      {
        title: '附件数',
        dataIndex: 'attachments',
        key: 'attachments',
        render: (attachments: Attachment[]) => attachments?.length || 0,
      },
      {
        title: '禁用通知',
        dataIndex: 'notify_disabled',
        key: 'notify_disabled',
        render: (value: number) => value === 1 ? '是' : '否',
      },
      {
        title: '处理时间',
        dataIndex: 'handle_time',
        key: 'handle_time',
        render: (text: Date) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        title: '操作',
        key: 'action',
        render: (_: any, record: AlertHandleLog) => (
          <Space size="middle">
            <Button size="small" onClick={() => message.info(`查看处理记录ID: ${record.id}`)}>
              查看
            </Button>
          </Space>
        ),
      },
    ];
  
    return (
      <div>
        <Card title="告警处理记录" style={{ marginBottom: 16 }}>
          <Form
            form={formRef}
            layout="inline"
            onFinish={handleSearch}
            style={{ marginBottom: 16 }}
          >
            <Form.Item name="alert_id" label="告警ID">
              <Input placeholder="输入告警ID" style={{ width: 120 }} />
            </Form.Item>
            <Form.Item name="handle_type" label="处理类型">
              <Select
                placeholder="选择处理类型"
                style={{ width: 150 }}
                allowClear
                options={handleTypeOptions}
              />
            </Form.Item>
            <Form.Item name="problem_type" label="问题类型">
              <Select
                placeholder="选择问题类型"
                style={{ width: 150 }}
                allowClear
                options={problemTypeOptions}
              />
            </Form.Item>
            <Form.Item name="time" label="处理时间">
              <DatePicker.RangePicker
                showTime
                style={{ width: 380 }}
              />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
          
          <Table
            columns={columns}
            dataSource={alertHandleData}
            rowKey="id"
            pagination={pagination}
            loading={loading}
            onChange={handleTableChange}
          />
        </Card>
      </div>
    );
  };