<template>
  <div class="exercise-answer">
    <div class="user-list">
      <span class="title">回答正确</span>
      <ul>
        <li
          v-for="{ user_id, user_image_url, user_real_name, answer_record_id } in answer_right_person_list"
          :key="user_id"
          :class="['user-item', { active: user_id === curUserId }]"
          @click="selectUser(user_id, answer_record_id)"
        >
          <el-avatar :size="24" :src="user_image_url" />
          <span>{{ user_real_name }}</span>
        </li>
      </ul>
      <span class="title">回答错误</span>
      <ul>
        <li
          v-for="{ user_id, user_image_url, user_real_name, answer_record_id } in answer_error_person_list"
          :key="user_id"
          :class="['user-item', { active: user_id === curUserId }]"
          @click="selectUser(user_id, answer_record_id)"
        >
          <el-avatar :size="24" :src="user_image_url" />
          <span>{{ user_real_name }}</span>
        </li>
      </ul>
    </div>

    <!-- 练习题题目 -->
    <div v-loading="loading" class="question-container">
      <div class="answer-wrapper">
        <header class="header">
          <div class="back round" @click="goBack">
            <i class="el-icon-arrow-left"></i>
            <span>返回</span>
          </div>
          <div v-if="is_objective" class="user-answer-info">
            <template v-if="user_answer.answer_status === 1">
              <span class="answer-status right"><SvgIcon :size="10" icon-class="check-mark" />回答正确</span>
            </template>
            <template v-else-if="user_answer.answer_status === 2">
              <span class="answer-status error"><SvgIcon :size="10" icon-class="cross" />回答错误</span>
            </template>
          </div>
          <div class="question-info">
            <el-popover :width="200" :disabled="true" trigger="click" popper-class="question-wrapper">
              <div slot="reference" :style="{ backgroundColor: '#E9E8EA' }" class="round question-index">
                <SvgIcon icon-class="list" />
                <span>{{ curQuestionIndex + 1 }} / {{ questionList.length }}</span>
                <span>{{ getExerciseName('cur') }}</span>
              </div>
            </el-popover>
          </div>
        </header>

        <main class="main">
          <template v-for="({ id }, i) in questionList">
            <component
              :is="curQuestionPage"
              v-if="i === curQuestionIndex"
              :key="id"
              ref="exercise"
              :data="currentQuestion"
            />
          </template>
        </main>

        <footer class="footer">
          <el-popover v-model="isPopover" placement="top-start" trigger="click">
            <!-- 教师填写批注 -->
            <div class="annotations-container">
              <div class="title">增加批注</div>
              <div v-if="currentQuestion.type === 'read'" class="read-score">
                <div v-for="(item, i) in remark.child_question_remark_list" :key="i">
                  <span>小题 {{ i + 1 }} 分数：</span>
                  <span v-if="isEnable(item?.is_objective)">得分 {{ item.score }}</span>
                  <el-input-number v-else v-model="item.score" :min="0" :max="item.score_question" :step="1" />
                </div>
              </div>
              <div v-else-if="!is_objective" class="score">
                <span>分数</span>
                <el-input-number
                  v-model="remark.score"
                  :min="0"
                  :max="question.score"
                  :step="question.score_type === scoreTypeList[0].value ? 1 : 0.1"
                />
              </div>
              <el-input v-model="remark.remark" type="textarea" rows="6" resize="none" class="remark" />
              <div>图片/视频</div>

              <el-upload action="no" accept="video/*,image/*" :show-file-list="false" :http-request="upload">
                <div class="upload">
                  <i class="el-icon-plus avatar-uploader-icon"></i>
                  <span>Upload</span>
                </div>
              </el-upload>
              <ul class="file-list">
                <li v-for="({ file_name, file_id }, i) in remark.file_list" :key="file_id" @click="removeFile(i)">
                  <span>{{ file_name }}</span>
                  <SvgIcon icon-class="delete" />
                </li>
              </ul>

              <div class="popover-footer">
                <el-button @click="isPopover = false">取消</el-button>
                <el-button type="primary" @click="fillQuestionAnswerRemark">确定</el-button>
              </div>
            </div>

            <div slot="reference" :class="['annotations', { has: isEnable(remark.is_remarked) && !isTeacher }]">
              <template v-if="isEnable(remark.is_remarked) && !isTeacher">
                <span>有一条教师批注</span>
              </template>
              <template v-else><i class="el-icon-plus"></i><span>批注</span></template>
            </div>
          </el-popover>
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
import {
  GetExerciseQuestionAnswerUserList,
  GetExerciseQuestionIndexList,
  GetQuestionInfo_AnswerRecord,
  FillQuestionAnswerRemark,
} from '@/api/exercise';
import { exerciseNames } from '@/views/exercise_questions/data/questionType';
import { scoreTypeList } from '@/views/exercise_questions/data/common';
import { fileUpload } from '@/api/app';

