"use strict";
const common_vendor = require("../../common/vendor.js");
const api_user = require("../../api/user.js");
const common_assets = require("../../common/assets.js");
const _sfc_main = {
  data() {
    return {
      cameraContext: null,
      devicePosition: "front",
      interviewStarted: true,
      showEndModal: false,
      currentQuestionIndex: 0,
      currentStep: 1,
      stepTexts: ["测试准备", "回答问题", "测试结束"],
      progressWidth: 50,
      remainingTime: "00:27",
      selectedOption: null,
      selectedOptions: [],
      showResult: false,
      isAnswerCorrect: false,
      questions: [],
      // 改为空数组，将通过API获取
      interviewId: null,
      // 存储当前面试ID
      useVideo: false,
      timerInterval: null,
      score: 0,
      totalQuestions: 0,
      interviewCompleted: false,
      digitalHumanUrl: "",
      // 数字人URL
      loading: true,
      // 添加加载状态
      loadError: false,
      // 添加加载错误状态
      errorMessage: "",
      // 添加错误消息
      answers: [],
      // 存储用户的所有答案
      currentQuestionDetail: null,
      // 当前题目详情
      isSubmitting: false,
      // 是否正在提交答案
      openQuestionAnswer: "",
      // 存储开放问题的答案
      currentAnswer: null,
      // 存储当前答案以便提交
      questionStartTime: null
      // 存储问题开始时间
    };
  },
  computed: {
    currentQuestion() {
      console.log(this.questions[this.currentQuestionIndex]);
      return this.questions[this.currentQuestionIndex];
    }
  },
  onLoad(options) {
    if (options && options.id) {
      this.interviewId = options.id;
      this.fetchInterviewData();
    } else {
      this.fetchInterviewList();
    }
  },
  onReady() {
    this.cameraContext = common_vendor.index.createCameraContext();
    if (this.useVideo) {
      this.aiVideoContext = common_vendor.index.createVideoContext("aiInterviewer");
    }
    this.initDigitalHuman();
  },
  methods: {
    // 获取面试列表
    async fetchInterviewList() {
      try {
        this.loading = true;
        const res2 = await api_user.getInterviewList({ job_id: JSON.parse(common_vendor.index.getStorageSync("selectedJob")).id });
        console.log(res2);
        this.interviewId = res2;
        this.fetchInterviewData(res2);
      } catch (error) {
        console.error("获取面试列表失败:", error);
        this.handleLoadError("获取面试列表失败");
      }
    },
    // 获取面试详情数据
    async fetchInterviewData(data) {
      try {
        this.loading = true;
        if (data && Array.isArray(data)) {
          this.questions = data.map((q, index) => ({
            id: q.id || index + 1,
            text: q.question || "未知问题",
            options: q.options || [],
            correctAnswer: q.correctAnswer || 0,
            isImportant: q.is_system || false,
            explanation: q.explanation || "",
            questionType: q.question_form,
            questionTypeName: q.question_form_name || "单选题",
            correctAnswers: q.correct_answers || [],
            difficulty: q.difficulty || 1,
            difficultyName: q.difficulty_name || "初级"
          }));
        } else {
          this.processInterviewData(res);
        }
        console.log(this.questions);
        this.totalQuestions = this.questions.length;
        if (this.questions.length > 0) {
          this.startTimer();
        }
      } catch (error) {
        console.error("获取面试详情失败:", error);
        this.handleLoadError("获取面试详情失败");
      } finally {
        this.loading = false;
      }
    },
    // 处理面试数据
    processInterviewData(data) {
      this.questions = [];
      if (data) {
        const formattedQuestion = {
          id: data.id || 1,
          text: data.question || "未知问题",
          options: data.options || [],
          correctAnswer: data.correctAnswer || 0,
          isImportant: data.is_system || false,
          explanation: data.explanation || "",
          questionType: data.question_form,
          // 1-单选题，2-多选题
          questionTypeName: data.question_form_name || "单选题",
          correctAnswers: data.correct_answers || [],
          difficulty: data.difficulty || 1,
          difficultyName: data.difficulty_name || "初级"
        };
        this.questions.push(formattedQuestion);
        this.totalQuestions = this.questions.length;
        this.startTimer();
      } else {
        this.handleLoadError("面试中没有问题");
      }
    },
    // 处理加载错误
    handleLoadError(message) {
      this.loadError = true;
      this.loading = false;
      this.errorMessage = message || "加载失败";
      common_vendor.index.showToast({
        title: message || "加载失败",
        icon: "none",
        duration: 2e3
      });
    },
    startTimer() {
      if (this.questions.length === 0)
        return;
      this.questionStartTime = /* @__PURE__ */ new Date();
      let seconds = 30;
      this.timerInterval = setInterval(() => {
        seconds--;
        if (seconds <= 0) {
          clearInterval(this.timerInterval);
          if (!this.showResult) {
            this.checkAnswer();
          }
        }
        const min = Math.floor(seconds / 60).toString().padStart(2, "0");
        const sec = (seconds % 60).toString().padStart(2, "0");
        this.remainingTime = `${min}:${sec}`;
      }, 1e3);
    },
    resetTimer() {
      clearInterval(this.timerInterval);
      this.startTimer();
    },
    selectOption(index) {
      if (this.showResult)
        return;
      if (this.currentQuestion.questionType === 2) {
        const optionIndex = this.selectedOptions.indexOf(index);
        if (optionIndex > -1) {
          this.selectedOptions.splice(optionIndex, 1);
        } else {
          this.selectedOptions.push(index);
        }
      } else if (this.currentQuestion.questionType === 1) {
        this.selectedOption = index;
      }
      this.playAiSpeaking();
    },
    checkAnswer() {
      clearInterval(this.timerInterval);
      if (!this.currentQuestion) {
        console.error("当前问题不存在");
        return;
      }
      if (this.currentQuestion.questionType === 0) {
        this.isAnswerCorrect = true;
      } else if (this.currentQuestion.questionType === 2) {
        const sortedSelected = [...this.selectedOptions].sort();
        const sortedCorrect = [...this.currentQuestion.correctAnswers].sort();
        if (sortedSelected.length !== sortedCorrect.length) {
          this.isAnswerCorrect = false;
        } else {
          this.isAnswerCorrect = sortedSelected.every((value, index) => value === sortedCorrect[index]);
        }
      } else {
        this.isAnswerCorrect = this.selectedOption === this.currentQuestion.correctAnswer;
      }
      this.showResult = true;
    },
    nextQuestion(data) {
      if (!this.showResult) {
        this.checkAnswer();
        this.saveAnswer(data);
        this.submitCurrentAnswer(data).then(() => {
          this.showResult = true;
        }).catch((error) => {
          console.error("提交答案失败:", error);
          common_vendor.index.showToast({
            title: "提交答案失败，请重试",
            icon: "none"
          });
          this.showResult = true;
        });
        return;
      }
      if (this.currentQuestionIndex >= this.questions.length - 1) {
        this.showEndModal = true;
        return;
      }
      this.goToNextQuestion();
    },
    // 保存当前题目的答案
    saveAnswer() {
      let answer;
      if (this.currentQuestion.questionType === 0) {
        answer = {
          questionId: this.currentQuestion.id,
          questionType: this.currentQuestion.questionType,
          answer: this.openQuestionAnswer,
          answerDuration: this.getAnswerDuration()
          // 添加答题时长
        };
      } else {
        answer = {
          questionId: this.currentQuestion.id,
          questionType: this.currentQuestion.questionType,
          answer: this.currentQuestion.questionType === 1 ? this.selectedOption : this.selectedOptions,
          answerDuration: this.getAnswerDuration()
          // 添加答题时长
        };
      }
      const existingIndex = this.answers.findIndex((a) => a.questionId === answer.questionId);
      if (existingIndex > -1) {
        this.answers[existingIndex] = answer;
      } else {
        this.answers.push(answer);
      }
      this.currentAnswer = answer;
      console.log("已保存答案:", this.answers);
    },
    // 获取答题时长（秒）
    getAnswerDuration() {
      const remainingTimeArr = this.remainingTime.split(":");
      const remainingSeconds = parseInt(remainingTimeArr[0]) * 60 + parseInt(remainingTimeArr[1]);
      return 30 - remainingSeconds;
    },
    // 提交当前答案
    async submitCurrentAnswer() {
      if (!this.currentAnswer)
        return;
      try {
        common_vendor.index.showLoading({
          title: "正在提交答案..."
        });
        let answerContent = "";
        if (this.currentAnswer.questionType === 0) {
          answerContent = this.currentAnswer.answer;
        } else if (this.currentAnswer.questionType === 1) {
          const selectedIndex = this.currentAnswer.answer;
          const selectedOption = this.currentQuestion.options[selectedIndex];
          answerContent = selectedOption.id ? selectedOption.id.toString() : selectedIndex.toString();
        } else if (this.currentAnswer.questionType === 2) {
          const selectedIndices = this.currentAnswer.answer;
          const selectedOptionIds = selectedIndices.map((index) => {
            const option = this.currentQuestion.options[index];
            return option.id ? option.id : index;
          });
          answerContent = selectedOptionIds.join(",");
        }
        const submitData = {
          application_id: 1,
          // 或者使用其他合适的ID
          question_id: this.currentAnswer.questionId,
          answer_content: answerContent,
          answer_duration: this.currentAnswer.answerDuration || 0,
          // 如果需要tenant_id，请在这里添加
          tenant_id: 1
        };
        console.log("提交数据:", submitData);
        const res2 = await this.$http.post("http://192.168.66.187:8083/api/job/submit_answer", submitData);
        console.log("提交答案响应:", res2);
        common_vendor.index.hideLoading();
        return res2;
      } catch (error) {
        console.error("提交答案失败:", error);
        common_vendor.index.hideLoading();
        common_vendor.index.showToast({
          title: "提交答案失败，请重试",
          icon: "none"
        });
        throw error;
      }
    },
    // 修改 goToNextQuestion 方法，添加 async 关键字
    async goToNextQuestion() {
      this.showResult = false;
      this.selectedOption = null;
      this.selectedOptions = [];
      this.openQuestionAnswer = "";
      this.currentQuestionIndex++;
      if (this.questions[this.currentQuestionIndex]) {
        this.progressWidth = (this.currentQuestionIndex + 1) / this.questions.length * 100;
        this.resetTimer();
        this.playAiSpeaking();
        setTimeout(() => {
          this.pauseAiSpeaking();
        }, 2e3);
        return;
      }
      try {
        this.loading = true;
        await new Promise((resolve) => setTimeout(resolve, 1e3));
        const res2 = {
          /* 模拟的题目数据 */
        };
        if (res2) {
          const formattedQuestion = {
            id: res2.id || this.currentQuestionIndex + 1,
            text: res2.question || "未知问题",
            options: res2.options || [],
            correctAnswer: res2.correctAnswer || 0,
            isImportant: res2.is_system || false,
            explanation: res2.explanation || "",
            questionType: res2.question_form || 1,
            questionTypeName: res2.question_form_name || "单选题",
            correctAnswers: res2.correct_answers || [],
            difficulty: res2.difficulty || 1,
            difficultyName: res2.difficulty_name || "初级"
          };
          this.questions.push(formattedQuestion);
        }
      } catch (error) {
        console.error("获取题目详情失败:", error);
        common_vendor.index.showToast({
          title: "获取题目失败，请重试",
          icon: "none"
        });
        this.currentQuestionIndex--;
      } finally {
        this.loading = false;
        this.progressWidth = (this.currentQuestionIndex + 1) / this.questions.length * 100;
        this.resetTimer();
      }
    },
    toggleSettings() {
      common_vendor.index.showToast({
        title: "设置功能开发中",
        icon: "none"
      });
    },
    back() {
      if (this.timerInterval) {
        clearInterval(this.timerInterval);
      }
      try {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          common_vendor.index.reLaunch({
            url: "/pages/index/index"
          });
        } else {
          common_vendor.index.reLaunch({
            url: "/pages/index/index"
          });
        }
      } catch (e) {
        console.error("导航错误:", e);
        common_vendor.index.reLaunch({
          url: "/pages/index/index"
        });
      }
    },
    error(e) {
      console.error(e.detail);
      common_vendor.index.showToast({
        title: "相机启动失败，请检查权限设置",
        icon: "none"
      });
    },
    playAiSpeaking() {
      if (this.useVideo && this.aiVideoContext) {
        this.aiVideoContext.play();
      }
      if (this.digitalHumanUrl) {
        const speakText = this.currentQuestion ? this.currentQuestion.text : "";
        this.interactWithDigitalHuman(speakText);
      }
    },
    pauseAiSpeaking() {
      if (this.useVideo && this.aiVideoContext) {
        this.aiVideoContext.pause();
      }
    },
    // 重新开始测试
    restartTest() {
      this.currentQuestionIndex = 0;
      this.score = 0;
      this.showEndModal = false;
      this.showResult = false;
      this.selectedOption = null;
      this.selectedOptions = [];
      this.resetTimer();
    },
    // 在methods中添加测试方法
    testEndScreen() {
      this.interviewCompleted = true;
      this.showEndModal = false;
    },
    // 初始化数字人
    initDigitalHuman() {
      this.digitalHumanUrl = "";
    },
    // 与数字人交互的方法
    interactWithDigitalHuman(message) {
      const webview = this.$mp.page.$getAppWebview().children()[0];
      if (webview) {
        webview.evalJS(`receiveMessage('${message}')`);
      }
    }
  },
  // 添加生命周期钩子，确保在组件销毁时清除计时器
  beforeDestroy() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
  }
};
if (!Array) {
  const _component_uni_load_more = common_vendor.resolveComponent("uni-load-more");
  _component_uni_load_more();
}
function _sfc_render(_ctx, _cache, $props, $setup, $data, $options) {
  return common_vendor.e({
    a: $data.digitalHumanUrl
  }, $data.digitalHumanUrl ? {
    b: $data.digitalHumanUrl
  } : {
    c: common_assets._imports_0
  }, {
    d: common_vendor.t($data.currentQuestionIndex + 1),
    e: common_vendor.t($options.currentQuestion.id),
    f: common_vendor.t($data.questions.length),
    g: $options.currentQuestion.isImportant
  }, $options.currentQuestion.isImportant ? {} : {}, {
    h: common_vendor.t($options.currentQuestion.questionTypeName),
    i: common_vendor.t($options.currentQuestion.text),
    j: $options.currentQuestion.questionType == 0
  }, $options.currentQuestion.questionType == 0 ? {
    k: $data.openQuestionAnswer,
    l: common_vendor.o(($event) => $data.openQuestionAnswer = $event.detail.value),
    m: common_vendor.t($data.openQuestionAnswer.length)
  } : {
    n: common_vendor.f($options.currentQuestion.options, (option, index, i0) => {
      return {
        a: common_vendor.t(option.option_text || (typeof option === "string" ? option : JSON.stringify(option))),
        b: index,
        c: ($options.currentQuestion.questionType === 1 ? $data.selectedOption === index : $data.selectedOptions.includes(index)) ? 1 : "",
        d: $data.showResult && ($options.currentQuestion.questionType === 1 ? index === $options.currentQuestion.correctAnswer : $options.currentQuestion.correctAnswers.includes(index)) ? 1 : "",
        e: $data.showResult && ($options.currentQuestion.questionType === 1 ? $data.selectedOption === index && index !== $options.currentQuestion.correctAnswer : $data.selectedOptions.includes(index) && !$options.currentQuestion.correctAnswers.includes(index)) ? 1 : "",
        f: common_vendor.o(($event) => $options.selectOption(index), index)
      };
    }),
    o: common_vendor.t($options.currentQuestion.questionType === 1 ? "●" : "☐")
  }, {
    p: common_vendor.t($data.showResult ? "下一题" : "提交答案"),
    q: common_vendor.o(($event) => $options.nextQuestion(_ctx.option)),
    r: $options.currentQuestion.questionType === 0 && $data.openQuestionAnswer.trim() === "" || $options.currentQuestion.questionType === 1 && $data.selectedOption === null || $options.currentQuestion.questionType === 2 && $data.selectedOptions.length === 0,
    s: $data.showEndModal
  }, $data.showEndModal ? {
    t: common_vendor.o((...args) => $options.restartTest && $options.restartTest(...args)),
    v: common_vendor.o((...args) => $options.back && $options.back(...args))
  } : {}, {
    w: $data.interviewCompleted
  }, $data.interviewCompleted ? {
    x: common_assets._imports_0,
    y: common_vendor.o((...args) => $options.back && $options.back(...args))
  } : {}, {
    z: $data.loading
  }, $data.loading ? {
    A: common_vendor.p({
      status: "loading",
      contentText: {
        contentdown: "加载中..."
      }
    })
  } : {}, {
    B: !$data.loading && $data.loadError
  }, !$data.loading && $data.loadError ? {
    C: common_vendor.o((...args) => $options.fetchInterviewData && $options.fetchInterviewData(...args))
  } : {});
}
const MiniProgramPage = /* @__PURE__ */ common_vendor._export_sfc(_sfc_main, [["render", _sfc_render]]);
wx.createPage(MiniProgramPage);
