<template>
  <div class="app-container">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>选择问卷开始答题</span>
        <el-button style="float: right;" type="text" @click="handleBack">返回</el-button>
      </div>
      
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="选择问卷" prop="questionnaireId">
          <el-select v-model="form.questionnaireId" placeholder="请选择要答题的问卷" style="width: 100%;" filterable>
            <el-option
              v-for="questionnaire in questionnaireList"
              :key="questionnaire.questionnaireId"
              :label="questionnaire.questionnaireName"
              :value="questionnaire.questionnaireId">
              <span style="float: left">{{ questionnaire.questionnaireName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ questionnaire.itemCount || 0 }}题</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="答题人姓名" prop="respondentName">
          <el-input v-model="form.respondentName" placeholder="请输入答题人姓名（可选）" style="width: 100%;" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">开始答题</el-button>
          <el-button @click="handleBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { startQuestionnaireAnswer } from "@/api/psychology/questionnaireAnswer";
import { listQuestionnaire } from "@/api/psychology/questionnaire";

export default {
  name: "QuestionnaireStart",
  data() {
    return {
      loading: false,
      questionnaireList: [],
      form: {
        questionnaireId: undefined,
        respondentName: undefined
      },
      rules: {
        questionnaireId: [
          { required: true, message: "请选择问卷", trigger: "change" }
        ]
      }
    };
  },
  created() {
    // 检查URL参数中是否有questionnaireId
    const questionnaireId = this.$route.query.questionnaireId;
    if (questionnaireId) {
      this.form.questionnaireId = parseInt(questionnaireId);
      // 如果已经选择了问卷，直接开始答题（不需要填写姓名）
      this.$nextTick(() => {
        this.startAnswerDirectly();
      });
    } else {
      this.loadQuestionnaires();
    }
  },
  methods: {
    /** 加载问卷列表 */
    loadQuestionnaires() {
      listQuestionnaire({ status: '0' }).then(response => {
        this.questionnaireList = response.rows.filter(q => q.itemCount > 0);
      }).catch(error => {
        console.error("加载问卷列表失败:", error);
        this.$message.error('加载问卷列表失败，请稍后重试');
      });
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          const data = {
            questionnaireId: this.form.questionnaireId,
            respondentName: this.form.respondentName || null
          };
          
          startQuestionnaireAnswer(data).then(response => {
            if (response.code === 200) {
              this.$modal.msgSuccess("答题已开始");
              const answerId = response.data;
              this.$router.push({ path: '/psychology/questionnaire/taking', query: { answerId: answerId } });
            }
            this.loading = false;
          }).catch(error => {
            console.error('Failed to start questionnaire answer:', error);
            this.$modal.msgError("开始答题失败，请重试");
            this.loading = false;
          });
        }
      });
    },
    /** 直接开始答题（从测评开始页面跳转过来时使用） */
    startAnswerDirectly() {
      if (!this.form.questionnaireId) {
        this.$modal.msgError("问卷ID不能为空");
        // 根据用户角色跳转到相应页面
        const roles = this.$store.getters.roles || [];
        const isStudent = roles.some(role => role === 'student' || role.includes('学员'));
        this.$router.push(isStudent ? '/student/tests' : '/psychology/scale');
        return;
      }
      
      this.loading = true;
      const data = {
        questionnaireId: this.form.questionnaireId,
        respondentName: null // 不填写姓名
      };
      
      startQuestionnaireAnswer(data).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("答题已开始");
          const answerId = response.data;
          this.$router.push({ path: '/psychology/questionnaire/taking', query: { answerId: answerId } });
        }
        this.loading = false;
      }).catch(error => {
        console.error('Failed to start questionnaire answer:', error);
        this.$modal.msgError("开始答题失败，请重试");
        this.loading = false;
      });
    },
    /** 返回 */
    handleBack() {
      // 根据用户角色跳转到相应页面
      const roles = this.$store.getters.roles || [];
      const isStudent = roles.some(role => role === 'student' || role.includes('学员'));
      this.$router.push(isStudent ? '/student/tests' : '/psychology/scale');
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>

