def CreateRow(table, row_count):
    """
    创建表格行
    """
    table.getRows().insertByIndex(table.getRows().getCount(), row_count)

def InsertRow(location_bookmark_name, data):
    """
    表格插入行
    Args:
        location_bookmark: 用于定位表格的书签
        data: 二维数组,用于填充表格数据
    """
    bookmark_info = QueryAll()
    table_bookmarks = bookmark_info["table"]

    handle_table_index = -1

    for table_info in table_bookmarks:
      table_bookmark_names = table_info["bookmark"]
      if location_bookmark_name in table_bookmark_names:
        handle_table_index = table_info["tableIndex"]

    if handle_table_index == -1:
      return

    doc = XSCRIPTCONTEXT.getDocument()
    tables = doc.getTextTables()
    handle_table = tables.getByIndex(handle_table_index)
    col_count = handle_table.getColumns().getCount()
    row_count = handle_table.getRows().getCount()
    if data.len > 0 & data[0].len == col_count:
      CreateRow(handle_table, data.len)
      for row in range(data.len + 1, row_count + 1):
        for col in range(col_count):
          cell = handle_table.getCellByPosition(col, row)
          cell.setString(data[row][col])


def DebugCall():
    """
    调试调用
    """
    InsertRow("h1", [["1", "2", "3"], ["4", "5", "6"]])


def QueryAll():
    """
    查询所有书签,表格中的书签获取对应表格index

    返回结果格式:
    {
        "text": [],
        "table": [
            {
                "tableIndex": 表格索引,
                "bookmark": [书签名称列表]
            }
        ]
    }
    """

    doc = XSCRIPTCONTEXT.getDocument()
    bookmarks = doc.getBookmarks()
    bookmark_names = bookmarks.getElementNames()

    result = {
        "text": [],
        "table": []
    }

    tables = doc.getTextTables()
    bookmark_in_table_position = QueryBookmarkPositionInTable(tables, bookmarks)

    existing_table_indices = {}

    for bk_name in bookmark_names:
        if bk_name in bookmark_in_table_position:
            table_index = bookmark_in_table_position[bk_name]["tableIndex"]
            if table_index in existing_table_indices:
                index = existing_table_indices[table_index]
                result["table"][index]["bookmark"].append(bk_name)
            else:
                new_entry = {
                    "tableIndex": table_index,
                    "bookmark": [bk_name]
                }
                result["table"].append(new_entry)
                existing_table_indices[table_index] = len(result["table"]) - 1  # 更新索引记录
        else:
            result["text"].append(bk_name)
    
    return result



def QueryBookmarkPositionInTable(tables, bookmarks):

    """
    查询书签在表格中的位置
    {'bk1': {'tableIndex': 0, 'row': 0, 'col': 0}, 'bk2': {'tableIndex': 0, 'row': 0, 'col': 2}}
    """

    bookmark_names = bookmarks.getElementNames()

    bookmark_position = {}

    for table_index in range(tables.getCount()):
        table = tables.getByIndex(table_index)

        col_count = table.getColumns().getCount()
        row_count = table.getRows().getCount()

        for row in range(row_count):
            for col in range(col_count):
                cell = table.getCellByPosition(col, row)
                cell_text_obj = cell.getText()

                for bk_name in bookmark_names:
                    bookmark_obj = bookmarks.getByName(bk_name)
                    bookmark_text_obj = bookmark_obj.getAnchor().getText()
                    if cell_text_obj == bookmark_text_obj:
                        bookmark_position[bk_name] = {
                            "tableIndex": table_index,
                            "col": col,
                            "row": row}

    print(bookmark_position)

    return bookmark_position

g_exportedScripts = (InsertRow,DebugCall,)