import React, {useState, useEffect} from 'react';
import {PageContainer} from '@ant-design/pro-components';
import {Button, message, Popconfirm, Select, Space, Modal, Tooltip} from 'antd';
import {PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, FullscreenOutlined} from '@ant-design/icons';
import {getDeploymentConfigPage, deleteDeploymentConfig, getDeployConfigTemplates} from './service';
import {getEnvironmentList} from '../../Environment/List/service';
import type {DeploymentConfig, DeploymentConfigQueryParams, DeployConfigTemplate} from './types';
import type {Environment} from '../../Environment/List/types';
import DeploymentConfigModal from './components/DeploymentConfigModal';
import {ProTable} from '@ant-design/pro-components';
import type {ProColumns, ActionType} from '@ant-design/pro-components';
import {Editor} from '@/components/Editor';

const {Option} = Select;

const CodePreviewModal: React.FC<{
    open: boolean;
    onCancel: () => void;
    code: string;
    language?: string;
}> = ({open, onCancel, code, language = 'shell'}) => {
    const [isFullscreen, setIsFullscreen] = useState(false);

    // 当模态��打开或关闭时重置全屏状态
    useEffect(() => {
        setIsFullscreen(false);
    }, [open]);

    return (
        <Modal
            title={
                <Space>
                    代码预览
                    <Button
                        type="text"
                        icon={<FullscreenOutlined/>}
                        onClick={() => setIsFullscreen(!isFullscreen)}
                    />
                </Space>
            }
            open={open}
            onCancel={() => {
                onCancel();
                setIsFullscreen(false);
            }}
            footer={null}
            width={isFullscreen ? "100vw" : 800}
            style={isFullscreen ? {
                top: 0,
                paddingBottom: 0
            } : undefined}
            wrapClassName={isFullscreen ? 'fullscreen-modal' : undefined}
            styles={{
                body: {padding: 0}
            }}
            destroyOnClose
        >
            <Editor
                height={isFullscreen ? "calc(100vh - 100px)" : "500px"}
                defaultLanguage={language}
                value={code}
                options={{
                    readOnly: true,
                    minimap: {enabled: true},
                    scrollBeyondLastLine: false,
                    automaticLayout: true,
                    contextmenu: true,
                }}
            />
        </Modal>
    );
};

