package view;

import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.control.cell.PropertyValueFactory;
import model.DataManager;
import model.Goods;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class GoodsManagementView extends BorderPane {

    private TextField idField;
    private TextField nameField;
    private TextField quantityField;
    private TextField supplierField;
    private TextField remarkField;
    private TableView<Goods> tableView;

    public GoodsManagementView() {
        initializeUI();
    }

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

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

        // 加载现有货��数据
        loadGoodsData();

        // 添加双击事件填充文本字段
        tableView.setOnMouseClicked(event -> {
            if (event.getClickCount() == 2) {
                Goods selectedGoods = tableView.getSelectionModel().getSelectedItem();
                if (selectedGoods != null) {
                    fillFields(selectedGoods);
                }
            }
        });
    }

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

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

        Label idLabel = new Label("单号：");
        idField = new TextField();
        idField.setPromptText("请输入单号");

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

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

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

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

        basicInfo.addRow(0, idLabel, idField, nameLabel, nameField);
        basicInfo.addRow(1, quantityLabel, quantityField, supplierLabel, supplierField);
        basicInfo.addRow(2, remarkLabel, remarkField);

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

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

        // 操作按钮
        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<Goods> createTableView() {
        TableView<Goods> table = new TableView<>();

        TableColumn<Goods, String> idCol = new TableColumn<>("单号");
        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> supplierCol = new TableColumn<>("供应商");
        supplierCol.setCellValueFactory(new PropertyValueFactory<>("supplier"));

        TableColumn<Goods, LocalDateTime> timeCol = new TableColumn<>("入库时间");
        timeCol.setCellValueFactory(new PropertyValueFactory<>("inboundTime"));

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

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

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

        return table;
    }

    private void loadGoodsData() {
        String url = "jdbc:sqlite:db/dbuml.db3";
        List<Goods> goodsList = new ArrayList<>();
        try (Connection conn = DriverManager.getConnection(url)) {
            String sql = "SELECT id, goods_id as name, quantity, " +
                        "supplier, inbound_time, operator, remark " +
                        "FROM warehouse " +
                        "ORDER BY id";  // 不再使用GROUP BY，直接显示所有记录
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {

                while (rs.next()) {
                    Goods goods = new Goods(
                            rs.getString("id"),
                            rs.getString("name"),
                            rs.getInt("quantity"),
                            rs.getString("remark")
                    );
                    goods.setInboundTime(LocalDateTime.parse(rs.getString("inbound_time")));
                    goods.setOperator(rs.getString("operator"));
                    goods.setSupplier(rs.getString("supplier"));
                    goodsList.add(goods);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "加载货物信息失败：" + e.getMessage());
        }
        tableView.setItems(FXCollections.observableArrayList(goodsList));
    }

    private void handleSave() {
        try {
            String id = idField.getText().trim();
            String name = nameField.getText().trim();
            String quantityText = quantityField.getText().trim();
            String supplier = supplierField.getText().trim();
            String remark = remarkField.getText().trim();

            // 输入验证
            if (id.isEmpty()) {
                showAlert("错误", "请先选择要修改的货物记录！");
                return;
            }

            if (name.isEmpty() || quantityText.isEmpty() || supplier.isEmpty()) {
                showAlert("错误", "请填写完整的货物信息！");
                return;
            }

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

            String url = "jdbc:sqlite:db/dbuml.db3";
            try (Connection conn = DriverManager.getConnection(url)) {
                // 修改SQL语句，使用UPDATE而不是INSERT
                String sql = "UPDATE warehouse SET " +
                            "goods_id = ?, " +
                            "quantity = ?, " +
                            "supplier = ?, " +
                            "remark = ? " +
                            "WHERE id = ?";
                            
                try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                    pstmt.setString(1, name);
                    pstmt.setInt(2, quantity);
                    pstmt.setString(3, supplier);
                    pstmt.setString(4, remark);
                    pstmt.setString(5, id);
                    
                    int affectedRows = pstmt.executeUpdate();
                    if (affectedRows > 0) {
                        // 记录操作日志
                        String logSql = "INSERT INTO operation_logs " +
                                      "(id, operation_type, operation_target, operator, operation_time, details) " +
                                      "VALUES (?, ?, ?, ?, ?, ?)";
                        try (PreparedStatement logStmt = conn.prepareStatement(logSql)) {
                            String logId = String.format("LOG%014d", System.currentTimeMillis());
                            logStmt.setString(1, logId);
                            logStmt.setString(2, "修改");
                            logStmt.setString(3, name);
                            logStmt.setString(4, "系统管理员");
                            logStmt.setString(5, LocalDateTime.now().toString());
                            logStmt.setString(6, String.format("修改货物信息：%s，数量：%d，供应商：%s", 
                                name, quantity, supplier));
                            
                            logStmt.executeUpdate();
                        }
                        
                        // 刷新表格
                        loadGoodsData();
                        handleClear();
                        showAlert("成功", "货物信息已更新！");
                    } else {
                        showAlert("错误", "未找到要修改的货物记录！");
                    }
                }
            } catch (SQLException e) {
                e.printStackTrace();
                showAlert("错误", "更新失败：" + e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("错误", "保存失败：" + e.getMessage());
        }
    }

    private void handleClear() {
        idField.clear();
        nameField.clear();
        quantityField.clear();
        supplierField.clear();
        remarkField.clear();
    }

    private void fillFields(Goods goods) {
        idField.setText(goods.getId());
        nameField.setText(goods.getName());
        quantityField.setText(String.valueOf(goods.getQuantity()));
        supplierField.setText(goods.getSupplier());
        remarkField.setText(goods.getRemark());
    }

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