package view;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import model.Goods;
import model.InventoryManager;

public class InventoryView extends BorderPane {

    private TextField goodsField;
    private TextField quantityField;
    private TextField remarkField;
    private TableView<Goods> tableView;
    private Label totalValue;
    private final InventoryManager inventoryManager;

    public InventoryView() {
        inventoryManager = new InventoryManager();
        initializeUI();
    }

    private void initializeUI() {
        // 顶部操作区域
        VBox topArea = createTopArea();
        setTop(topArea);

        // 中间表格区域
        tableView = createTableView();
        setCenter(tableView);

        // 底部汇总区域
        HBox bottomArea = createBottomArea();
        setBottom(bottomArea);
    }

    private VBox createTopArea() {
        VBox topArea = new VBox(10);
        topArea.setPadding(new Insets(10));

        // 第一行：基本信息
        GridPane basicInfo = new GridPane();
        basicInfo.setHgap(10);
        basicInfo.setVgap(10);

        Label goodsLabel = new Label("货物名称：");
        goodsField = new TextField();
        goodsField.setPromptText("请输入货物名称");

        Label quantityLabel = new Label("数量：");
        quantityField = new TextField();
        quantityField.setPromptText("请输入数量");

        Label remarkLabel = new Label("备注：");
        remarkField = new TextField();
        remarkField.setPromptText("请输入备注信息");

        basicInfo.addRow(0, goodsLabel, goodsField, quantityLabel, quantityField);
        basicInfo.addRow(1, remarkLabel, remarkField);

        // 设置列宽
        ColumnConstraints column1 = new ColumnConstraints();
        column1.setMinWidth(80);
        ColumnConstraints column2 = new ColumnConstraints();
        column2.setMinWidth(200);
        ColumnConstraints column3 = new ColumnConstraints();
        column3.setMinWidth(80);
        ColumnConstraints column4 = new ColumnConstraints();
        column4.setMinWidth(200);

        basicInfo.getColumnConstraints().addAll(column1, column2, column3, column4);

        // 操作按钮
        HBox buttonBox = new HBox(10);
        buttonBox.setAlignment(Pos.CENTER_RIGHT);
        buttonBox.setPadding(new Insets(10, 0, 0, 0));

        Button addButton = new Button("添加库存");
        addButton.setOnAction(e -> handleAdd());

        Button clearButton = new Button("清空");
        clearButton.setOnAction(e -> handleClear());

        buttonBox.getChildren().addAll(addButton, clearButton);

        topArea.getChildren().addAll(basicInfo, buttonBox);
        return topArea;
    }

    private TableView<Goods> createTableView() {
        TableView<Goods> table = new TableView<>();

        TableColumn<Goods, String> idCol = new TableColumn<>("货物ID");
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));

        TableColumn<Goods, String> nameCol = new TableColumn<>("货物名称");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Goods, Integer> quantityCol = new TableColumn<>("数量");
        quantityCol.setCellValueFactory(new PropertyValueFactory<>("quantity"));

        TableColumn<Goods, String> remarkCol = new TableColumn<>("备注");
        remarkCol.setCellValueFactory(new PropertyValueFactory<>("remark"));

        table.getColumns().addAll(idCol, nameCol, quantityCol, remarkCol);

        table.getItems().addListener((javafx.collections.ListChangeListener.Change<? extends Goods> c) -> {
            updateTotal();
        });

        return table;
    }

    private HBox createBottomArea() {
        HBox bottomArea = new HBox(10);
        bottomArea.setPadding(new Insets(10));
        bottomArea.setAlignment(Pos.CENTER_RIGHT);

        Label totalLabel = new Label("库存总数量：");
        totalValue = new Label("0");
        Label unitLabel = new Label("件");

        bottomArea.getChildren().addAll(totalLabel, totalValue, unitLabel);
        return bottomArea;
    }

    private void updateTotal() {
        int total = tableView.getItems().stream()
                .mapToInt(Goods::getQuantity)
                .sum();
        totalValue.setText(String.valueOf(total));
    }

    private void handleAdd() {
        try {
            String goodsName = goodsField.getText().trim();
            String quantityText = quantityField.getText().trim();
            String remark = remarkField.getText().trim();

            // 输入验证
            if (goodsName.isEmpty() || quantityText.isEmpty()) {
                showAlert("错误", "请填写完整的库存信息！");
                return;
            }

            int quantity;
            try {
                quantity = Integer.parseInt(quantityText);
                if (quantity <= 0) {
                    showAlert("错误", "数量必须大于0！");
                    return;
                }
            } catch (NumberFormatException e) {
                showAlert("错误", "请输入有效的数量！");
                return;
            }

            // 创建货物对象
            String id = "G" + System.currentTimeMillis();
            Goods goods = new Goods(id, goodsName, quantity, remark);

            // 添加到库存管理器
            inventoryManager.addOrUpdateInventory(goods.getId(), quantity);

            // 添加到表格
            tableView.getItems().add(goods);

            // 更新总计
            updateTotal();

            // 清空输入
            handleClear();

            showAlert("成功", "库存记录已保存！");

        } catch (Exception e) {
            showAlert("错误", "保存失败：" + e.getMessage());
        }
    }

    private void handleClear() {
        goodsField.clear();
        quantityField.clear();
        remarkField.clear();
    }

    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
}
