
def type_cql_query():
    query = """
    MATCH (n:data_model)
    WHERE id(n) = $nodeId
    // 获取元数据节点, 数据模型
    WITH n
    OPTIONAL MATCH (n)-[:connection]->(a:meta_node)
    // 获取数据标准
    OPTIONAL MATCH (n)-[:clean_model]-(d:data_standard)-[:clean_model]->(a) 
    // 获取数据标签
    OPTIONAL MATCH (n)-[:label]->(la:data_label)
    OPTIONAL MATCH (child) where id(child) = n.childernId 
    OPTIONAL MATCH (ma) where id(ma) = a.master_data 
    WITH n, a, d, la, n.childrenId AS childrenIds,ma
    // 遍历 childrenIds 并获取对应的子节点
    UNWIND childrenIds AS child_id
    OPTIONAL MATCH (child) WHERE id(child) = child_id
    // 收集子节点信息
    WITH n, a, d, la, collect(DISTINCT {id: id(child), name: child.name}) AS childrenId,ma
    // 收集元数据信息并排序
    WITH a, d, la, n, childrenId, ma
    WITH n, collect(DISTINCT {id: id(a), name: a.name, en_name: a.en_name,
                             data_type: a.data_type, master_data: {id: id(ma), name: ma.name},
                             data_standard: {id: id(d), name: d.name}}) AS meta_ids,
            properties(n) AS properties, {id: id(la), name: la.name} AS tag, childrenId
   // 对 meta_ids 进行排序
    UNWIND meta_ids AS meta_id
    WITH n, tag, properties, childrenId, meta_id
    ORDER BY meta_id.id
    WITH n, tag, properties, childrenId, collect(meta_id) AS sorted_meta_ids
    // 构建结果集
    WITH [{data_resource: null, resource_id: null, meta_ids: sorted_meta_ids}]AS resources, 
         id(n) as nodeid, tag, properties, n, childrenId
    UNWIND resources as resource
    WITH nodeid, collect(resource) as results, tag, properties, n,childrenId
    // 合并结果集
    RETURN results, tag, properties, childrenId
    """

    return query


# 数据模型编辑接口
def handle_id_model(id):
    # 获取数据模型的名称,元数据名称,对应选中的数据资源名称
    query = type_cql_query()

    data_ = connect_graph.run(query, nodeId=id)

    res_list = []
    properties = {}

    for record in data_:
        res_list = record['results']
        properties = record['properties']
        properties['tag'] = record['tag']
        properties['childrenId'] = record['childrenId']
        properties.pop('id_list', None)
        if 'tag' not in properties:
            properties['tag'] = None
        if 'describe' not in properties:
            properties['describe'] = None

    res_dict = {"resource_selected": res_list}
    merged_dict = {**res_dict, **properties}
    response_data = {"data_model": merged_dict}

    return response_data