import React, { useState, useEffect } from 'react';
import { Modal, Table, Tag, Button, Space } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { WorkflowHistoricalInstance } from '../types';
import { getHistoricalInstances } from '../service';
import DetailModal from './DetailModal';
import { DEFAULT_PAGE_SIZE, DEFAULT_CURRENT } from '@/utils/page';

interface HistoryModalProps {
    visible: boolean;
    onCancel: () => void;
    workflowDefinitionId?: number;
}

const HistoryModal: React.FC<HistoryModalProps> = ({ visible, onCancel, workflowDefinitionId }) => {
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState<WorkflowHistoricalInstance[]>([]);
    const [total, setTotal] = useState(0);
    const [query, setQuery] = useState({
        pageNum: DEFAULT_CURRENT - 1,
        pageSize: DEFAULT_PAGE_SIZE,
    });
    const [detailVisible, setDetailVisible] = useState(false);
    const [selectedInstance, setSelectedInstance] = useState<WorkflowHistoricalInstance>();

    useEffect(() => {
        setQuery(prev => ({
            ...prev,
            workflowDefinitionId
        }));
    }, [workflowDefinitionId]);

    const loadData = async () => {
        setLoading(true);
        try {
            const result = await getHistoricalInstances(query);
            setData(result.content || []);
            setTotal(result.totalElements || 0);
        } catch (error) {
            console.error('加载历史记录失败:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (visible) {
            loadData();
        }
    }, [visible, query]);

    const handleViewDetail = (record: WorkflowHistoricalInstance) => {
        setSelectedInstance(record);
        setDetailVisible(true);
    };

    const getStatusTag = (status: string) => {
        const statusMap: Record<string, { color: string; text: string }> = {
            COMPLETED: { color: 'success', text: '已完成' },
            RUNNING: { color: 'processing', text: '运行中' },
            FAILED: { color: 'error', text: '失败' },
            TERMINATED: { color: 'warning', text: '已终止' }
        };
        const statusInfo = statusMap[status] || { color: 'default', text: status };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
    };

    const columns: ColumnsType<WorkflowHistoricalInstance> = [
        {
            title: '业务标识',
            dataIndex: 'businessKey',
            key: 'businessKey',
            width: 200,
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: status => getStatusTag(status)
        },
        {
            title: '开始时间',
            dataIndex: 'startTime',
            key: 'startTime',
            width: 180,
        },
        {
            title: '结束时间',
            dataIndex: 'endTime',
            key: 'endTime',
            width: 180,
            render: time => time || '暂无'
        },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 100,
            render: (_, record) => (
                <Button type="link" onClick={() => handleViewDetail(record)}>
                    详情
                </Button>
            ),
        },
    ];

    return (
        <>
            <Modal
                title="历史执行记录"
                open={visible}
                onCancel={onCancel}
                width={1000}
                footer={null}
            >
                <Table
                    columns={columns}
                    dataSource={data}
                    loading={loading}
                    rowKey="id"
                    scroll={{ x: 800 }}
                    pagination={{
                        current: query.pageNum + 1,
                        pageSize: query.pageSize,
                        total: total,
                        onChange: (page, pageSize) => setQuery(prev => ({
                            ...prev,
                            pageNum: page - 1,
                            pageSize
                        })),
                        showSizeChanger: true,
                        showQuickJumper: true,
                    }}
                />
            </Modal>
            {selectedInstance && (
                <DetailModal
                    visible={detailVisible}
                    onCancel={() => setDetailVisible(false)}
                    instanceData={selectedInstance}
                />
            )}
        </>
    );
};

export default HistoryModal;