import PreviewQuestionTypeMixin from '@/views/exercise_questions/data/PreviewQuestionTypeMixin';

export default {
  name: 'ExerciseAnswerUserList',
  mixins: [PreviewQuestionTypeMixin],
  data() {
    const { share_record_id, question_id, exercise_id, search_exercise_id, question_type } = this.$route.query;

    return {
      share_record_id,
      question_id,
      exercise_id, // 练习id
      search_exercise_id, // 搜索练习id
      question_type, // 题目类型
      exerciseNames,
      scoreTypeList,
      isTeacher: this.$store.getters.isTeacher, // 是否是教师
      curUserId: '', // 当前用户id
      curAnswerRecordId: '', // 当前答题记录id
      answer_right_person_list: [],
      answer_error_person_list: [],
      questionList: [], // 题目列表
      curQuestionPage: '', // 当前问题页面
      curQuestionIndex: -1, // 当前题目索引
      currentQuestion: {}, // 当前题目
      is_objective: false, // 是否客观题
      remark: {
        is_remarked: 'false',
        score: 0,
        remark: '',
        remark_person_image_url: '',
        remark_person_name: '',
        remark_time: '',
        file_list: [],
        child_question_remark_list: [], // 子题批注列表
      }, // 批注
      question: {
        score: 1,
        score_item: 1,
        score_type: 'aggregate',
      }, // 题目信息
      // 用户答案
      user_answer: {
        answer_status: 0,
      },
      loading: false,
      user_answer_record_info: {}, // 当前用户的答题记录信息
      isPopover: false,
    };
  },
  watch: {
    curAnswerRecordId: {
      handler(val) {
        if (!val) return;
        this.getQuestionInfo_AnswerRecord();
      },
    },
  },
  created() {
    this.init();
    GetExerciseQuestionAnswerUserList({
      share_record_id: this.share_record_id,
      question_id: this.question_id,
    }).then(({ answer_right_person_list, answer_error_person_list }) => {
      this.answer_right_person_list = answer_right_person_list;
      this.answer_error_person_list = answer_error_person_list;
      if (answer_right_person_list.length > 0 || answer_error_person_list.length > 0) {
        const userList = answer_right_person_list.length > 0 ? answer_right_person_list : answer_error_person_list;
        this.selectUser(userList[0].user_id, userList[0].answer_record_id);
      }
    });
  },
  methods: {
    init() {
      this.getExerciseQuestionIndexList();
    },
    // 得到练习的题目索引列表
    getExerciseQuestionIndexList() {
      GetExerciseQuestionIndexList({ exercise_id: this.exercise_id }).then(({ index_list }) => {
        this.questionList = index_list.map((item) => ({
          ...item,
          isFill: true,
        }));
        this.curQuestionIndex = this.questionList.findIndex((item) => item.id === this.question_id);
      });
    },
    // 得到答题记录题目信息
    getQuestionInfo_AnswerRecord() {
      const type = this.question_type;
      let answer = {
        answer_list: [],
      };
      if (type === 'activity') {
        answer.answer_list.push({
          accessory_file_id_list: [],
        });
      }
      if (type === 'answer_question') {
        answer.answer_list.push({
          audio_file_id: '',
        });
      }
      if (type === 'read') {
        answer.question_list = [];
      }
      if (type === 'essay_question') {
        answer.answer_list.push({
          text: '',
        });
      }
      if (type !== 'read') {
        this.$refs.exercise?.[0].showAnswer(false, false, answer, true);
      }
      GetQuestionInfo_AnswerRecord({
        answer_record_id: this.curAnswerRecordId,
        question_id: this.question_id,
      }).then(({ question, user_answer: { is_fill_answer, content, is_objective, answer_status }, remark }) => {
        if (question.type === 'read') {
          let question_list = JSON.parse(question.content)?.question_list ?? [];
          let child_question_remark_list = question_list
            .map(({ id }) => {
              return remark.child_question_remark_list.find((item) => item.question_id === id);
            })
            .filter((item) => item);
          remark.child_question_remark_list = child_question_remark_list;
        }
        // 批注
        this.remark = remark;

        this.question = question;
        // 题目内容
        if (question.content) {
          this.currentQuestion = JSON.parse(question.content);
          if (!this.curQuestionPage) {
            this.curQuestionPage = this.previewComponents[this.question_type];
          }
        }
        this.is_objective = is_objective === 'true';
        this.user_answer.answer_status = answer_status;
        // 如果已经填写过答案，直接显示答案
        if (is_fill_answer === 'true') {
          this.$nextTick().then(() => {
            this.$refs.exercise?.[0].showAnswer(true, true, content.length > 0 ? JSON.parse(content) : null, true);
          });
        } else {
          this.$refs.exercise?.[0].showAnswer(false, false, answer, true);
        }
      });
    },
    upload(file) {
      fileUpload('Mid', file).then(({ file_info_list }) => {
        if (file_info_list.length > 0) {
          const { file_id, file_url, file_name } = file_info_list[0];
          this.remark.file_list.push({ file_id, file_url, file_name });
        }
      });
    },
    // 填写批注
    fillQuestionAnswerRemark() {
      FillQuestionAnswerRemark({
        answer_record_id: this.curAnswerRecordId,
        question_id: this.question_id,
        file_id_list: this.remark.file_list.map(({ file_id }) => file_id),
        child_question_remark_list: this.remark.child_question_remark_list,
        score: this.remark.score,
        remark: this.remark.remark,
      }).then(() => {
        this.$message.success('批注成功');
        this.isPopover = false;
      });
    },
    goBack() {
      this.$router.push({
        path: '/answer_data',
        query: { share_record_id: this.share_record_id, exercise_id: this.search_exercise_id },
      });
    },
    getExerciseName(type, question_type, additional_type) {
      if (this.questionList.length <= 0) return;
      if (type === 'cur') {
        if (this.curQuestionIndex < 0) return '';
        let { type: _type, additional_type: _additional_type } = this.questionList[this.curQuestionIndex];
        if (_type === 'select') {
          return _additional_type === 'single' ? '单选题' : '多选题';
        }
        return this.exerciseNames[_type];
      }

      if (type === 'list') {
        if (question_type === 'select') {
          return additional_type === 'single' ? '单选题' : '多选题';
        }
        return this.exerciseNames[question_type];
      }
    },
    selectUser(user_id, answer_record_id) {
      this.curUserId = user_id;
      this.curAnswerRecordId = answer_record_id;
    },
  },
};
</script>

