/**
 * 通用表单配置转换工具（完整兼容版）
 * 支持：page根节点、嵌套容器、各种表单组件及未知类型容错
 */

// -------------------------- 类型定义 --------------------------
interface SourceNode {
    id: string;
    type: string;
    label?: string;
    field?: string;
    input?: boolean;
    children?: SourceNode[];
    componentProps?: Record<string, any>;
    [key: string]: any; // 支持任意扩展属性
}

interface BaseTransformedNode {
    id: string;
    type: "container" | "formItem";
    label: string;
    inheritProps?: Record<string, any>;
}

interface TransformedContainer extends BaseTransformedNode {
    type: "container";
    containerType: string;
    props: Record<string, any>;
    children: TransformedNode[];
}

interface TransformedFormItem extends BaseTransformedNode {
    type: "formItem";
    component: string;
    field: string;
    value: any;
    required: boolean;
    readonly?: boolean;
    hidden?: boolean;
    props: Record<string, any>;
}

type TransformedNode = TransformedContainer | TransformedFormItem;

// -------------------------- 核心配置 --------------------------
/** 容器类型映射表（支持page/row/card/form等） */
const containerConfig: Record<
    string,
    {
        type: string;
        defaultProps: Record<string, any>;
        inheritKeys?: string[];
    }
> = {
    page: {
        type: "pageContainer",
        defaultProps: {
            style: { padding: "16px" },
            title: "页面容器"
        },
        inheritKeys: []
    },
    row: {
        type: "gridRow",
        defaultProps: { gutter: 16, justify: "start", align: "top" },
        inheritKeys: []
    },
    col: {
        type: "gridCol",
        defaultProps: { span: 24 },
        inheritKeys: []
    },
    card: {
        type: "card",
        defaultProps: { title: "", bordered: true, collapsible: false },
        inheritKeys: []
    },
    form: {
        type: "formContainer",
        defaultProps: {
            labelWidth: 100,
            labelPosition: "right",
            layout: "horizontal",
            labelCol: { span: 5 },
            wrapperCol: { span: 19 }
        },
        inheritKeys: ["labelWidth", "labelPosition", "labelCol", "wrapperCol"]
    }
};

/** 表单组件映射表（支持input/select/radio等） */
const componentConfig: Record<
    string,
    {
        component: string;
        defaultProps: Record<string, any>;
    }
> = {
    input: {
        component: "ElInput",
        defaultProps: { placeholder: "请输入", type: "text" }
    },
    select: {
        component: "ElSelect",
        defaultProps: { placeholder: "请选择", options: [] }
    },
    radio: {
        component: "ElRadioGroup",
        defaultProps: { options: [], placeholder: "请选择" }
    },
    "upload-image": {
        component: "ElUpload",
        defaultProps: { action: "", listType: "picture", showFileList: true }
    },
    "upload-file": {
        component: "ElUpload",
        defaultProps: { action: "", listType: "text", showFileList: true }
    }
};

// -------------------------- 转换逻辑 --------------------------
/** 递归转换单个节点 */
const transformNode = (node: SourceNode, parentInheritProps: Record<string, any> = {}): TransformedNode => {
    // 1. 处理容器类型节点
    if (containerConfig[node.type]) {
        const { type: containerType, defaultProps, inheritKeys } = containerConfig[node.type];
        const nodeProps = node.componentProps || {};

        // 合并默认属性与源属性（源属性优先级更高）
        const containerProps = { ...defaultProps, ...nodeProps };

        // 计算需要向下传递的继承属性
        const currentInheritProps = inheritKeys
            ? inheritKeys.reduce((acc, key) => {
                  acc[key] = containerProps[key] ?? parentInheritProps[key];
                  return acc;
              }, {} as Record<string, any>)
            : parentInheritProps;

        // 递归转换子节点
        const children = node.children ? node.children.map(child => transformNode(child, currentInheritProps)) : [];

        return {
            id: node.id,
            type: "container",
            containerType,
            label: node.label || containerType,
            props: containerProps,
            children,
            inheritProps: currentInheritProps
        };
    }

    // 2. 处理表单组件节点（input为true的组件）
    if (node.input) {
        const config = componentConfig[node.type] || {
            component: "ElInput",
            defaultProps: { placeholder: `请输入${node.label || ""}` }
        };
        const nodeProps = node.componentProps || {};

        // 合并默认属性、继承属性和源属性
        const componentProps = {
            ...config.defaultProps,
            ...parentInheritProps,
            ...nodeProps
        };
        console.log();
        return {
            id: node.id,
            type: "formItem",
            label: node.label || "",
            component: config.component,
            field: node.field || `field_${node.id}`,
            value: nodeProps.defaultValue ?? null,
            required: nodeProps.required ?? false,
            readonly: false,
            hidden: false,
            props: componentProps,
            inheritProps: parentInheritProps
        };
    }

    // 3. 处理未知类型节点（容错机制）
    return {
        id: node.id,
        type: "formItem",
        label: node.label || `未知组件(${node.type})`,
        component: "ElInput",
        field: `unknown_${node.id}`,
        value: null,
        required: true,
        props: {
            placeholder: `未配置的组件类型: ${node.type}`,
            disabled: true,
            __originalType: node.type // 保留原始类型便于调试
        },
        inheritProps: parentInheritProps
    };
};

/** 入口函数：转换整个配置数组 */
export const transformFormConfig = (source: SourceNode[]): TransformedNode[] => {
    return source.map(node => transformNode(node));
};

// -------------------------- 使用示例 --------------------------
// 假设sourceData是你的源数据数组
// const transformedResult = transformFormConfig(sourceData);
// console.log(JSON.stringify(transformedResult, null, 2));
