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.ResultSet;
import java.sql.Statement;
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 specificationField;
    private TextField unitField;
    private TextField priceField;
    private TextField categoryField;
    private TextField quantityField;
    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("货物ID：");
        idField = new TextField();
        idField.setPromptText("请输入货物ID");

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

        Label specificationLabel = new Label("规格：");
        specificationField = new TextField();
        specificationField.setPromptText("请输入规格");

        Label unitLabel = new Label("单位：");
        unitField = new TextField();
        unitField.setPromptText("请输入单位");

        Label priceLabel = new Label("价格：");
        priceField = new TextField();
        priceField.setPromptText("请输入价格");

        Label categoryLabel = new Label("类别：");
        categoryField = new TextField();
        categoryField.setPromptText("请输入类别");

        basicInfo.addRow(0, idLabel, idField, nameLabel, nameField);
        basicInfo.addRow(1, specificationLabel, specificationField, unitLabel, unitField);
        basicInfo.addRow(2, priceLabel, priceField, categoryLabel, categoryField);

        // 库存信息
        GridPane stockInfo = new GridPane();
        stockInfo.setHgap(10);
        stockInfo.setVgap(10);

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

        stockInfo.addRow(0, quantityLabel, quantityField);

        // 设置列宽
        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);
        stockInfo.getColumnConstraints().addAll(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, stockInfo, buttonBox);
        return topArea;
    }

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

        TableColumn<Goods, String> idCol = new TableColumn<>("货物ID");
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));

        TableColumn<Goods, String> nameCol = new TableColumn<>("货物名称");
        nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));

        TableColumn<Goods, String> specificationCol = new TableColumn<>("规格");
        specificationCol.setCellValueFactory(new PropertyValueFactory<>("specification"));

        TableColumn<Goods, String> unitCol = new TableColumn<>("单位");
        unitCol.setCellValueFactory(new PropertyValueFactory<>("unit"));

        TableColumn<Goods, Double> priceCol = new TableColumn<>("价格");
        priceCol.setCellValueFactory(new PropertyValueFactory<>("price"));

        TableColumn<Goods, String> categoryCol = new TableColumn<>("类别");
        categoryCol.setCellValueFactory(new PropertyValueFactory<>("category"));

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

        // 新增的列
        TableColumn<Goods, LocalDateTime> inboundTimeCol = new TableColumn<>("入库时间");
        inboundTimeCol.setCellValueFactory(new PropertyValueFactory<>("inboundTime"));

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

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

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

        table.getColumns().addAll(idCol, nameCol, specificationCol, unitCol, priceCol, categoryCol, quantityCol,
                inboundTimeCol, operatorCol, supplierCol, 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 * FROM goods";
            try (Statement stmt = conn.createStatement();
                 ResultSet rs = stmt.executeQuery(sql)) {

                while (rs.next()) {
                    Goods goods = new Goods(
                            rs.getString("id"),
                            rs.getString("name"),
                            rs.getString("specification"),
                            rs.getString("unit"),
                            rs.getDouble("price"),
                            rs.getString("category"),
                            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 specification = specificationField.getText().trim();
            String unit = unitField.getText().trim();
            String priceText = priceField.getText().trim();
            String category = categoryField.getText().trim();
            String quantityText = quantityField.getText().trim();

            // 输入验证
            if (id.isEmpty() || name.isEmpty() || specification.isEmpty() || unit.isEmpty() ||
                    priceText.isEmpty() || category.isEmpty() || quantityText.isEmpty()) {
                showAlert("错误", "请填写完整的货物信息！");
                return;
            }

            double price;
            int quantity;
            try {
                price = Double.parseDouble(priceText);
                if (price <= 0) {
                    showAlert("错误", "价格必须大于0！");
                    return;
                }
            } catch (NumberFormatException e) {
                showAlert("错误", "请输入有效的价格！");
                return;
            }

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

            // 查找货物对象
            Goods existingGoods = DataManager.getInstance().getGoods(id);
            if (existingGoods == null) {
                // 插入新货物
                Goods newGoods = new Goods(id, name, specification, unit, price, category, quantity, "");
                newGoods.setInboundTime(LocalDateTime.now());
                newGoods.setOperator("当前用户");
                DataManager.getInstance().addGoodsToDatabase(newGoods);
            } else {
                // 更新现有货物
                existingGoods.setName(name);
                existingGoods.setSpecification(specification);
                existingGoods.setUnit(unit);
                existingGoods.setPrice(price);
                existingGoods.setCategory(category);
                existingGoods.setQuantity(quantity);
                DataManager.getInstance().updateGoodsInDatabase(existingGoods);
            }

            // 更新表格
            loadGoodsData();

            // 清空输入
            handleClear();

            showAlert("成功", "货物信息已更新！");

        } catch (Exception e) {
            showAlert("错误", "保存失败：" + e.getMessage());
            e.printStackTrace(); // 添加堆栈跟踪以便调试
        }
    }

    private void handleClear() {
        idField.clear();
        nameField.clear();
        specificationField.clear();
        unitField.clear();
        priceField.clear();
        categoryField.clear();
        quantityField.clear();
    }

    private void fillFields(Goods goods) {
        idField.setText(goods.getId());
        nameField.setText(goods.getName());
        specificationField.setText(goods.getSpecification());
        unitField.setText(goods.getUnit());
        priceField.setText(String.valueOf(goods.getPrice()));
        categoryField.setText(goods.getCategory());
        quantityField.setText(String.valueOf(goods.getQuantity()));
    }

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


}
