package com.zhangmeng.online.exam.ui.components;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;

import java.util.*;

/**
 * @Description: 简答题组件
 * @author zm
 * @date 2025/3/4 15:46
 * @version: 1.0
 */
public class ShortAnswerComponent extends VBox {

    private Button indexButton;

    private Map<String,Object> context = new HashMap<>();

    public Map<String, Object> getContext() {
        return context;
    }

    public void setContext(Map<String, Object> context) {
        this.context = context;
    }

    private String correctAnswer = null; // 预设正确答案

    private int number_of_responses = 0;//作答次数

    private final SimpleStringProperty result_answer = new SimpleStringProperty(); // 最终答案

    private HBox hBox = new HBox();

    private Label questionLabel;

    private TextArea answerArea;

    private List<String> keywords = new ArrayList<>(); // 参考答案关键词（如 ["封装","继承","多态"]）

    private static final String DEFAULT_STYLE_CLASS = "button";

    public void setBackground() {
        indexButton.getStyleClass().remove("custom-button-cancel");
        indexButton.getStyleClass().add("custom-button-click");
    }

    //取消
    public void cancelBackground() {
        indexButton.getStyleClass().remove("custom-button-click");
        indexButton.getStyleClass().add("custom-button-cancel");
    }


    public ShortAnswerComponent(String question, List<Map<String, Object>> options) {

        this.setStyle("-fx-background-color: white; -fx-border-color: #eadcdc;" +
                "-fx-border-radius: 10px; -fx-border-width: 1px; -fx-border-style: solid;-fx-background-radius: 10px;");

        for (Map<String, Object> option : options) {
            keywords.add( option.get("content").toString());
        }

        // 题目展示
        questionLabel = new Label(question);

        hBox.getChildren().add(questionLabel);
        this.getChildren().add(hBox);
        this.setPrefHeight(240);


        // 输入组件
        answerArea = new TextArea();
        answerArea.setMinHeight(200);
        answerArea.setPromptText("在此输入答案（建议不少于50字）");
        answerArea.setWrapText(true); // 自动换行‌:ml-citation{ref="1" data="citationList"}
        this.getChildren().add(answerArea);

        answerArea.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                if (newValue.length() > 0) {
                    setBackground();
                }else {
                    cancelBackground();
                }
            }
        });


        // 功能组件
        Button submitBtn = new Button("提交答案");
        Label resultLabel = new Label();

        // 提交事件处理
        submitBtn.setOnAction(e -> {
            String userAnswer = answerArea.getText().trim();
            if (userAnswer.isEmpty()) {
                resultLabel.setText("⚠ 答案不能为空");
                resultLabel.setStyle("-fx-text-fill: #e67e22;");
                return;
            }

            // 关键词匹配验证
            StringBuilder missingKeys = new StringBuilder();
            int matchCount = 0;
            for (String keyword : keywords) {
                if (userAnswer.contains(keyword)) {
                    matchCount++;
                } else {
                    missingKeys.append("、").append(keyword);
                }
            }

            // 反馈逻辑
            if (matchCount == keywords.size()) {
                resultLabel.setText("✅ 答案完整，包含所有关键词！");
                resultLabel.setStyle("-fx-text-fill: #2ecc71;");
            } else if (matchCount > 0) {
                resultLabel.setText("⚠ 部分正确（缺失：" + missingKeys.substring(1) + "）");
                resultLabel.setStyle("-fx-text-fill: #f1c40f;");
            } else {
                resultLabel.setText("❌ 参考答案关键词：" + String.join(",", keywords));
                resultLabel.setStyle("-fx-text-fill: #e74c3c;");
            }
        });

        // 布局容器
//        this.setSpacing(20);
//        this.setPadding(new Insets(20));
        this.getChildren().addAll(submitBtn, resultLabel);

        // 布局容器
        this.setSpacing(10);
        this.setPadding(new Insets(15));
        this.hBox.getChildren().add(1,resultLabel);

    }

    public Button getIndexButton() {
        return indexButton;
    }

    public void setIndexButton(Button indexButton) {
        this.indexButton = indexButton;
    }
}
