package com.bifan.txtreaderlib.ui;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.LongDef;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bifan.txtreaderlib.R;
import com.bifan.txtreaderlib.adapter.MessageAdapter;
import com.bifan.txtreaderlib.bean.ChatMessage_bmob;
import com.bifan.txtreaderlib.bean.ChatRequest;
import com.bifan.txtreaderlib.bean.ChatResponse;
import com.bifan.txtreaderlib.bean.GenerateQue_bmob;
import com.bifan.txtreaderlib.bean.Message;
import com.bifan.txtreaderlib.interfaces.ChatGPTService;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ChatWithGptActivity extends AppCompatActivity implements MessageAdapter.OnRegenerateClickListener {
    private Boolean isStop=false;
    private RecyclerView recyclerView;
    private MessageAdapter messageAdapter;
    private EditText editTextMessage;
    private TextView chatbot_title;
    private ImageView buttonSend, chat_return;
    private String bookName = "";
    private String userid = "";
    private String cite = "";
    private String lastUserQuestion = ""; // 全局变量来存储最后一条用户消息
    private Call<ChatResponse> currentCall = null;

    private ArrayList<Message> messageList = new ArrayList<>();
    private TextView questionView1, questionView2, questionView3, textView_Cite;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chatwithgpt);
        Bmob.initialize(this, "8f9f1d1ea520b0ce4f84a6fa83a5f754");
        if (getIntent() != null) {
            if (getIntent().hasExtra("book_name")) {
                bookName = getIntent().getStringExtra("book_name");
            }
            if (getIntent().hasExtra("cite")) {
                cite = getIntent().getStringExtra("cite");
            }
        }
        SharedPreferences sharedPreferences = getSharedPreferences("userinf", Context.MODE_PRIVATE);
        String userIdFromPrefs = sharedPreferences.getString("user_id", "");
        userid = userIdFromPrefs != null ? userIdFromPrefs : "";
        setupViews();
        init();
        initgenerateUserQuestions();
        loadLastUserMessage();
        setupListeners();
    }

    private void setupListeners() {
        buttonSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 检查是否存在活跃的请求,有的话再点击一次则取消本次请求
                if (currentCall != null) {
                    isStop=true;
                    currentCall.cancel();
                } else {
                    // 没有活跃的请求或请求已完成，发送新的请求
                    String message = editTextMessage.getText().toString();
                    sendandStoreMessage(message); // 发送并存储消息的函数需要你自行实现
                }
            }
        });
        View.OnClickListener questionClickListener = view -> {
            TextView questionView = (TextView) view;
            String message = questionView.getText().toString();
            sendandStoreMessage(message);
        };
        questionView1.setOnClickListener(questionClickListener);
        questionView2.setOnClickListener(questionClickListener);
        questionView3.setOnClickListener(questionClickListener);
        chat_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void clearQuestionsVisibility() {
        questionView1.setVisibility(View.GONE);
        questionView2.setVisibility(View.GONE);
        questionView3.setVisibility(View.GONE);
    }

    private void sendandStoreMessage(String text) {
        clearQuestionsVisibility();
        editTextMessage.setHint("请求中...");
        messageList.add(new Message(text, 1, cite)); // User message
        messageAdapter.notifyItemInserted(messageList.size() - 1);
        editTextMessage.setText("");
        sendMessageToChatGPT(text);
        storeMessage(text, 1);
        hideKeyboard();
    }
    //隐藏软键盘
    private void hideKeyboard() {
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        View view = getCurrentFocus();
        if (view != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    //存储到bmob
    private void storeMessage(String text, int isuser) {
        ChatMessage_bmob chatMessage_bmob = new ChatMessage_bmob(text, isuser, bookName, userid, cite);
        chatMessage_bmob.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
//                                toast("添加数据成功，返回objectId为："+objectId);
                } else {
                    //toast("创建数据失败：" + e.getMessage());
                }
            }
        });
    }

    //初始化视图
    private void setupViews() {
        recyclerView = findViewById(R.id.chatRecyclerView);
        editTextMessage = findViewById(R.id.inputEditText);
        buttonSend = findViewById(R.id.sendButton);
        chatbot_title = findViewById(R.id.chatbot_title);
        questionView1 = findViewById(R.id.question1);
        questionView2 = findViewById(R.id.question2);
        questionView3 = findViewById(R.id.question3);
        textView_Cite = findViewById(R.id.textView_Cite);
        chat_return = findViewById(R.id.chat_return);
        messageAdapter = new MessageAdapter(messageList, this);
        messageAdapter.setOnRegenerateClickListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(messageAdapter);
        chatbot_title.setText(bookName);
        editTextMessage.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 根据输入框是否有文本来禁用或启用按钮
                if(editTextMessage.getHint()=="请求中..."){
                    buttonSend.setEnabled(true);
                }
                else{
                    buttonSend.setEnabled(s.toString().trim().length() > 0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        buttonSend.setEnabled(false);
    }

    private void loadLastUserMessage() {
        BmobQuery<ChatMessage_bmob> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("relatedBook", bookName);
        bmobQuery.addWhereEqualTo("userid", userid);
        bmobQuery.addWhereEqualTo("isuser", 1); // 只查找用户的消息
        bmobQuery.order("-createdAt"); // 按创建时间降序排列，以确保最新的消息排在最前
        bmobQuery.setLimit(1); // 只获取一条记录

        bmobQuery.findObjects(new FindListener<ChatMessage_bmob>() {
            @Override
            public void done(List<ChatMessage_bmob> messages, BmobException e) {
                if (e == null && messages != null && !messages.isEmpty()) {
                    lastUserQuestion = messages.get(0).getContent(); // 获取最新的用户消息
                    if(messages.get(0).getCite()!=""&&messages.get(0).getCite()!=null){
                        lastUserQuestion= "请你根据《" + bookName + "》书中的这段内容：" + messages.get(0).getCite() + ",回答我这个提问：" + lastUserQuestion;
                    }
                } else {
                    Log.e("ChatActivity", "No recent user message found, or error fetching data: " + (e != null ? e.getMessage() : "No details"));
                }
            }
        });
    }
//从数据库加载数据
    private void init() {
        if (cite != "") {
            cite = "引用：" + cite;
            textView_Cite.setVisibility(View.VISIBLE);
            textView_Cite.setText(cite);
        }
        BmobQuery<ChatMessage_bmob> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("relatedBook", bookName);
        bmobQuery.addWhereEqualTo("userid", userid);
        bmobQuery.findObjects(new FindListener<ChatMessage_bmob>() {
            @Override
            public void done(List<ChatMessage_bmob> messages, BmobException e) {
                if (e == null && messages != null) {
                    if (!messages.isEmpty()) {
                        for (ChatMessage_bmob item : messages) {
                            if (item.getContent() == null) {
                                String content = "出现未知错误!";
                                messageList.add(new Message(content, item.getIsuser(), ""));
                            } else {
                                messageList.add(new Message(item.getContent(), item.getIsuser(), item.getCite()));
                            }
                        }
                    } else {
                        // 如果没有消息，添加一条 bot 的欢迎消息
                        String welcomeMessage = "你好！我是你的阅读助手。我可以帮助你解答关于书籍的各种问题，比如内容概述、作者信息、主要主题和角色分析等。请随时向我提问，现在，你有什么关于《" + bookName + "》的问题吗？";
                        messageList.add(new Message(welcomeMessage, 0, "")); // 假设 0 表示系统或助手消息
                        ChatMessage_bmob chatMessage_bmob = new ChatMessage_bmob(welcomeMessage, 0, bookName, userid, "");
                        chatMessage_bmob.save(new SaveListener<String>() {
                            @Override
                            public void done(String objectId, BmobException e) {
                                if (e == null) {
//                                toast("添加数据成功，返回objectId为："+objectId);
                                } else {
                                    //toast("创建数据失败：" + e.getMessage());
                                }
                            }
                        });

                    }
                    messageAdapter.notifyDataSetChanged();
                } else {
                    Log.e("BookInfo", "Error loading book info: " + (e != null ? e.getMessage() : ""));
                }
            }
        });
    }
    //加载模拟用户评论
    private void initgenerateUserQuestions() {
        BmobQuery<ChatMessage_bmob> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("relatedBook", bookName);
        bmobQuery.addWhereEqualTo("userid", userid);
        bmobQuery.addWhereEqualTo("isuser", 1);
        bmobQuery.findObjects(new FindListener<ChatMessage_bmob>() {
            @Override
            public void done(List<ChatMessage_bmob> messages, BmobException e) {
                if (e == null && messages != null) {
                    if (!messages.isEmpty()) {
                        BmobQuery<GenerateQue_bmob> bmobQueryGen = new BmobQuery<>();
                        bmobQueryGen.addWhereEqualTo("relatedBook", bookName);
                        bmobQueryGen.addWhereEqualTo("userid", userid);
                        bmobQueryGen.findObjects(new FindListener<GenerateQue_bmob>() {
                            @Override
                            public void done(List<GenerateQue_bmob> list, BmobException e) {
                                if (e == null) {
                                    for (GenerateQue_bmob generateQue : list) {
                                        if (generateQue.getQues1() != null) {
                                            questionView1.setVisibility(View.VISIBLE);
                                            questionView1.setText(generateQue.getQues1());
                                        }
                                        if (generateQue.getQues2() != null) {
                                            questionView2.setVisibility(View.VISIBLE);
                                            questionView2.setText(generateQue.getQues2());
                                        }
                                        if (generateQue.getQues2() != null) {
                                            questionView3.setVisibility(View.VISIBLE);
                                            questionView3.setText(generateQue.getQues3());
                                        }
                                    }
                                } else {

                                }
                            }
                        });
                    } else {
                        questionView1.setVisibility(View.VISIBLE);
                        questionView1.setText("请告诉我有关这本书的内容概述。");
                        questionView2.setVisibility(View.VISIBLE);
                        questionView2.setText("请告诉有关这本书作者的信息。");
                        questionView3.setVisibility(View.VISIBLE);
                        questionView3.setText("请告诉我这本书的主题是什么。");
                    }
                    messageAdapter.notifyDataSetChanged();
                } else {
                    Log.e("BookInfo", "Error loading book info: " + (e != null ? e.getMessage() : ""));
                }
            }
        });
    }

    /**
     * 从数据库加载历史对话并构建消息列表
     */
    private List<ChatRequest.Message> loadMessagesFromDatabase(String bookName, String userId) {
        List<ChatRequest.Message> messages = new ArrayList<>();
        BmobQuery<ChatMessage_bmob> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("relatedBook", bookName);
        bmobQuery.addWhereEqualTo("userid", userId);
        bmobQuery.order("-createdAt");
        bmobQuery.setLimit(10);     //设置上下文最多10条历史对话
        bmobQuery.findObjects(new FindListener<ChatMessage_bmob>() {
            @Override
            public void done(List<ChatMessage_bmob> chatMessages, BmobException e) {
                if (e == null && chatMessages != null && !chatMessages.isEmpty()) {
                    for (ChatMessage_bmob item : chatMessages) {
                        String role = item.getIsuser() == 0 ? "user" : "assistant";
                        messages.add(new ChatRequest.Message(role, item.getContent()));
                    }
                    Collections.reverse(messages); // 反转列表以使消息按时间升序排列, 展示最近的10条数据，按时间顺序。
                } else {
                    Log.e("BookInfo", "Error loading book info: " + (e != null ? e.getMessage() : "No error details."));
                }
            }
        });
        return messages;
    }

    private void sendMessageToChatGPT(String messageText) {
        moveToNewest();
        buttonSend.setImageResource(R.drawable.ic_loading);
        if (cite != "") {
            textView_Cite.setVisibility(View.GONE);
            messageText = "请你根据《" + bookName + "》书中的这段内容：" + cite +
                    ",回答我这个提问：" + messageText;
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl("https://api.openai-ch.top/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ChatGPTService service = retrofit.create(ChatGPTService.class);
        List<ChatRequest.Message> messages = new ArrayList<>();
        String prompt = "你是一个专业的阅读助手。请确保你的回答准确而精炼。如果有任何偏离《" + bookName + "》的问题，你应该尽力引导对话回到书籍讨论上来。";

        if (messageText.equals("请告诉我更多内容。") && !lastUserQuestion.isEmpty()) {
            // 特别关注用户的上一个问题
            prompt += "用户之前问了关于《" + bookName + "》的'" + lastUserQuestion + "'。关于这个问题，请你对你原先的回答进行补充说明？";
        } else if (!lastUserQuestion.isEmpty()) {
            // 处理正常的用户问题
            prompt += "用户提出的上一个问题是：" + lastUserQuestion + "，你可以有个了解，准备应对用户提出的新问题。";
        } else {
            // 没有历史问题的情况
            prompt += "你可以帮助用户解答关于《" + bookName + "》的各种问题，比如内容概述、作者信息、主要主题和角色分析等。";
        }
        messages.add(new ChatRequest.Message("system", prompt));
        messages.addAll(loadMessagesFromDatabase(bookName, userid));
        messages.add(new ChatRequest.Message("user", messageText+"。你的回答不应超过250个字。"));  // 添加用户消息
        ChatRequest request = new ChatRequest(messages);  // 使用消息列表创建请求
        request.setModel("gpt-4-turbo"); // 根据需要选择不同的模型
        request.setMaxTokens(50); // 设置最大 token 数，根据需要调整
        request.setTemperature(0.5); // 设置适当的温度
        currentCall = service.postMessage(request);
        String finalMessageText = messageText;
        currentCall.enqueue(new Callback<ChatResponse>() {
            @Override
            public void onResponse(Call<ChatResponse> call, Response<ChatResponse> response) {
                lastUserQuestion= finalMessageText;
                    if (response.isSuccessful() && response.body() != null) {
                        ChatResponse chatResponse = response.body();
                        if (chatResponse.choices != null && !chatResponse.choices.isEmpty()) {
                            ChatResponse.Message message = chatResponse.choices.get(0).message;
                            String reply = message.content; // 这是从 GPT-3.5 响应中提取的内容
                            runOnUiThread(() -> {
                                cite = "";
                                editTextMessage.setHint("与阅读小助手交谈...");
                                messageList.add(new Message(reply, 0, ""));
                                messageAdapter.notifyDataSetChanged();
                                moveToNewest();
                                buttonSend.setImageResource(R.drawable.ic_send);
                                generateUserQuestions(reply);
                                storeMessage(reply, 0);
                            });
                        }
                        currentCall = null; // 请求失败后清空引用
                    } else {
                        try {
                            String errorBody = response.errorBody() != null ? response.errorBody().string() : "Unknown error";
                            Log.e("ChatGPT", "Error: " + errorBody);
                        } catch (IOException e) {
                            Log.e("ChatGPT", "Error reading error body", e);
                        }
                    }
            }

            @Override
            public void onFailure(Call<ChatResponse> call, Throwable t) {
                if(isStop==true){
                    buttonSend.setImageResource(R.drawable.ic_send);
                    editTextMessage.setHint("与阅读小助手交谈...");
                    isStop=false;
                }
                else {
                    String content = "机器人响应超时，请重新生成回答！";
                    buttonSend.setImageResource(R.drawable.ic_send);
                    messageList.add(new Message(content, 0, ""));
                    messageAdapter.notifyDataSetChanged();
                    moveToNewest();
                    currentCall = null; // 请求失败后清空引用
                    storeMessage(content, 0);
                    Log.e("ChatGPT", "Failure: " + t.getMessage());
                }
            }
        });
    }


    //自动移动至最新回答
    private void moveToNewest() {
        NestedScrollView nestedScrollView = findViewById(R.id.nestedScrollView);
        recyclerView.post(() -> {
            // 确保最后一条消息可见
            if (messageList.size() > 0) {
                recyclerView.scrollToPosition(messageList.size() - 1);
                recyclerView.post(() -> {
                    // 获取最后一个视图的引用
                    View lastChild = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
                    int bottom = lastChild.getBottom() + recyclerView.getPaddingBottom();
                    int sy = nestedScrollView.getScrollY();
                    int sh = nestedScrollView.getHeight();
                    int delta = bottom - (sy + sh);
                    nestedScrollView.smoothScrollBy(0, delta);
                });
            }
        });
    }

    //回调函数，重新生成回答
    @Override
    public void onRegenerateClick(int position) {
        clearQuestionsVisibility();
        BmobQuery<ChatMessage_bmob> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("relatedBook", bookName);
        bmobQuery.addWhereEqualTo("userid", userid);
        bmobQuery.addWhereEqualTo("isuser", 0);
        bmobQuery.order("-createdAt");
        bmobQuery.setLimit(2);
        bmobQuery.findObjects(new FindListener<ChatMessage_bmob>() {
            @Override
            public void done(List<ChatMessage_bmob> chatMessages, BmobException e) {
                if (e == null && chatMessages != null && !chatMessages.isEmpty()) {
                    for (ChatMessage_bmob item : chatMessages) {
                        ChatMessage_bmob chatMessage_bmob = new ChatMessage_bmob();
                        chatMessage_bmob.setObjectId(item.getObjectId());
                        chatMessage_bmob.delete(new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if (e == null) {
                                    // 删除成功
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            messageList.remove(position);
                                            messageAdapter.notifyItemRemoved(position);
                                            messageAdapter.notifyItemRangeChanged(position, messageList.size());
                                            sendMessageToChatGPT(lastUserQuestion);
                                        }
                                    });
                                } else {
                                    // 删除失败
                                }
                            }
                        });
                    }
                }
            }
        });
    }

    //模拟生成用户回答
    private void generateUserQuestions(String lastBotReply) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl("https://api.openai-ch.top/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ChatGPTService service = retrofit.create(ChatGPTService.class);

        // 构建请求数据
        List<ChatRequest.Message> messages = new ArrayList<>();
        messages.add(new ChatRequest.Message("system", "请你模拟用户的口吻，基于《" + bookName + "》" +
                "的内容，请根据上一条聊天机器人的回复，生成两个读者可能的简短提问，每个提问不多于20个字，每个问题占一行,以序号开头，示例如下：1.勒庞是否提出了群体心理中的自我意识丧失和传染性特征？" +
                "2.《乌合之众》是否强调了群体行为易受领导者情感诉求的影响？"));
        messages.add(new ChatRequest.Message("user", lastBotReply));  // 模拟用户的提问

        ChatRequest request = new ChatRequest(messages);
        request.setModel("gpt-3.5-turbo");
        request.setMaxTokens(60);
        request.setTemperature(0.9); // 较高温度以增加多样性

        service.postMessage(request).enqueue(new Callback<ChatResponse>() {
            @Override
            public void onResponse(Call<ChatResponse> call, Response<ChatResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ChatResponse chatResponse = response.body();
                    List<String> questions = extractQuestions(chatResponse);
                    runOnUiThread(() -> displayQuestions(questions));
                } else {
                    try {
                        String errorBody = response.errorBody() != null ? response.errorBody().string() : "Unknown error";
                        Log.e("ChatGPT", "Error: " + errorBody);
                    } catch (IOException e) {
                        Log.e("ChatGPT", "Error reading error body", e);
                    }
                }
            }

            @Override
            public void onFailure(Call<ChatResponse> call, Throwable t) {
                Log.e("ChatGPT", "Failure: " + t.getMessage());
            }
        });
    }

    // 提取问题
    private List<String> extractQuestions(ChatResponse response) {
        GenerateQue_bmob generateQue_bmob = new GenerateQue_bmob();
        generateQue_bmob.setQues1("请告诉我更多内容。");
        generateQue_bmob.setUserid(userid);
        generateQue_bmob.setRelatedBook(bookName);
        List<String> questions = new ArrayList<>();

        if (response.getChoices() != null && !response.getChoices().isEmpty()) {
            String text = response.choices.get(0).message.content;
            if (text != null && !text.trim().isEmpty()) {
                Log.d("ChatGPT Response:", text);
                String[] lines = text.trim().split("\\r?\\n");
                int questionIndex = 2; // Start from ques2 since ques1 is set by default

                for (String line : lines) {
                    if (line.matches("^\\d+\\.\\s+.*")) {
                        String cleanedLine = line.replaceFirst("^\\d+\\.\\s*", "");
                        if (!cleanedLine.trim().isEmpty()) {
                            questions.add(cleanedLine);
                            // Set questions to Bmob object based on availability
                            if (questionIndex == 2) {
                                generateQue_bmob.setQues2(cleanedLine);
                                questionIndex++;
                            } else if (questionIndex == 3) {
                                generateQue_bmob.setQues3(cleanedLine);
                                questionIndex++;
                            }
                        }
                    }
                }
            }
        }
        BmobQuery<GenerateQue_bmob> bmobQuery = new BmobQuery<>();
        bmobQuery.addWhereEqualTo("relatedBook", bookName);
        bmobQuery.addWhereEqualTo("userid", userid);
        bmobQuery.findObjects(new FindListener<GenerateQue_bmob>() {
            @Override
            public void done(List<GenerateQue_bmob> list, BmobException e) {
                if (e == null && !list.isEmpty()) {
                    generateQue_bmob.update(list.get(0).getObjectId(), new UpdateListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                //toast("更新成功:"+p2.getUpdatedAt());
                            } else {
                                //toast("更新失败：" + e.getMessage());
                            }
                        }
                    });
                } else {
                    // Save the Bmob object to database
                    generateQue_bmob.save(new SaveListener<String>() {
                        @Override
                        public void done(String objectId, BmobException e) {
                            if (e == null) {
                                Log.d("Save Successful", "Object saved with objectId: " + objectId);
                            } else {
                                Log.e("Save Failed", "Error saving object: " + e.getMessage());
                            }
                        }
                    });
                }
            }
        });
        return questions;
    }


    // 将问题显示在 UI 上的逻辑
    private void displayQuestions(List<String> questions) {
        questionView1.setText("请告诉我更多内容。");
        questionView1.setVisibility(View.VISIBLE);

        // Display questions based on size
        if (questions.size() > 0) {
            questionView2.setText(questions.get(0));
            questionView2.setVisibility(View.VISIBLE);
        }
        if (questions.size() > 1) {
            questionView3.setText(questions.get(1));
            questionView3.setVisibility(View.VISIBLE);
        }
    }
}
