package view;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import model.InventoryManager;

import java.sql.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class InventoryView extends BorderPane {
    private TextField goodsField;
    private Label resultLabel;

    private TableView<InventoryManager> tableView;
    private TextField customerField;
    private TextField quantityField;
    private TextField remarkField;
    public InventoryView() {
        initializeUI();
    }

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

        // 中间结果显示区域
        tableView = createTableView();
        setCenter(tableView);
    }
    private TableView<InventoryManager> createTableView() {
        TableView<InventoryManager> table = new TableView<>();

        TableColumn<InventoryManager, String> idCol = new TableColumn<>("单号");
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        idCol.setPrefWidth(150);

        TableColumn<InventoryManager, String> goodsCol = new TableColumn<>("货物名称");
        goodsCol.setCellValueFactory(new PropertyValueFactory<>("goodsId"));
        goodsCol.setPrefWidth(120);

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

        TableColumn<InventoryManager, String> supplierCol = new TableColumn<>("供应商");
        supplierCol.setCellValueFactory(new PropertyValueFactory<>("supplier"));
        supplierCol.setPrefWidth(120);

        TableColumn<InventoryManager, String> operatorCol = new TableColumn<>("操作人员");
        operatorCol.setCellValueFactory(new PropertyValueFactory<>("operator"));
        operatorCol.setPrefWidth(100);

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

        table.getColumns().addAll(idCol, goodsCol, quantityCol, supplierCol, operatorCol, remarkCol);
        table.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                InventoryManager selectedRecord = table.getSelectionModel().getSelectedItem();
                if (selectedRecord != null) {
                    fillFields(selectedRecord);
                }
            }
        });

        return table;
    }
    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 operatorLabel = new Label("操作员：");
        TextField operatorField = new TextField();
        operatorField.setPromptText("请输入操作员");

        // 第一行：供应商
        Label supplierLabel = new Label("供应商：");
        TextField supplierField = new TextField();
        supplierField.setPromptText("请输入供应商");

        basicInfo.addRow(0, goodsLabel, goodsField, operatorLabel, operatorField, supplierLabel, supplierField);

        // 设置列宽
        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);
        ColumnConstraints column5 = new ColumnConstraints();
        column5.setMinWidth(80);
        ColumnConstraints column6 = new ColumnConstraints();
        column6.setMinWidth(200);

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

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

        Button queryButton = new Button("查询库存");
        queryButton.setOnAction(e -> handleQuery(operatorField.getText(), supplierField.getText()));

        buttonBox.getChildren().add(queryButton);

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

    private void handleQuery(String operator, String supplier) {
        String goodsName = goodsField.getText().trim();

        if (goodsName.isEmpty() && operator.isEmpty() && supplier.isEmpty()) {
            showAlert("错误", "请输入至少一个查询条件！");
            return;
        }

        Platform.runLater(() -> {
            try {
                String url = "jdbc:sqlite:db/dbuml.db3";
                try (Connection conn = DriverManager.getConnection(url)) {
                    StringBuilder sqlBuilder = new StringBuilder("SELECT * FROM warehouse WHERE 1=1");
                    List<Object> params = new ArrayList<>();

                    if (!goodsName.isEmpty()) {
                        sqlBuilder.append(" AND goods_id LIKE ?");
                        params.add("%" + goodsName + "%");
                    }
                    if (!operator.isEmpty()) {
                        sqlBuilder.append(" AND operator LIKE ?");
                        params.add("%" + operator + "%");
                    }
                    if (!supplier.isEmpty()) {
                        sqlBuilder.append(" AND supplier LIKE ?");
                        params.add("%" + supplier + "%");
                    }

                    String sql = sqlBuilder.toString();
                    try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                        for (int i = 0; i < params.size(); i++) {
                            stmt.setString(i + 1, (String) params.get(i));
                        }
                        ResultSet rs = stmt.executeQuery();

                        // 获取当前表格中的数据
                        ObservableList<InventoryManager> existingData = tableView.getItems();
                        // 清空现有数据
                        existingData.clear();

                        boolean found = false;
                        while (rs.next()) {
                            String id = rs.getString("id");
                            String goodsId = rs.getString("goods_id");
                            int quantity = rs.getInt("quantity");
                            String supplierRs = rs.getString("supplier");
                            String operatorRs = rs.getString("operator");
                            String remark = rs.getString("remark");

                            InventoryManager record = new InventoryManager(
                                    id,
                                    goodsId,
                                    quantity,
                                    supplierRs,
                                    null, // 入库时间为 null
                                    null, // 出库时间为 null
                                    operatorRs,
                                    remark,
                                    null // 客户为 null
                            );
                            // 将新的记录添加到现有数据中
                            existingData.add(record);
                            found = true;
                        }
                        if (!found) {
                            showAlert("提示", "未找到匹配的货物！");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                resultLabel.setText("查询失败：" + e.getMessage());
            }
        });
    }
    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();
    }

    // 加填充字段的方法
    private void fillFields(InventoryManager record) {
        goodsField.setText(record.getGoodsId());
        customerField.setText(record.getCustomer());
        quantityField.setText(String.valueOf(record.getQuantity()));
        remarkField.setText(record.getRemark());
    }
}
