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.InboundRecord;
import model.DataManager;
import model.Goods;
import javafx.collections.FXCollections;
import java.util.List;
import java.util.stream.Collectors;
import java.sql.*;

public class InboundView extends BorderPane {
    
    private TextField goodsField;
    private TextField supplierField;
    private TextField quantityField;
    private TextField remarkField;
    private TableView<InboundRecord> tableView;
    private Label totalValue;
    
    public InboundView() {
        initializeUI();
        loadInboundRecords();
    }
    
    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("供应商：");
        supplierField = new TextField();
        supplierField.setPromptText("请输入供应商");
        
        basicInfo.addRow(0, goodsLabel, goodsField, supplierLabel, supplierField);
        
        // 第二行：数量和备注
        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<InboundRecord> createTableView() {
        TableView<InboundRecord> table = new TableView<>();
        
        TableColumn<InboundRecord, String> idCol = new TableColumn<>("入库单号");
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        
        TableColumn<InboundRecord, String> goodsCol = new TableColumn<>("货物名称");
        goodsCol.setCellValueFactory(new PropertyValueFactory<>("goodsId"));
        
        TableColumn<InboundRecord, Integer> quantityCol = new TableColumn<>("数量");
        quantityCol.setCellValueFactory(new PropertyValueFactory<>("quantity"));
        
        TableColumn<InboundRecord, String> supplierCol = new TableColumn<>("供应商");
        supplierCol.setCellValueFactory(new PropertyValueFactory<>("supplier"));
        
        TableColumn<InboundRecord, LocalDateTime> timeCol = new TableColumn<>("入库时间");
        timeCol.setCellValueFactory(new PropertyValueFactory<>("inboundTime"));
        
        TableColumn<InboundRecord, String> operatorCol = new TableColumn<>("操作员");
        operatorCol.setCellValueFactory(new PropertyValueFactory<>("operator"));
        
        TableColumn<InboundRecord, String> remarkCol = new TableColumn<>("备注");
        remarkCol.setCellValueFactory(new PropertyValueFactory<>("remark"));
        
        table.getColumns().addAll(idCol, goodsCol, quantityCol, supplierCol, 
                                timeCol, operatorCol, remarkCol);
        
        table.getItems().addListener((javafx.collections.ListChangeListener.Change<? extends InboundRecord> 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(InboundRecord::getQuantity)
                .sum();
        totalValue.setText(String.valueOf(total));
    }
    
    private void handleSave() {
        try {
            String goodsName = goodsField.getText().trim();
            String supplier = supplierField.getText().trim();
            String quantityText = quantityField.getText().trim();
            String remark = remarkField.getText().trim();
            
            // 输入验证
            if (goodsName.isEmpty() || supplier.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 = "IN" + System.currentTimeMillis();
            LocalDateTime now = LocalDateTime.now();
            
            // 修改数据库连接为相对路径
            String url = "jdbc:sqlite:db/dbuml.db3";
            try (Connection conn = DriverManager.getConnection(url)) {
                String sql = "INSERT INTO inbound_records (id, goods_id, quantity, supplier, inbound_time, operator, remark) " +
                            "VALUES (?, ?, ?, ?, ?, ?, ?)";
                
                try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    pstmt.setString(1, id);
                    pstmt.setString(2, goodsName);
                    pstmt.setInt(3, quantity);
                    pstmt.setString(4, supplier);
                    pstmt.setString(5, now.toString());
                    pstmt.setString(6, "当前用户");
                    pstmt.setString(7, remark);
                    
                    pstmt.executeUpdate();
                }
            }
            
            // 创建记录对象并添加到表格
            InboundRecord record = new InboundRecord(
                id,
                goodsName,
                quantity,
                supplier,
                now,
                "当前用户",
                remark
            );
            
            // 添加到表格
            tableView.getItems().add(record);
            
            // ��新总计
            updateTotal();
            
            // 清空输入
            handleClear();
            
            // 添加操作日志
            String details = String.format("入库货物：%s，数量：%d，供应商：%s", 
                goodsName, quantity, supplier);
            DataManager.getInstance().addOperationLog("入库", goodsName, "当前用户", details);
            
            showAlert("成功", "入库记录已保存！");
            
        } catch (Exception e) {
            showAlert("错误", "保存失败：" + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private void handleClear() {
        goodsField.clear();
        supplierField.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 loadInboundRecords() {
        String url = "jdbc:sqlite:db/dbuml.db3";
        try (Connection conn = DriverManager.getConnection(url)) {
            String sql = "SELECT * FROM inbound_records ORDER BY inbound_time DESC";
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {
                
                while (rs.next()) {
                    InboundRecord record = new InboundRecord(
                        rs.getString("id"),
                        rs.getString("goods_id"),
                        rs.getInt("quantity"),
                        rs.getString("supplier"),
                        LocalDateTime.parse(rs.getString("inbound_time")),
                        rs.getString("operator"),
                        rs.getString("remark")
                    );
                    tableView.getItems().add(record);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载入库记录失败：" + e.getMessage());
        }
    }
} 