package view;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.control.cell.PropertyValueFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import model.OutboundRecord;
import model.DataManager;
import model.Goods;
import javafx.collections.FXCollections;
import java.util.List;
import java.util.stream.Collectors;
import java.sql.*;

public class OutboundView extends BorderPane {

    private TextField goodsField;
    private TextField customerField;
    private TextField quantityField;
    private TextField remarkField;
    private TableView<OutboundRecord> tableView;
    private Label totalValue;

    public OutboundView() {
        initializeUI();
        loadOutboundRecords();
    }

    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 supplierLabel = new Label("供应商：");
        customerField = new TextField();
        customerField.setPromptText("请输入供应商");

        basicInfo.addRow(0, goodsLabel, goodsField, supplierLabel, customerField);

        // 第二行：数量和备注
        Label quantityLabel = new Label("数量：");
        quantityField = new TextField();
        quantityField.setPromptText("请输入数量");

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

        basicInfo.addRow(1, quantityLabel, quantityField, 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 saveButton = new Button("出库");
        saveButton.setOnAction(e -> handleSave());

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

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

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

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

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

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

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

        TableColumn<OutboundRecord, String> customerCol = new TableColumn<>("供应商");
        customerCol.setCellValueFactory(new PropertyValueFactory<>("customer"));
        customerCol.setPrefWidth(120);

        TableColumn<OutboundRecord, LocalDateTime> timeCol = new TableColumn<>("出库时间");
        timeCol.setCellValueFactory(new PropertyValueFactory<>("outboundTime"));
        timeCol.setPrefWidth(180);
        timeCol.setCellFactory(column -> new TableCell<OutboundRecord, LocalDateTime>() {
            private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            @Override
            protected void updateItem(LocalDateTime item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText(null);
                } else {
                    setText(formatter.format(item));
                }
            }
        });

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

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

        table.getColumns().addAll(idCol, goodsCol, quantityCol, customerCol,
                timeCol, operatorCol, remarkCol);

        // 添加双击事件处理
        table.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                OutboundRecord selectedRecord = table.getSelectionModel().getSelectedItem();
                if (selectedRecord != null) {
                    fillFields(selectedRecord);
                }
            }
        });

        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(OutboundRecord::getQuantity)
                .sum();
        totalValue.setText(String.valueOf(total));
    }

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

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

            int quantity = Integer.parseInt(quantityText);
            if (quantity <= 0) {
                showAlert("错误", "数量必须大于0！");
                return;
            }

            String url = "jdbc:sqlite:db/dbuml.db3";
            try (Connection conn = DriverManager.getConnection(url)) {
                // 首先查询当前库存
                String checkSql = "SELECT id, quantity FROM warehouse WHERE goods_id = ?";
                try (PreparedStatement checkStmt = conn.prepareStatement(checkSql)) {
                    checkStmt.setString(1, goodsName);
                    ResultSet rs = checkStmt.executeQuery();
                    
                    if (rs.next()) {
                        int currentStock = rs.getInt("quantity");
                        String recordId = rs.getString("id");
                        
                        if (currentStock < quantity) {
                            showAlert("错误", "库存不足！当前库存: " + currentStock);
                            return;
                        }
                        
                        int remainingStock = currentStock - quantity;
                        
                        if (remainingStock == 0) {
                            // 如果全部出库，删除记录
                            String deleteSql = "DELETE FROM warehouse WHERE id = ?";
                            try (PreparedStatement deleteStmt = conn.prepareStatement(deleteSql)) {
                                deleteStmt.setString(1, recordId);
                                deleteStmt.executeUpdate();
                            }
                        } else {
                            // 更新剩余库存
                            String updateSql = "UPDATE warehouse SET quantity = ? WHERE id = ?";
                            try (PreparedStatement updateStmt = conn.prepareStatement(updateSql)) {
                                updateStmt.setInt(1, remainingStock);
                                updateStmt.setString(2, recordId);
                                updateStmt.executeUpdate();
                            }
                        }
                        
                        // 刷新表格显示
                        loadOutboundRecords();
                        
                        // 清空输入
                        handleClear();
                        
                        // 添加出库操作日志
                        String details = String.format("出库货物：%s，数量：%d，客户：%s，备注：%s", 
                            goodsName, quantity, customer, remark);
                        System.out.println("正在添加出库日志: " + details);

                        try {
                            DataManager.getInstance().addOperationLog("出库", goodsName, "当前用户", details);
                            System.out.println("出库日志添加成功");
                        } catch (Exception e) {
                            System.err.println("添加出库日志失败: " + e.getMessage());
                            e.printStackTrace();
                        }
                        
                        showAlert("成功", "出库记录已保存！");
                    } else {
                        showAlert("错误", "未找到该货物的库存记录！");
                    }
                }
            }
        } catch (NumberFormatException e) {
            showAlert("错误", "请输入有效的数量！");
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "保存失败：" + e.getMessage());
        }
    }

    private void handleClear() {
        goodsField.clear();
        customerField.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();
    }

    private void loadOutboundRecords() {
        String url = "jdbc:sqlite:db/dbuml.db3";
        try (Connection conn = DriverManager.getConnection(url)) {
            String sql = "SELECT * FROM warehouse ORDER BY inbound_time DESC";
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {
                
                tableView.getItems().clear();
                while (rs.next()) {
                    try {
                        String id = rs.getString("id");
                        String goodsId = rs.getString("goods_id");
                        int quantity = rs.getInt("quantity");
                        String supplier = rs.getString("supplier");
                        String timeStr = rs.getString("inbound_time");
                        String operator = rs.getString("operator");
                        String remark = rs.getString("remark");

                        LocalDateTime dateTime = LocalDateTime.parse(timeStr);
                        
                        OutboundRecord record = new OutboundRecord(
                            id,
                            goodsId,
                            quantity,
                            supplier,
                            dateTime,
                            operator,
                            remark
                        );
                        tableView.getItems().add(record);
                        
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                updateTotal();
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载出库记录失败：" + e.getMessage());
        }
    }

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