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;

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();
    }

    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 customerLabel = new Label("客户：");
        customerField = new TextField();
        customerField.setPromptText("请输入客户");

        basicInfo.addRow(0, goodsLabel, goodsField, customerLabel, 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"));

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

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

        TableColumn<OutboundRecord, String> customerCol = new TableColumn<>("客户");
        customerCol.setCellValueFactory(new PropertyValueFactory<>("customer"));

        TableColumn<OutboundRecord, LocalDateTime> timeCol = new TableColumn<>("出库时间");
        timeCol.setCellValueFactory(new PropertyValueFactory<>("outboundTime"));

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

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

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

        table.getItems().addListener((javafx.collections.ListChangeListener.Change<? extends OutboundRecord> 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(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;
            try {
                quantity = Integer.parseInt(quantityText);
                if (quantity <= 0) {
                    showAlert("错误", "数量必须大于0！");
                    return;
                }
            } catch (NumberFormatException e) {
                showAlert("错误", "请输入有效的数量！");
                return;
            }

            // 创建出库记录
            String id = "OUT" + System.currentTimeMillis();
            OutboundRecord record = new OutboundRecord(
                    id,
                    goodsName,
                    quantity,
                    customer,
                    LocalDateTime.now(),
                    "当前用户",
                    remark
            );

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

            // 更新总计
            updateTotal();

            // 清空输入
            handleClear();

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

            // 在handleSave方法中添加日志记录
            String details = String.format("出库货物：%s，数量：%d，客户：%s", 
                goodsName, quantity, customer);
            DataManager.getInstance().addOperationLog("出库", goodsName, "当前用户", details);

        } catch (Exception e) {
            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();
    }
}