package view;

import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.control.cell.PropertyValueFactory;
import model.DataManager;
import model.OperationLog;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class OperationLogView extends BorderPane {
    
    private TableView<OperationLog> tableView;
    private DatePicker startDatePicker;
    private DatePicker endDatePicker;
    private ComboBox<String> operationTypeComboBox;
    
    public OperationLogView() {
        initializeUI();
    }
    
    private void initializeUI() {
        // 顶部搜索区域
        VBox topArea = createTopArea();
        setTop(topArea);
        
        // 中间表格区域
        tableView = createTableView();
        setCenter(tableView);
        
        // 加载日志数据
        loadLogData();
    }
    
    private VBox createTopArea() {
        VBox topArea = new VBox(10);
        topArea.setPadding(new Insets(10));
        
        // 搜索条件区域
        GridPane searchArea = new GridPane();
        searchArea.setHgap(10);
        searchArea.setVgap(10);
        
        // 时间范围选择
        Label dateRangeLabel = new Label("时间范围：");
        startDatePicker = new DatePicker();
        Label toLabel = new Label("至");
        endDatePicker = new DatePicker();
        
        // 操作类型选择
        Label operationTypeLabel = new Label("操作类型：");
        operationTypeComboBox = new ComboBox<>();
        operationTypeComboBox.getItems().addAll("全部", "入库", "出库", "修改");
        operationTypeComboBox.setValue("全部");
        
        // 搜索按钮
        Button searchButton = new Button("搜索");
        searchButton.setOnAction(e -> handleSearch());
        
        // 添加到网格
        searchArea.addRow(0, dateRangeLabel, startDatePicker, toLabel, endDatePicker);
        searchArea.addRow(1, operationTypeLabel, operationTypeComboBox, searchButton);
        
        topArea.getChildren().add(searchArea);
        return topArea;
    }
    
    private TableView<OperationLog> createTableView() {
        TableView<OperationLog> table = new TableView<>();
        
        TableColumn<OperationLog, String> idCol = new TableColumn<>("单号");
        idCol.setCellValueFactory(new PropertyValueFactory<>("id"));
        
        TableColumn<OperationLog, String> typeCol = new TableColumn<>("操作类型");
        typeCol.setCellValueFactory(new PropertyValueFactory<>("operationType"));
        
        TableColumn<OperationLog, String> targetCol = new TableColumn<>("操作对象");
        targetCol.setCellValueFactory(new PropertyValueFactory<>("operationTarget"));
        
        TableColumn<OperationLog, String> operatorCol = new TableColumn<>("操作人");
        operatorCol.setCellValueFactory(new PropertyValueFactory<>("operator"));
        
        TableColumn<OperationLog, LocalDateTime> timeCol = new TableColumn<>("操作时间");
        timeCol.setCellValueFactory(new PropertyValueFactory<>("operationTime"));
        timeCol.setCellFactory(column -> new TableCell<OperationLog, 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<OperationLog, String> detailsCol = new TableColumn<>("操作详情");
        detailsCol.setCellValueFactory(new PropertyValueFactory<>("details"));
        
        table.getColumns().addAll(idCol, typeCol, targetCol, operatorCol, timeCol, detailsCol);
        return table;
    }
    
    private void loadLogData() {
        try {
            List<OperationLog> logs = DataManager.getInstance().getOperationLogs();
            System.out.println("获取到 " + logs.size() + " 条操作日志");
            
            if (logs.isEmpty()) {
                Label noDataLabel = new Label("暂无操作日志");
                noDataLabel.setStyle("-fx-font-size: 14px;");
                tableView.setPlaceholder(noDataLabel);
            }
            
            tableView.getItems().clear();
            tableView.setItems(FXCollections.observableArrayList(logs));
            
            // 打印每条日志的内容
            for (OperationLog log : logs) {
                System.out.println(String.format("日志: %s - %s - %s", 
                    log.getOperationType(), 
                    log.getOperationTime(), 
                    log.getDetails()));
            }
            
        } catch (Exception e) {
            System.err.println("加载操作日志失败: " + e.getMessage());
            e.printStackTrace();
            showAlert("错误", "加载操作日志失败：" + e.getMessage());
        }
    }
    
    private void handleSearch() {
        try {
            LocalDateTime startDate = startDatePicker.getValue() != null ? 
                startDatePicker.getValue().atStartOfDay() : null;
            LocalDateTime endDate = endDatePicker.getValue() != null ? 
                endDatePicker.getValue().atTime(23, 59, 59) : null;
            String operationType = operationTypeComboBox.getValue();
            
            List<OperationLog> filteredLogs = DataManager.getInstance()
                .getFilteredOperationLogs(startDate, endDate, operationType);
                
            // 设置空数据提示
            if (filteredLogs.isEmpty()) {
                Label noDataLabel = new Label("未找到符合条件的操作日志");
                noDataLabel.setStyle("-fx-font-size: 14px;");
                tableView.setPlaceholder(noDataLabel);
            }
            
            tableView.setItems(FXCollections.observableArrayList(filteredLogs));
            System.out.println("搜索到 " + filteredLogs.size() + " 条操作日志"); // 添加调试输出
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("搜索操作日志失败: " + e.getMessage()); // 添加错误输出
            showAlert("错误", "搜索操作日志失败：" + e.getMessage());
        }
    }
    
    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();
    }
} 