package com.ecep.contract.util;

import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import org.springframework.data.domain.Sort;

import javafx.scene.Node;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.MouseButton;
import javafx.scene.input.PickResult;

public class TableViewUtils {

    /**
     * 获取 Table 的排序
     */
    public static <T> List<Sort.Order> getOrders(TableView<T> table) {
        return table.getSortOrder().stream().filter(c -> {
            if (!c.isSortable()) {
                return false;
            }
            String id = c.getId();
            return id.endsWith("Column");
        }).map(c -> {
            String id = c.getId();
            id = id.replace(table.getId() + "_", "");
            id = id.replace("Column", "");
            Sort.Direction dir = c.getSortType() == TableColumn.SortType.ASCENDING ? Sort.Direction.ASC : Sort.Direction.DESC;
            return new Sort.Order(dir, id);
        }).toList();
    }

    public static <T> void bindDoubleClicked(TableView<T> table, Consumer<T> consumer) {
        table.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2 && event.getButton() == MouseButton.PRIMARY) {
                PickResult pickResult = event.getPickResult();
                Node intersectedNode = pickResult.getIntersectedNode();
                if (intersectedNode instanceof TableRow) {
                    // 鼠标点击的地方没有定义列，只返回了行，跳过不做处理
                    TableRow<T> row = (TableRow<T>) intersectedNode;
                    row.getItem();
                    return;
                }

                T selectedItem = table.getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    try {
                        consumer.accept(selectedItem);
                    } catch (UnsupportedOperationException e) {
                        UITools.showExceptionAndWait("当前操作不支持", e);
                    } catch (Exception e) {
                        UITools.showExceptionAndWait(e.getMessage(), e);
                    }
                }

            }
        });


    }

    public static <T> void bindEnterPressed(TableView<T> table, Consumer<T> consumer) {
        table.setOnKeyPressed(event -> {
            if (event.getCode() == KeyCode.ENTER) {
                T selectedItem = table.getSelectionModel().getSelectedItem();
                if (selectedItem != null) {
                    consumer.accept(selectedItem);
                }
            }
        });
    }

    /**
     * 计算表格的可视行数
     *
     * @param table 表格视图
     * @param <T>   T
     * @return 可视行数
     */
    public static <T> int getTableViewVisibleRows(TableView<T> table) {
        int rows = 0;
        Set<Node> tableRow = table.lookupAll("TableRow");
        for (Node node : tableRow) {
            if (node instanceof TableRow) {
                if (!node.isVisible()) {
                    continue;
                }
                rows++;
            }
        }
        return rows;
    }
}