<style lang="scss" scoped>
.exercise-answer {
  display: flex;
  height: 100%;

  .user-list {
    width: 200px;
    height: 100%;
    background-color: #fff;

    .title {
      padding: 8px 8px 0;
      font-size: 12px;
      color: #999;
    }

    ul {
      .user-item {
        display: flex;
        gap: 8px;
        align-items: center;
        padding: 8px;
        font-size: 14px;
        cursor: pointer;

        &.active {
          background-color: #e7eeff;
        }
      }
    }
  }

  .question-container {
    flex: 1;
    height: 100%;
    padding: 16px;
    background-color: #f9f8f9;

    .answer-wrapper {
      display: flex;
      flex-direction: column;
      row-gap: 16px;
      max-width: 1200px;
      min-height: 100%;
      padding: 16px;
      margin: 0 auto;
      background-color: #fff;
      border-radius: 24px;
      box-shadow: 0 6px 30px 5px #0000000d;

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 38px;
        font-size: 14px;

        .back {
          cursor: pointer;
        }

        .user-answer-info {
          .answer-status {
            display: flex;
            column-gap: 8px;
            align-items: center;
            padding: 8px 16px;
            color: #fff;
            border-radius: 40px;

            &.right {
              background-color: #3acb85;
            }

            &.error {
              background-color: #e65656;
            }
          }
        }

        .question-info {
          display: flex;
          column-gap: 12px;

          .question-index {
            cursor: pointer;
          }
        }
      }

      .main {
        flex: 1;
      }

      .footer {
        position: relative;
        display: flex;
        align-items: center;

        .annotations {
          display: flex;
          column-gap: 8px;
          align-items: center;
          padding: 7px 16px;
          font-size: 14px;
          cursor: pointer;
          background-color: $fill-color;
          border-radius: 20px;

          &.has {
            color: $danger-color;
            background-color: #ffece8;
          }
        }

        .el-button {
          padding: 9px 40px;
        }
      }
    }
  }
}
</style>

