"""
表单数据操作节点

支持对在线表单数据进行 CRUD 操作：
- FormDataCreateNode: 创建表单数据
- FormDataReadNode: 读取单条表单数据
- FormDataUpdateNode: 更新表单数据
- FormDataDeleteNode: 删除表单数据
- FormDataListNode: 查询表单数据列表
- FormSchemaToLLMNode: 将表单配置转换为 LLM 结构化输出配置
"""
import json
import logging
import time
from datetime import date, datetime
from decimal import Decimal
from typing import Any, Dict, List, Optional
from uuid import UUID

from ..base import BaseNode, NodeContext, NodeResult
from ..registry import NodeRegistry

logger = logging.getLogger(__name__)


def serialize_value(value: Any) -> Any:
    """将数据库值转换为可 JSON 序列化的格式"""
    if value is None:
        return None
    if isinstance(value, datetime):
        return value.isoformat()
    if isinstance(value, date):
        return value.isoformat()
    if isinstance(value, Decimal):
        return float(value)
    if isinstance(value, UUID):
        return str(value)
    if isinstance(value, bytes):
        return value.decode('utf-8', errors='replace')
    if isinstance(value, (list, tuple)):
        return [serialize_value(v) for v in value]
    if isinstance(value, dict):
        return {k: serialize_value(v) for k, v in value.items()}
    return value


def serialize_row(row: Dict[str, Any]) -> Dict[str, Any]:
    """序列化数据库行"""
    return {k: serialize_value(v) for k, v in row.items()}


class BaseFormDataNode(BaseNode):
    """表单数据操作节点基类"""

    node_category = 'data'
    node_icon = 'file-text'

    async def _get_form_data_service(self, context: NodeContext, form_code: str):
        """获取表单数据服务实例"""
        from online_dev.form_data_manager.service import FormDataService

        db = context.db_session
        if not db:
            raise ValueError('数据库会话不可用')

        service = await FormDataService.create_service(db, form_code)
        return service, db


