<template>
  <div class="account-container" v-loading="loading">
    <div class="top" style="margin-bottom: 40px">
      <div class="account-title">
        {{ $t('trainTarget.assessmentResults') }} :
        <el-tag size="small " v-if="isPass.flag" type="success" hit>{{ isPass.msg }}</el-tag>
        <el-tag size="small " v-else type="danger" hit>{{ isPass.msg }}</el-tag>
        <span style=" margin-left: 10px">
        {{ $t('trainTarget.assessmentScore') }} :
          <el-tag size="small " v-if="isPass.flag" type="success" hit>{{ isPass.myScore }}</el-tag>
        <el-tag size="small " v-else type="danger" hit>{{ isPass.myScore }}</el-tag>
        </span>
      </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>

        <el-form ref="form" :model="form" :rules="rules" label-position="top" style="margin: 0 0 0 200px">
          <el-form-item
            v-for="(item,index) in questionList" :key="index" prop="answer">
            <span slot="label">
              <span v-if="!item.flag" style="color:red;">{{index + 1 + '. ' + item.questionContext + '('+item.questionTypeName + ',' + $t('question.score') + item.score + $t('trainList.scoreUnit')+')'}}</span>
              <span v-else>{{index + 1 + '. ' + item.questionContext + '('+item.questionTypeName + ',' + $t('question.score') + item.score + $t('trainList.scoreUnit')+')'}}</span>
            </span>
            <!--            单选/判断--><!--v-model="demo['radio' + index]"-->
            <el-radio-group disabled v-if="item.questionType === '01' || item.questionType === '03'"
                            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 disabled 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 disabled v-else type="textarea" v-model="item.answer" style="width: 50%;"/>
            <div >
              <span style="font-weight: bold;">
                {{$t('trainTarget.correctAnswer')}} : {{ correctAnswerChoice(item) }}
              </span>
              <span style="font-weight: bold;margin-left: 10px">
                {{ $t('trainTarget.assessmentScore')}} : {{ item.getScore }}
              </span>
            </div>

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

<script>
import {getTestResult} 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: {

    isPass() {
      let myTotalScore = 0
      this.questionList.forEach(item => {
        myTotalScore += item.getScore
      })
      const result = myTotalScore >= this.assessmentPlanForm.passScore ? this.$t('trainTarget.pass') : this.$t('trainTarget.notPass')
      return {
        msg: result,
        flag: myTotalScore >= this.assessmentPlanForm.passScore,
        myScore: myTotalScore
      };
    },

    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'}]);
    //   });
    // },
    // 正确答案选项
    correctAnswerChoice(row){
      const letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
      if(row.questionType !== '04'){
        let choiceArray = []
        // 从选项列表中，得到正确答案的索引集合
        let indexes = this.optionListFiltered(row).map((item, index) => {
          const correctAnswers = row.correctAnswer.split(";");
          return correctAnswers.some(ans => ans === item) ? index : -1;
        }).filter(index => index !== -1);

        indexes.forEach(item =>{
          choiceArray.push(letters[item]);

        })
        return choiceArray.join(",")
      }else{
        return row.correctAnswer
      }

    },

    // 获取试卷及考核结果
    getList() {
      console.log("this.$route.query", this.$route.query.data.id)
      let trainId = this.$route.query.data.id
      if (!trainId) {
        return
      }
      let query = {
        id: trainId
      }
      // 根据培训id获取 试卷详细
      getTestResult(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') {
            if (question.answerContent) {
              let myAnswerArray = question.answerContent.split(";")
              myAnswerArray.sort((a, b) => {
                return question.correctAnswer.split(";").indexOf(a) - question.correctAnswer.split(";").indexOf(b)
              })
              return {
                ...question,
                answer: myAnswerArray,
                flag: myAnswerArray.join(";") === question.correctAnswer
              }
            } else {
              return {
                ...question,
                answer: [],
                flag: false
              }
            }
          }
          return {
            ...question,
            answer: question.answerContent,
            flag: question.correctAnswer === question.answerContent
          }
        })
      }).then(() => {
        // todo(等会做 表单校验)
        // this.initFormRules()
      })
      // 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;
    }

  }

}

</style>