<style lang="scss">
.answer-container {
  padding: 0 !important;
}

.el-popover {
  display: flex;
  flex-direction: column;
  row-gap: 8px;
  padding: 8px 8px 14px;
  font-size: 14px;

  %read-score {
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    > div {
      display: flex;
      column-gap: 8px;
      align-items: center;
      color: #000;

      :first-child {
        color: #999;
      }

      .el-input-number {
        flex: 1;
      }
    }
  }

  .remark-container {
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    .remark-info {
      display: flex;
      column-gap: 8px;
      align-items: center;

      .remark-name {
        flex: 1;
      }

      .remark-time {
        font-size: 12px;
        color: #999;
      }
    }

    .file {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .el-image {
        width: 80px;
        height: 80px;
        background-color: #d9d9d9;
      }
    }

    .read-score {
      @extend %read-score;
    }
  }

  .annotations-container {
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    .title {
      color: #000;
    }

    .read-score {
      @extend %read-score;
    }

    .score {
      display: flex;
      column-gap: 8px;
      align-items: center;

      :first-child {
        color: #999;
      }
    }

    .remark {
      width: 350px;
    }

    .upload {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: space-around;
      width: 80px;
      height: 80px;
      padding: 8px;
      background-color: $fill-color;
      border: 1px solid $border-color;
    }

    .file-list {
      display: flex;
      flex-direction: column;
      row-gap: 4px;

      > li {
        display: flex;
        column-gap: 4px;

        :first-child {
          flex: 1;
        }

        :last-child {
          cursor: pointer;
        }
      }
    }

    .popover-footer {
      display: flex;
      justify-content: flex-end;
    }
  }
}

.question-wrapper {
  max-height: 60vh;
  padding: 8px;
  overflow: auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px 0 #00000040;

  .question-list {
    li {
      display: flex;
      column-gap: 8px;
      align-items: center;
      padding: 8px 16px;
      cursor: pointer;

      &.active {
        color: $main-color;
        background-color: #f4f8ff;
        border-radius: 2px;
      }
    }
  }
}
</style>