@NodeRegistry.register
class FormDataCreateNode(BaseFormDataNode):
    """
    表单数据创建节点

    根据表单编码创建一条或多条数据
    """

    node_type = 'form_data_create'
    node_name = '创建表单数据'
    node_description = '向指定表单创建一条或多条数据'

    inputs = [
        {
            'name': 'form_code',
            'type': 'string',
            'description': '表单编码',
            'required': True,
        },
        {
            'name': 'data',
            'type': 'object',
            'description': '要创建的数据（对象或数组）',
            'required': True,
        },
    ]

    outputs = [
        {
            'name': 'result',
            'type': 'object',
            'description': '创建结果（包含新记录ID）',
        },
        {
            'name': 'count',
            'type': 'number',
            'description': '创建的记录数',
        },
    ]

    def execute(self, context: NodeContext) -> NodeResult:
        """同步执行"""
        import asyncio
        loop = asyncio.get_event_loop()
        if loop.is_running():
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, self.execute_async(context))
                return future.result()
        else:
            return loop.run_until_complete(self.execute_async(context))

    async def execute_async(self, context: NodeContext) -> NodeResult:
        """异步执行创建操作"""
        start_time = time.time()

        try:
            # 获取配置
            form_code = self.config.get('form_code', '')
            data = self.config.get('data', {})
            output_variable = self.config.get('output_variable', 'form_data_create_result')

            # 解析变量
            if isinstance(form_code, str) and '{{' in form_code:
                form_code = context.resolve_template(form_code)

            # 解析 data 变量
            if isinstance(data, str):
                if '{{' in data:
                    data = context.resolve_template(data)
                # 尝试解析为 JSON 或 Python 字面量
                try:
                    data = json.loads(data)
                except json.JSONDecodeError:
                    # 尝试使用 ast.literal_eval 解析 Python 字典字符串（单引号格式）
                    try:
                        import ast
                        data = ast.literal_eval(data)
                    except (ValueError, SyntaxError):
                        pass

            logger.info(f'[FormDataCreate] 解析后 data 类型: {type(data).__name__}, 值: {str(data)[:200]}')

            # 如果在循环中且 data 为空或未配置，使用循环的当前项
            if not data or (isinstance(data, dict) and not data):
                loop_item = context.get_variable('_loop_item')
                logger.info(f'[FormDataCreate] 尝试获取循环项，_loop_item 类型: {type(loop_item).__name__}, 值: {loop_item}')
                if loop_item is not None:
                    data = loop_item
                    logger.info(f'[FormDataCreate] 使用循环项作为数据: {data}')

            logger.info(f'[FormDataCreate] 包装前 data 类型: {type(data).__name__}, 值: {str(data)[:200]}')

            # 如果 data 不包含 main 键，自动包装
            if isinstance(data, dict) and 'main' not in data:
                # 检查是否是表单字段数据（不是嵌套的配置对象）
                data = {'main': data}
                logger.info(f'[FormDataCreate] 自动包装数据为 main 格式')

            logger.info(f'[FormDataCreate] 最终 data 类型: {type(data).__name__}, 值: {str(data)[:200]}')

            if not form_code:
                return NodeResult(
                    success=False,
                    error='未指定表单编码',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 获取服务
            service, db = await self._get_form_data_service(context, form_code)

            # 判断是单条还是多条
            results = []
            if isinstance(data, list):
                # 批量创建
                for item in data:
                    result = await service.create(db, item)
                    results.append(serialize_row(result))
                await db.commit()
            else:
                # 单条创建
                result = await service.create(db, data)
                await db.commit()
                results.append(serialize_row(result))

            elapsed_time = int((time.time() - start_time) * 1000)

            output = results if len(results) > 1 else results[0] if results else None

            return NodeResult(
                success=True,
                output=output,
                output_variables={
                    output_variable: output,
                    f'{output_variable}_count': len(results),
                },
                elapsed_time=elapsed_time,
            )

        except Exception as e:
            logger.exception(f'表单数据创建失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
                elapsed_time=int((time.time() - start_time) * 1000),
            )


@NodeRegistry.register
class FormDataReadNode(BaseFormDataNode):
    """
    表单数据读取节点

    根据 ID 读取单条表单数据
    """

    node_type = 'form_data_read'
    node_name = '读取表单数据'
    node_description = '根据ID读取单条表单数据'

    inputs = [
        {
            'name': 'form_code',
            'type': 'string',
            'description': '表单编码',
            'required': True,
        },
        {
            'name': 'id',
            'type': 'string',
            'description': '记录ID',
            'required': True,
        },
    ]

    outputs = [
        {
            'name': 'data',
            'type': 'object',
            'description': '表单数据',
        },
    ]

    def execute(self, context: NodeContext) -> NodeResult:
        """同步执行"""
        import asyncio
        loop = asyncio.get_event_loop()
        if loop.is_running():
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, self.execute_async(context))
                return future.result()
        else:
            return loop.run_until_complete(self.execute_async(context))

    async def execute_async(self, context: NodeContext) -> NodeResult:
        """异步执行读取操作"""
        start_time = time.time()

        try:
            # 获取配置
            form_code = self.config.get('form_code', '')
            record_id = self.config.get('id', '')
            output_variable = self.config.get('output_variable', 'form_data')

            # 解析变量
            if isinstance(form_code, str) and '{{' in form_code:
                form_code = context.resolve_template(form_code)
            if isinstance(record_id, str) and '{{' in record_id:
                record_id = context.resolve_template(record_id)

            if not form_code:
                return NodeResult(
                    success=False,
                    error='未指定表单编码',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            if not record_id:
                return NodeResult(
                    success=False,
                    error='未指定记录ID',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 获取服务
            service, db = await self._get_form_data_service(context, form_code)

            # 读取数据
            result = await service.get(db, record_id)
            result = serialize_row(result)

            elapsed_time = int((time.time() - start_time) * 1000)

            return NodeResult(
                success=True,
                output=result,
                output_variables={
                    output_variable: result,
                },
                elapsed_time=elapsed_time,
            )

        except Exception as e:
            logger.exception(f'表单数据读取失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
                elapsed_time=int((time.time() - start_time) * 1000),
            )


@NodeRegistry.register
class FormDataUpdateNode(BaseFormDataNode):
    """
    表单数据更新节点

    根据 ID 更新表单数据
    """

    node_type = 'form_data_update'
    node_name = '更新表单数据'
    node_description = '根据ID更新表单数据'

    inputs = [
        {
            'name': 'form_code',
            'type': 'string',
            'description': '表单编码',
            'required': True,
        },
        {
            'name': 'id',
            'type': 'string',
            'description': '记录ID',
            'required': True,
        },
        {
            'name': 'data',
            'type': 'object',
            'description': '要更新的数据',
            'required': True,
        },
    ]

    outputs = [
        {
            'name': 'result',
            'type': 'object',
            'description': '更新后的数据',
        },
    ]

    def execute(self, context: NodeContext) -> NodeResult:
        """同步执行"""
        import asyncio
        loop = asyncio.get_event_loop()
        if loop.is_running():
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, self.execute_async(context))
                return future.result()
        else:
            return loop.run_until_complete(self.execute_async(context))

    async def execute_async(self, context: NodeContext) -> NodeResult:
        """异步执行更新操作"""
        start_time = time.time()

        try:
            # 获取配置
            form_code = self.config.get('form_code', '')
            record_id = self.config.get('id', '')
            data = self.config.get('data', {})
            output_variable = self.config.get('output_variable', 'form_data_update_result')

            # 解析变量
            if isinstance(form_code, str) and '{{' in form_code:
                form_code = context.resolve_template(form_code)
            if isinstance(record_id, str) and '{{' in record_id:
                record_id = context.resolve_template(record_id)

            # 解析 data 变量
            if isinstance(data, str):
                if '{{' in data:
                    data = context.resolve_template(data)
                # 尝试解析为 JSON 或 Python 字面量
                try:
                    data = json.loads(data)
                except json.JSONDecodeError:
                    # 尝试使用 ast.literal_eval 解析 Python 字典字符串（单引号格式）
                    try:
                        import ast
                        data = ast.literal_eval(data)
                    except (ValueError, SyntaxError):
                        pass

            # 如果在循环中且 data 为空或未配置，使用循环的当前项
            if not data or (isinstance(data, dict) and not data):
                loop_item = context.get_variable('_loop_item')
                if loop_item is not None:
                    data = loop_item

            # 如果 data 不包含 main 键，自动包装
            if isinstance(data, dict) and 'main' not in data:
                data = {'main': data}

            if not form_code:
                return NodeResult(
                    success=False,
                    error='未指定表单编码',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            if not record_id:
                return NodeResult(
                    success=False,
                    error='未指定记录ID',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 获取服务
            service, db = await self._get_form_data_service(context, form_code)

            # 更新数据
            result = await service.update(db, record_id, data)
            await db.commit()
            result = serialize_row(result)

            elapsed_time = int((time.time() - start_time) * 1000)

            return NodeResult(
                success=True,
                output=result,
                output_variables={
                    output_variable: result,
                },
                elapsed_time=elapsed_time,
            )

        except Exception as e:
            logger.exception(f'表单数据更新失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
                elapsed_time=int((time.time() - start_time) * 1000),
            )


@NodeRegistry.register
class FormDataDeleteNode(BaseFormDataNode):
    """
    表单数据删除节点

    根据 ID 删除表单数据（支持软删除和硬删除）
    """

    node_type = 'form_data_delete'
    node_name = '删除表单数据'
    node_description = '根据ID删除表单数据'

    inputs = [
        {
            'name': 'form_code',
            'type': 'string',
            'description': '表单编码',
            'required': True,
        },
        {
            'name': 'id',
            'type': 'string',
            'description': '记录ID（支持单个或数组）',
            'required': True,
        },
        {
            'name': 'hard_delete',
            'type': 'boolean',
            'description': '是否硬删除（默认软删除）',
            'default': False,
        },
    ]

    outputs = [
        {
            'name': 'success',
            'type': 'boolean',
            'description': '是否成功',
        },
        {
            'name': 'count',
            'type': 'number',
            'description': '删除的记录数',
        },
    ]

    def execute(self, context: NodeContext) -> NodeResult:
        """同步执行"""
        import asyncio
        loop = asyncio.get_event_loop()
        if loop.is_running():
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, self.execute_async(context))
                return future.result()
        else:
            return loop.run_until_complete(self.execute_async(context))

    async def execute_async(self, context: NodeContext) -> NodeResult:
        """异步执行删除操作"""
        start_time = time.time()

        try:
            # 获取配置
            form_code = self.config.get('form_code', '')
            record_ids = self.config.get('id', '')
            hard_delete = self.config.get('hard_delete', False)
            output_variable = self.config.get('output_variable', 'form_data_delete_result')

            # 解析变量
            if isinstance(form_code, str) and '{{' in form_code:
                form_code = context.resolve_template(form_code)
            if isinstance(record_ids, str) and '{{' in record_ids:
                record_ids = context.resolve_template(record_ids)
                # 尝试解析为 JSON 或 Python 字面量
                try:
                    record_ids = json.loads(record_ids)
                except json.JSONDecodeError:
                    # 尝试使用 ast.literal_eval 解析 Python 列表字符串（单引号格式）
                    try:
                        import ast
                        record_ids = ast.literal_eval(record_ids)
                    except (ValueError, SyntaxError):
                        pass

            if not form_code:
                return NodeResult(
                    success=False,
                    error='未指定表单编码',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            if not record_ids:
                return NodeResult(
                    success=False,
                    error='未指定记录ID',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 获取服务
            service, db = await self._get_form_data_service(context, form_code)

            # 转换为列表
            if isinstance(record_ids, str):
                record_ids = [record_ids]

            # 删除数据
            delete_count = 0
            for record_id in record_ids:
                await service.delete(db, record_id, hard=hard_delete)
                delete_count += 1

            await db.commit()

            elapsed_time = int((time.time() - start_time) * 1000)

            return NodeResult(
                success=True,
                output={'success': True, 'count': delete_count},
                output_variables={
                    output_variable: {'success': True, 'count': delete_count},
                    f'{output_variable}_count': delete_count,
                },
                elapsed_time=elapsed_time,
            )

        except Exception as e:
            logger.exception(f'表单数据删除失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
                elapsed_time=int((time.time() - start_time) * 1000),
            )


@NodeRegistry.register
class FormDataListNode(BaseFormDataNode):
    """
    表单数据列表查询节点

    查询表单数据列表，支持分页和过滤
    """

    node_type = 'form_data_list'
    node_name = '查询表单数据'
    node_description = '查询表单数据列表，支持分页和过滤'

    inputs = [
        {
            'name': 'form_code',
            'type': 'string',
            'description': '表单编码',
            'required': True,
        },
        {
            'name': 'page',
            'type': 'number',
            'description': '页码（默认1）',
            'default': 1,
        },
        {
            'name': 'page_size',
            'type': 'number',
            'description': '每页条数（默认20）',
            'default': 20,
        },
        {
            'name': 'filters',
            'type': 'object',
            'description': '过滤条件',
        },
        {
            'name': 'sort',
            'type': 'array',
            'description': '排序配置',
        },
    ]

    outputs = [
        {
            'name': 'items',
            'type': 'array',
            'description': '数据列表',
        },
        {
            'name': 'total',
            'type': 'number',
            'description': '总记录数',
        },
    ]

    def execute(self, context: NodeContext) -> NodeResult:
        """同步执行"""
        import asyncio
        loop = asyncio.get_event_loop()
        if loop.is_running():
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, self.execute_async(context))
                return future.result()
        else:
            return loop.run_until_complete(self.execute_async(context))

    async def execute_async(self, context: NodeContext) -> NodeResult:
        """异步执行列表查询"""
        start_time = time.time()

        try:
            # 获取配置
            form_code = self.config.get('form_code', '')
            page = self.config.get('page', 1)
            page_size = self.config.get('page_size', 20)
            filters = self.config.get('filters', {})
            sort_list = self.config.get('sort', [])
            output_variable = self.config.get('output_variable', 'form_data_list')

            # 解析变量
            if isinstance(form_code, str) and '{{' in form_code:
                form_code = context.resolve_template(form_code)

            # 解析 filters 变量
            if isinstance(filters, str):
                if '{{' in filters:
                    filters = context.resolve_template(filters)
                try:
                    filters = json.loads(filters)
                except json.JSONDecodeError:
                    filters = {}

            if not form_code:
                return NodeResult(
                    success=False,
                    error='未指定表单编码',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 获取服务
            service, db = await self._get_form_data_service(context, form_code)

            # 查询数据
            result = await service.list(
                db,
                page=page,
                page_size=page_size,
                filters=filters,
                sort_list=sort_list,
            )

            # 序列化结果
            items = [serialize_row(item) for item in result.get('items', [])]
            total = result.get('total', 0)

            elapsed_time = int((time.time() - start_time) * 1000)

            return NodeResult(
                success=True,
                output={'items': items, 'total': total},
                output_variables={
                    output_variable: items,
                    f'{output_variable}_total': total,
                    f'{output_variable}_page': page,
                    f'{output_variable}_page_size': page_size,
                },
                elapsed_time=elapsed_time,
            )

        except Exception as e:
            logger.exception(f'表单数据查询失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
                elapsed_time=int((time.time() - start_time) * 1000),
            )


@NodeRegistry.register
class FormSchemaToLLMNode(BaseFormDataNode):
    """
    表单配置转 LLM 结构化输出节点

    将表单的字段配置转换为 LLM Function Calling 的结构化输出配置
    支持生成数组类型的输出（用于批量数据）
    """

    node_type = 'form_schema_to_llm'
    node_name = '表单转LLM结构'
    node_description = '将表单配置转换为LLM结构化输出配置'

    inputs = [
        {
            'name': 'form_code',
            'type': 'string',
            'description': '表单编码',
            'required': True,
        },
        {
            'name': 'is_array',
            'type': 'boolean',
            'description': '是否生成数组类型（用于多条数据）',
            'default': False,
        },
        {
            'name': 'include_fields',
            'type': 'array',
            'description': '要包含的字段列表（为空则包含所有）',
        },
        {
            'name': 'exclude_fields',
            'type': 'array',
            'description': '要排除的字段列表',
        },
    ]

    outputs = [
        {
            'name': 'schema',
            'type': 'array',
            'description': 'LLM 结构化输出配置',
        },
    ]

    # 表单组件类型到 JSON Schema 类型的映射
    COMPONENT_TYPE_MAP = {
        'input': 'string',
        'textarea': 'string',
        'number': 'number',
        'select': 'string',
        'radio': 'string',
        'checkbox': 'array',
        'switch': 'boolean',
        'date': 'string',
        'date-picker': 'string',
        'time': 'string',
        'datetime': 'string',
        'rate': 'number',
        'slider': 'number',
        'color': 'string',
        'cascader': 'array',
        'tree-select': 'string',
        'upload': 'array',
        'rich-text': 'string',
        'user-selector': 'string',
        'dept-selector': 'string',
        'post-selector': 'string',
    }

    def execute(self, context: NodeContext) -> NodeResult:
        """同步执行"""
        import asyncio
        loop = asyncio.get_event_loop()
        if loop.is_running():
            import concurrent.futures
            with concurrent.futures.ThreadPoolExecutor() as executor:
                future = executor.submit(asyncio.run, self.execute_async(context))
                return future.result()
        else:
            return loop.run_until_complete(self.execute_async(context))

    async def execute_async(self, context: NodeContext) -> NodeResult:
        """异步执行转换"""
        start_time = time.time()

        try:
            from sqlalchemy import select
            from online_dev.form_manager.model import FormMeta

            # 获取配置
            form_code = self.config.get('form_code', '')
            is_array = self.config.get('is_array', False)
            include_fields = self.config.get('include_fields', [])
            exclude_fields = self.config.get('exclude_fields', [])
            output_variable = self.config.get('output_variable', 'llm_output_schema')

            # 解析变量
            if isinstance(form_code, str) and '{{' in form_code:
                form_code = context.resolve_template(form_code)

            if not form_code:
                return NodeResult(
                    success=False,
                    error='未指定表单编码',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            db = context.db_session
            if not db:
                return NodeResult(
                    success=False,
                    error='数据库会话不可用',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 获取表单配置
            stmt = select(FormMeta).where(
                FormMeta.code == form_code,
                FormMeta.is_deleted == False
            )
            result = await db.execute(stmt)
            form_meta = result.scalar_one_or_none()

            if not form_meta:
                return NodeResult(
                    success=False,
                    error=f'表单不存在: {form_code}',
                    elapsed_time=int((time.time() - start_time) * 1000),
                )

            # 提取字段配置
            form_config = form_meta.form_config or {}
            items = form_config.get('items', [])

            # 转换为 LLM 结构化输出配置
            schema_fields = self._extract_fields(items, include_fields, exclude_fields)

            # 如果是数组类型，包装为数组
            if is_array:
                output_schema = [{
                    'name': 'items',
                    'type': 'array',
                    'description': f'{form_meta.name}数据列表',
                    'required': True,
                    'children': schema_fields,
                }]
            else:
                output_schema = schema_fields

            elapsed_time = int((time.time() - start_time) * 1000)

            return NodeResult(
                success=True,
                output=output_schema,
                output_variables={
                    output_variable: output_schema,
                },
                elapsed_time=elapsed_time,
            )

        except Exception as e:
            logger.exception(f'表单配置转换失败: {e}')
            return NodeResult(
                success=False,
                error=str(e),
                elapsed_time=int((time.time() - start_time) * 1000),
            )

    def _extract_fields(
        self,
        items: List[Dict],
        include_fields: List[str],
        exclude_fields: List[str],
        in_sub_table: str = None,
    ) -> List[Dict]:
        """
        从表单配置中提取字段，转换为 LLM 结构化输出格式

        Args:
            items: 表单项列表
            include_fields: 要包含的字段
            exclude_fields: 要排除的字段
            in_sub_table: 当前是否在子表中

        Returns:
            LLM 结构化输出字段列表
        """
        schema_fields = []

        for item in items:
            item_type = item.get('type', '')
            field = item.get('field', '')
            label = item.get('label', field)

            # 跳过布局组件，递归处理其子项
            if item_type in ('grid', 'tabs', 'collapse', 'divider', 'alert', 'timeline', 'text', 'html', 'spacer', 'title', 'steps'):
                if item.get('columns'):
                    for col in item['columns']:
                        schema_fields.extend(
                            self._extract_fields(
                                col.get('children', []),
                                include_fields,
                                exclude_fields,
                                in_sub_table,
                            )
                        )
                if item.get('items'):
                    for sub_item in item['items']:
                        schema_fields.extend(
                            self._extract_fields(
                                sub_item.get('children', []),
                                include_fields,
                                exclude_fields,
                                in_sub_table,
                            )
                        )
                continue

            # 子表组件
            if item_type == 'sub-table':
                sub_table_name = field
                children = item.get('children', [])
                sub_fields = self._extract_fields(
                    children,
                    include_fields,
                    exclude_fields,
                    sub_table_name,
                )
                if sub_fields:
                    schema_fields.append({
                        'name': sub_table_name,
                        'type': 'array',
                        'description': label or sub_table_name,
                        'required': item.get('required', False),
                        'children': sub_fields,
                    })
                continue

            # 普通字段
            if not field:
                continue

            # 过滤字段
            if include_fields and field not in include_fields:
                continue
            if field in exclude_fields:
                continue

            # 跳过系统字段
            if field.startswith('sys_') or field in ('id', 'is_deleted', 'sort'):
                continue

            # 转换类型
            json_type = self.COMPONENT_TYPE_MAP.get(item_type, 'string')

            # 构建字段配置
            field_config = {
                'name': field,
                'type': json_type,
                'description': label or field,
                'required': item.get('required', False),
            }

            # 为日期类型添加格式说明
            if item_type in ('date', 'date-picker'):
                field_config['description'] = f'{label or field}（格式：YYYY-MM-DD，如 2024-01-15）'
            elif item_type == 'datetime':
                field_config['description'] = f'{label or field}（格式：YYYY-MM-DD HH:mm:ss，如 2024-01-15 14:30:00）'
            elif item_type == 'time':
                field_config['description'] = f'{label or field}（格式：HH:mm:ss，如 14:30:00）'

            # 添加枚举值（如果有选项）
            options = item.get('options', [])
            if options and json_type == 'string':
                enum_values = [opt.get('value') for opt in options if opt.get('value')]
                if enum_values:
                    field_config['enum'] = enum_values

            schema_fields.append(field_config)

        return schema_fields