const DeploymentConfigList: React.FC = () => {
    const [environments, setEnvironments] = useState<Environment[]>([]);
    const [selectedEnvId, setSelectedEnvId] = useState<number>();
    const [modalVisible, setModalVisible] = useState(false);
    const [currentConfig, setCurrentConfig] = useState<DeploymentConfig>();
    const [templates, setTemplates] = useState<DeployConfigTemplate[]>([]);
    const [codePreviewVisible, setCodePreviewVisible] = useState(false);
    const [previewCode, setPreviewCode] = useState<{ code: string; language?: string }>({code: ''});
    const [loading, setLoading] = useState(true);
    const actionRef = React.useRef<ActionType>();

    // 获取环境列表
    const fetchEnvironments = async () => {
        try {
            setLoading(true);
            const data = await getEnvironmentList();
            setEnvironments(data);
            if (data.length > 0) {
                setSelectedEnvId(data[0].id);
                // 手动触发表格刷新
                actionRef.current?.reload();
            }
        } catch (error) {
            message.error('获取环境列表失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取��置模板
    const fetchTemplates = async () => {
        try {
            const data = await getDeployConfigTemplates();
            setTemplates(data);
        } catch (error) {
            message.error('获取配置模板失败');
        }
    };

    // 初始化数据
    useEffect(() => {
        fetchEnvironments();
        fetchTemplates();
    }, []);

    const handleDelete = async (id: number) => {
        try {
            await deleteDeploymentConfig(id);
            message.success('删除成功');
            actionRef.current?.reload();
        } catch (error) {
            message.error('删除失败');
        }
    };

    const handleAdd = () => {
        if (!selectedEnvId) {
            message.warning('请先选择环境');
            return;
        }
        setCurrentConfig(undefined);
        setModalVisible(true);
    };

    const handleEdit = (config: DeploymentConfig) => {
        setCurrentConfig(config);
        setModalVisible(true);
    };

    const handleEnvChange = (value: number) => {
        setSelectedEnvId(value);
        actionRef.current?.reload();
    };

    const handleModalClose = () => {
        setModalVisible(false);
        setCurrentConfig(undefined);
    };

    const handleSuccess = () => {
        setModalVisible(false);
        setCurrentConfig(undefined);
        actionRef.current?.reload();
    };

    // 处理代码预览
    const handleCodePreview = (code: string, language?: string) => {
        setPreviewCode({code, language});
        setCodePreviewVisible(true);
    };

    // 根据模板获取构建配置的子列
    const getBuildConfigColumns = () => {
        const buildConfigColumns: ProColumns<DeploymentConfig>[] = [];

        // 获取所有可能的字段和它们的标题
        const fieldInfo = new Map<string, { title: string }>();
        templates.forEach(template => {
            if (template.buildVariablesSchema?.properties) {
                Object.entries(template.buildVariablesSchema.properties).forEach(([key, property]) => {
                    if (!fieldInfo.has(key)) {
                        fieldInfo.set(key, {
                            title: property.title || key
                        });
                    }
                });
            }
        });

        // 为每个字段创建一个列
        fieldInfo.forEach((info, field) => {
            buildConfigColumns.push({
                title: info.title,
                dataIndex: ['buildVariables', field],
                width: 150,
                ellipsis: true,
                render: (_, record) => {
                    // 找到对应的模板
                    const template = templates.find(t =>
                        t.buildType === record.buildType &&
                        t.languageType === record.languageType
                    );

                    if (!template?.buildVariablesSchema?.properties?.[field]) {
                        return '-';
                    }

                    const value = record.buildVariables?.[field];
                    if (!value) return '-';

                    // 如果是富文本编辑器字段
                    const fieldProperties = template?.buildVariablesSchema?.properties?.[field];
                    if (fieldProperties?.editorConfig) {
                        const shortContent = value.length > 50 ? value.slice(0, 50) + '...' : value;
                        return (
                            <Space>
                                <Tooltip title="点击查看完整内容">
                                    <Button
                                        type="link"
                                        icon={<EyeOutlined/>}
                                        onClick={() => handleCodePreview(
                                            value,
                                            fieldProperties.editorConfig?.language
                                        )}
                                    >
                                        {shortContent}
                                    </Button>
                                </Tooltip>
                            </Space>
                        );
                    }

                    // 普通字段，如果内容过长则使用 Tooltip
                    if (value.length > 50) {
                        return (
                            <Tooltip title={value}>
                                {value.slice(0, 50) + '...'}
                            </Tooltip>
                        );
                    }

                    return value;
                }
            });
        });

        return buildConfigColumns;
    };

    const columns: ProColumns<DeploymentConfig>[] = [
        {
            title: '应用编码',
            dataIndex: ['application', 'appCode'],
            width: 150,
            copyable: true,
            ellipsis: true,
            fixed: 'left',
        },
        {
            title: '应用名称',
            dataIndex: ['application', 'appName'],
            width: 150,
            ellipsis: true,
        },
        {
            title: '工作流',
            dataIndex: ['publishedWorkflowDefinition', 'name'],
            width: 200,
            ellipsis: true,
            render: (_, record) => {
                const workflow = record.publishedWorkflowDefinition;
                if (!workflow) return '-';
                return (
                    <Tooltip title={`${workflow.name} (${workflow.key})`}>
                        <span>{workflow.name}</span>
                    </Tooltip>
                );
            }
        },
        {
            title: '构建配置',
            children: getBuildConfigColumns()
        },
        {
            title: '状态',
            dataIndex: 'enabled',
            width: 100,
            valueEnum: {
                true: {text: '启用', status: 'Success'},
                false: {text: '禁用', status: 'Default'},
            },
        },
        {
            title: '操作',
            width: 180,
            key: 'action',
            valueType: 'option',
            fixed: 'right',
            render: (_, record) => [
                <Button
                    key="edit"
                    type="link"
                    onClick={() => handleEdit(record)}
                >
                    <Space>
                        <EditOutlined/>
                        编辑
                    </Space>
                </Button>,
                <Popconfirm
                    key="delete"
                    title="确定要删除该部署配置吗？"
                    description="删除后将无法恢复，请谨慎操作"
                    onConfirm={() => handleDelete(record.id)}
                >
                    <Button
                        type="link"
                        danger
                    >
                        <Space>
                            <DeleteOutlined/>
                            删除
                        </Space>
                    </Button>
                </Popconfirm>
            ],
        },
    ];

    return (
        <PageContainer
            header={{
                title: '部署配置管理',
                extra: [
                    <Select
                        key="env-select"
                        value={selectedEnvId}
                        onChange={handleEnvChange}
                        style={{width: 200}}
                        placeholder="请选择环境"
                        loading={loading}
                    >
                        {environments.map((env) => (
                            <Option key={env.id} value={env.id}>
                                {env.envName}
                            </Option>
                        ))}
                    </Select>,
                ],
            }}
        >
            <ProTable<DeploymentConfig>
                columns={columns}
                actionRef={actionRef}
                scroll={{x: 'max-content'}}
                cardBordered
                rowKey="id"
                search={false}
                options={{
                    setting: false,
                    density: false,
                    fullScreen: false,
                    reload: false,
                }}
                toolbar={{
                    actions: [
                        <Button
                            key="add"
                            type="primary"
                            onClick={handleAdd}
                            icon={<PlusOutlined/>}
                            disabled={!selectedEnvId}
                        >
                            新建部署配置
                        </Button>
                    ],
                }}
                pagination={{
                    pageSize: 10,
                    showQuickJumper: true,
                }}
                request={async (params) => {
                    if (!selectedEnvId || loading) {
                        return {
                            data: [],
                            success: true,
                            total: 0,
                        };
                    }
                    try {
                        const queryParams: DeploymentConfigQueryParams = {
                            pageSize: params.pageSize,
                            pageNum: params.current,
                            environmentId: selectedEnvId,
                            enabled: params.enabled as boolean,
                            workflowDefinitionId: params.workflowDefinitionId as number
                        };
                        const data = await getDeploymentConfigPage(queryParams);
                        return {
                            data: data.content || [],
                            success: true,
                            total: data.totalElements || 0,
                        };
                    } catch (error) {
                        message.error('获取部署配置列表失败');
                        return {
                            data: [],
                            success: false,
                            total: 0,
                        };
                    }
                }}
            />

            {modalVisible && selectedEnvId && (
                <DeploymentConfigModal
                    open={modalVisible}
                    onCancel={handleModalClose}
                    onSuccess={handleSuccess}
                    environmentId={selectedEnvId!}
                    buildType={environments.find(env => env.id === selectedEnvId)?.buildType || ''}
                    initialValues={currentConfig}
                />
            )}

            <CodePreviewModal
                open={codePreviewVisible}
                onCancel={() => setCodePreviewVisible(false)}
                code={previewCode.code}
                language={previewCode.language}
            />
        </PageContainer>
    );
};

export default DeploymentConfigList; 