<template>
  <div class="account-container" v-loading="loading">
    <div class="top" style="margin: 0 170px 40px 170px">
      <div class="account-title">{{ this.$t('trainList.examInProgress') }}</div>
      <div class="button-group">
        <el-button type="primary" icon="el-icon-circle-check" @click="submitForm"
                   :loading="submitLoading">{{ $t('common.confirm') }}
        </el-button>
        <el-button @click="cancel" icon="el-icon-remove-outline">
          {{ $t('common.cancel') }}
        </el-button>
      </div>
    </div>
    <div class="content">
      <div class="card card-full">
        <div class="test-title">{{ assessmentPlanForm.testPaperName }}</div>
        <div class="form-container">
          <el-form ref="form" :model="form" :rules="rules" label-position="top" >

            <el-form-item
              :label="index + 1 + '. ' + item.questionContext + '('+item.questionTypeName + ',' + $t('question.score') + item.score + $t('trainList.scoreUnit')+')'"
              v-for="(item,index) in questionList" :key="index" prop="answer">
              <!--            单选/判断--><!--v-model="demo['radio' + index]"-->
              <el-radio-group v-if="item.questionType === '01' || item.questionType === '03'" v-removeAriaHidden
                              v-model="item.answer">
                <el-radio v-for="(option,optionIndex) in optionListFiltered(item)" :key="optionIndex" :label="option">
                  {{ letterFromIndex(optionIndex) }}. {{ option }}
                </el-radio>
              </el-radio-group>

              <!--            多选-->
              <el-checkbox-group v-else-if="item.questionType === '02'" v-model="item.answer">
                <el-checkbox v-for="(option,optionIndex) in optionListFiltered(item)" :key="optionIndex"
                             :label="option">
                  {{ letterFromIndex(optionIndex) }}. {{ option }}
                </el-checkbox>
              </el-checkbox-group>

              <!--            填空题-->
              <el-input v-else type="textarea" v-model="item.answer" maxlength="500" style="width: 100%;"/>

            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {getTestPaperDetail} from "@/api/train/train";
import {addAssessResult} from "@/api/train/assessResult";

export default {
  dicts: ['train_question_type', 'training_category', 'train_status', 'train_whether_to_assess'],
  data() {
    return {
      submitLoading: false,
      demo: {},

      loading: false,
      questionList: [],
      form: {},
      assessmentPlanForm: {
        testPaperName: '试卷模板'
      },
      // 校验规则
      rules: {},
      // 结果列表(1.testPaperDetailId,2.trainTargetId,3.answerContent,4.score)
      assessResult: [],
    };
  },
  created() {
    this.getList()
  },
// Vue实例中的computed属性
  computed: {

    letterFromIndex() {
      const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
      return (index) => {
        if (index >= 0 && index <= letters.length - 1) {
          return letters[index];
        } else {
          return '';
        }
      };
    }
  },
  methods: {
    // 初始化表单校验(废弃)
    // initFormRules() {
    //   this.questionList.forEach(item => {
    //     this.$set(this.rules, 'answer', [{required: true, message: '此项为必填项', trigger: 'blur'}]);
    //   });
    // },
    // 提交试卷
    async submitForm() {
      this.$modal.confirm(this.$t('trainList.isConfirmTest')).then(() => {
        this.$refs['form'].validate(async valid => {
          console.log(valid);
        })
        this.questionList.forEach(item => {
          let result
          // 如果为多选，则使用';' 分割数组作为答案
          if (item.questionType === '02') {
            let getScore = 0
            let correctAnswerArray = item.correctAnswer.split(";")
            // 如果数组长度相同 切填写答案包含所有正确答案，则获得分数，否则分数为0
            if (item.answer.length === correctAnswerArray.length && correctAnswerArray.every(ans => item.answer.includes(ans))) {
              getScore = item.score
            } else {
              getScore = 0;
            }
            result = {
              testPaperDetailId: item.id,
              answerContent: item.answer.join(";"),
              score: getScore
            }
          } else {
            result = {
              testPaperDetailId: item.id,
              answerContent: item.answer,
              score: item.correctAnswer === item.answer ? item.score : 0
            }
          }
          this.assessResult.push(result)
        })
        // 插入答卷
        let query = {
          passScore: this.assessmentPlanForm.passScore,
          trainId: this.assessmentPlanForm.trainId,
          ttAssessResults: this.assessResult
        }
        addAssessResult(query).then(() => {
          // this.$tab.closeOpenPage("/train/trainTarget/")
          this.$tab.closePage()
          this.$modal.msgSuccess(this.$t('trainList.assessResultConfirm'))
        })
      })

    },
    // 获取试卷
    getList() {
      let trainId = JSON.parse(this.$route.query.data).id
      if (!trainId) {
        return
      }
      let query = {
        id: trainId
      }
      // 根据培训id获取 试卷详细
      getTestPaperDetail(query).then(res => {
        console.log("response", res)
        this.assessmentPlanForm.testPaperName = res.data.testPaperName
        this.assessmentPlanForm.remark = res.data.remark
        this.assessmentPlanForm.passScore = res.data.passScore
        this.assessmentPlanForm.trainId = res.data.trainId
        this.questionList = res.data.ttTestPaperDetailVoList
        res.data.ttTestPaperDetailVoList.forEach(item => {
          item.questionTypeName = this.dict.label.train_question_type[item.questionType];
          item.score = parseInt(item.questionScore)
        })
        // 初始化，多选题答案属性为空数组
        this.questionList = this.questionList.map(question => {
          if (question.questionType === '02') {
            return {
              ...question,
              answer: []
            }
          }
          return {...question}
        })
      }).then(() => {

      })
      // this.questionList = []

    },
    // 预览返回
    cancel() {
      // this.$tab.closeOpenPage("/train/trainTarget/")
      this.$tab.closePage()
    },
    // 获取选项
    optionListFiltered: function (item) {
      const optionList = [];
      for (let i = 1; i <= 10; i++) {
        const option = item[`option${i}`];
        if (option !== null) {
          optionList.push(option);
        }
      }
      return optionList;
    }
  }
};
</script>

<style scoped>

.account-container {
  padding: 16px 1vw;

  .account-title {
    font-family: Arial, Arial;
    font-weight: bold;
    font-size: 18px;
    line-height: 21px;
  }

  .question-content {
    text-align: center; /* 水平居中 */
    display: flex;
    justify-content: center;
  }

  .test-title {
    display: flex;
    justify-content: center; /* 水平居中，也可以使用 text-align */
    align-items: center; /* 垂直居中 */
    font-size: 20px;
    height: 50px; /* 设置高度以确保垂直居中生效 */
  }

  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .button-group {
    display: flex;
  }

  .content {
    width: 100%;
    display: flex;

    & > div {
      align-self: stretch;
    }

    .card {
      background: #FFFFFF;
      box-shadow: 0px 2px 10px 0px #CED6DD;
      border-radius: 6px;
      padding: 20px;
      margin: 0 auto; /* 实现水平居中 */
      width: 60%; /* 设置元素宽度 */
    }

    .card-full {
      width: 80vw;
    }

  }

}

.form-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  padding: 50px 0 0 0;
}

</style>
