<template>
  <div class="practice_answer">
    <el-container style="height: 100%">
      <el-aside width="260px" class="hide_scrollbar">
        <div class="side_list">
          <div class="side_title">待练习知识点</div>
          <div
            :class="['side_item', { active: item.exerciseId == exerciseId }]"
            v-for="item in waitList"
            :key="item.exerciseId"
            @click="ChangeKnowledge(item)"
          >
            <div class="item_name">
              {{ item.knowledgeName }}
            </div>
            <div class="item_content">
              <div class="content_left">
                <div class="content_type">
                  {{ item.exerciseType == 1 ? "自主练习" : "指定练习" }}
                </div>
                <div class="content_num">
                  题量：{{ item?.questionNum || "0" }}
                </div>
              </div>
              <div class="ai_explain" @click="OpenAi(item)">
                <img class="ai_icon" src="@/assets/icon_ai.png" />
                <span>AI讲解</span>
              </div>
            </div>
          </div>
        </div>
      </el-aside>
      <el-main class="main_body">
        <div class="content_main">
          <div class="content_title">
            <div class="title_name">{{ knowledgeName }}</div>
            <div class="button">
              <el-button plain class="download_btn" @click="downloadPaper"
                >下载试卷</el-button
              >
              <el-button type="primary" @click="SubmitAnswer">提交作答</el-button>
            </div>
          </div>
          <div class="question_list">
            <div
              class="question_item"
              v-for="(item, index) in questionList"
              :key="item.questionId"
            >
              <QuestionItem :index="index + 1" :question="item"></QuestionItem>
              <!-- 客观题->选择、判断。主观题->上传图片 -->
              <!-- isObjective 是否客观题 1是 0否  isJudge 是否判断题 1是 0否 -->
              <div
                :class="[
                  'question_footer',
                  { img_list: Number(item.isObjective) === 0 },
                ]"
              >
                <span class="footer_title">我的作答：</span>
                <div
                  v-if="Number(item.isObjective) === 1"
                  class="upload_answer"
                >
                  <!-- 判断题 -->
                  <el-radio-group
                    class="radio_group"
                    v-if="Number(item.isJudge) === 1"
                    v-model="item.studentAnswer"
                    @input="HandleJudgeChange(item)"
                  >
                    <el-radio label="√">√</el-radio>
                    <el-radio label="×">×</el-radio>
                  </el-radio-group>
                  <!-- 选择题 -->
                  <el-checkbox-group
                    class="checkbox_group"
                    v-else
                    v-model="item.studentAnswer"
                    @change="HandleCheckChange(item)"
                  >
                    <el-checkbox
                      v-for="num in item.optionsNum"
                      :key="num"
                      :label="optionsData[num - 1]"
                    ></el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-else class="upload_answer">
                  <el-upload
                    class="img_uploader"
                    list-type="picture-card"
                    :show-file-list="false"
                    :headers="{'Authorization': getToken}"
                    :action="uploadUrl"
                    accept="image/*"
                    multiple
                    :limit="10"
                    :on-exceed="HandleExceed"
                    :on-success="(response, file, fileList)=>HandleUploadSuccess(response, file, fileList,item)"
                  >
                    <el-button slot="default" class="upload_btn" plain
                      >拍照/上传答案</el-button
                    >
                  </el-upload>
                  <div
                    class="upload_list_item"
                    v-for="(url, index) in item.studentAnswer"
                    :key="index"
                    @click="HandlePictureCardPreview(url)"
                  >
                    <img :src="url" />
                    <i
                      @click.stop="HandleRemove(item.studentAnswer,index)"
                      class="el-icon-error upload_list_item_delete"
                    ></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
    <div class="page_dialog">
      <el-dialog :visible.sync="dialogVisible">
        <div class="dialog_center padding_20">
          <div class="dialog_img">
            <img style="max-width: 100%" :src="dialogImageUrl" />
          </div>
        </div>
      </el-dialog>
      <el-dialog
        title="下载试卷"
        width="360px"
        :visible.sync="dialogPaperVisible"
      >
        <div class="dialog_center padding_20">
          <div class="dialog_paper">
            <div class="dialog_paper_item">
              <span class="dialog_paper_title">试卷名称：</span>
              <el-radio-group class="radio_group" v-model="radio">
                <el-radio :label="3">A4</el-radio>
                <el-radio :label="6">A3</el-radio>
              </el-radio-group>
            </div>
            <div class="dialog_paper_item">
              <span class="dialog_paper_title">下载格式：</span>
              <el-radio-group class="radio_group" v-model="radio">
                <el-radio :label="3">PDF</el-radio>
                <el-radio :label="6">Word</el-radio>
              </el-radio-group>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogPaperVisible = false">取 消</el-button>
          <el-button type="primary" @click="ConfirmDownloadPaper"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import QuestionItem from "@/views/targetImprove/components/QuestionItem.vue"; //题目公共组件
import { getToken } from "@/utils/auth";
import base from '@/http/common/base.js';
import { mapState } from "vuex";
export default {
  components: {
    QuestionItem,
  },
  computed: {
    ...mapState("target", ["subjectCode", "levelCode","subjectName"]),
  },
  inject: ['openAiRobot'],//注入Ai机器人组件调用方法
  data() {
    return {
      waitList: [], //待练习知识点
      exerciseId: "", // 练习id
      knowledgeName: "", //知识点名称
      questionList: [],
      optionsData: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      getToken: getToken(),
      uploadUrl: '',//上传图片地址
      dialogImageUrl: "", //图片预览
      dialogVisible: false, //图片预览
      dialogPaperVisible: false, //下载试卷
      radio: 3, //下载试卷
    };
  },
  watch: {},
  mounted() {
    this.GetUploadUrl();
    this.GetStudentTargeWaitExercise();
  },
  methods: {
    //获取上传图片地址
    GetUploadUrl(){
      this.uploadUrl = `${base.prefix}/api/v1/student_upload/oss/upload_filesSele`;
    },

    //打开AI解读
    OpenAi(item)
    {
      console.log("打开AI解读",item);
      console.log("this.subjectName",this.subjectName);

      let content = "科目："+this.subjectName+",知识点："+item.knowledgeName;
      this.openAiRobot(content);
    },

    //待练习知识点
    GetStudentTargeWaitExercise() {
      this.$api.target
        .studentTargeWaitExercise({
          levelCode: this.levelCode, // 学段code
          subjectCode: this.subjectCode, //学科code
        })
        .then((res) => {
          if (res.code == 200) {
            this.waitList = res?.data || [];
            if (this.waitList.length > 0) {
              this.exerciseId = this.waitList?.[0]?.exerciseId || "";
              this.knowledgeName = this.waitList?.[0]?.knowledgeName || "";
              this.GetStudentTargeExerciseQuestion();
            }
          }
        });
    },
    // 查询试题列表（type 1待练习的列表 2已练习的列表）
    GetStudentTargeExerciseQuestion() {
      this.$api.target
        .studentTargeExerciseQuestion({
          exerciseId: this.exerciseId, // 练习id
          type: 1, // 1待练习的列表 2已练习的列表
        })
        .then((res) => {
          if (res.code == 200) {
            // 客观题->选择、判断。主观题->上传图片
            // isObjective 是否客观题 1是 0否  isJudge 是否判断题 1是 0否
            const questionList = res?.data || [];
            questionList.forEach((item) => {
              if (Number(item.isObjective) === 1) {
                //客观题
                let studentAnswer = "";
                if (Number(item.isJudge) === 1) {
                  //判断题
                  studentAnswer = item.studentAnswer || "";
                } else {
                  //选择题
                  studentAnswer = item.studentAnswer ? (item?.studentAnswer?.split('') || []) : [];
                }
                item.studentAnswer = studentAnswer;
              } else {
                item.studentAnswer = item.studentAnswer ? (item?.studentAnswer?.split(',') || []) : [];
              }
            });
            this.questionList = questionList;
          } else {
            this.questionList = [];
          }
        });
    },
    //切换知识点
    ChangeKnowledge(item) {
      if (this.exerciseId == item.exerciseId) {
        return;
      }
      this.exerciseId = item.exerciseId || "";
      this.knowledgeName = item.knowledgeName || "";
      this.GetStudentTargeExerciseQuestion();
    },
    //判断题改变
    HandleJudgeChange(item) {
      item.studentAnswer = item.studentAnswer || "";
      this.SubmitQuestionAnswering(item.exerciseQueId,item.studentAnswer);
    },
    //选择题改变
    HandleCheckChange(item) {
      item.studentAnswer = item.studentAnswer || [];
      const studentAnswer = item?.studentAnswer?.join('') || '';
      this.SubmitQuestionAnswering(item.exerciseQueId,studentAnswer);
    },
    // 超出最大数量触发
    HandleExceed(files, fileList) {
      this.$message.warning(`最多只能上传10张图片`)
    },
    //上传图片成功
    HandleUploadSuccess(res, file, fileList,item){
      if(res.code == 200){
        const url = res?.data?.url || '';
        item.studentAnswer.push(url);
        const studentAnswer = item?.studentAnswer?.join(',') || '';
        this.SubmitQuestionAnswering(item.exerciseQueId,studentAnswer);
      }
    },
    //删除图片
    HandleRemove(studentAnswer,index) {
      studentAnswer.splice(index, 1);
    },
    //提交答案
    SubmitQuestionAnswering(exerciseQueId,stuAnswer) {
      this.$api.target.studentTargeQuestionAnswering({
        exerciseQueId: exerciseQueId, // 练习试题id	
        stuAnswer: stuAnswer, // 学生答案
      }).then((res) => {
        if (res.code == 200) {
          // this.$message.success('提交成功');
        }  
      });
    },
    //提交作答
    SubmitAnswer(){
      console.log(this.questionList)
      const studentAnswers = this.questionList.map(item=>item.studentAnswer);
      const hasInvalid = studentAnswers.some(item => {
        // 判断 null 或 undefined
        if (item == null) return true;
        // 判断空字符串
        if (item === '') return true;
        // 判断空数组
        if (Array.isArray(item) && item.length === 0) return true;
        return false;
      });
      if (hasInvalid) {
        this.$message.warning('不能提交空答案');
        return;
      }
      this.$api.target.studentTargeSubmitExercise({
        exerciseId: this.exerciseId, // 练习id
      }).then((res) => {
        if (res.code == 200) {
          this.$message.success('提交成功');
          this.GetStudentTargeWaitExercise();//获取待练习知识点
        }  
      });
    },
    //图片预览
    HandlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    //下载试卷
    downloadPaper() {
      this.dialogPaperVisible = true;
    },
    //确定下载
    ConfirmDownloadPaper() {
      this.dialogPaperVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.practice_answer {
  flex: 1;
  width: 100%;
  overflow: hidden;

  .side_list {
    width: 100%;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    border-radius: 10px;
    padding: 16px 10px 14px;
    box-sizing: border-box;

    .side_title {
      font-weight: 500;
      font-size: 16px;
      color: #333333;
    }

    .side_item {
      margin-top: 16px;
      background-color: #ffffff;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      width: 100%;
      padding: 10px;
      box-sizing: border-box;
      cursor: pointer;

      &.active {
        background: rgba(46, 100, 250, 0.1);
        border: 1px solid #2e64fa;
      }

      .item_name {
        width: 100%;
        font-weight: 500;
        font-size: 14px;
        color: #333333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .item_content {
        width: 100%;
        display: flex;
        justify-content: space-between;
        margin-top: 10px;

        .content_left {
          flex: 1;
          display: flex;
          font-weight: 400;
          font-size: 12px;
          color: #999999;

          .content_type {
            flex-shrink: 0;
            margin-right: 10px;
          }

          .content_num {
            flex-shrink: 0;
          }
        }

        .ai_explain {
          flex-shrink: 0;
          display: flex;
          align-items: center;

          .ai_icon {
            width: 14px;
            height: 14px;
            margin-right: 4px;
          }

          span {
            font-weight: 400;
            font-size: 14px;
            color: #4f3eff;
          }
        }
      }
    }
  }

  .main_body {
    padding: 0 0 0 10px;
    overflow: hidden;

    .content_main {
      width: 100%;
      height: 100%;
      padding: 20px 0;
      display: flex;
      flex-direction: column;
      box-sizing: border-box;
      background-color: #ffffff;
      border-radius: 10px;

      .content_title {
        display: flex;
        width: 100%;
        padding: 0 20px 20px;
        box-sizing: border-box;
        justify-content: space-between;
        align-items: center;

        .title_name {
          font-weight: 500;
          font-size: 16px;
          color: #333333;
          flex: 1;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-right: 10px;
        }

        .button {
          display: flex;

          :deep(.el-button) {
            padding: 10px 20px;
          }

          .download_btn {
            color: #666666;

            &:hover {
              border-color: #dcdfe6;
            }

            &:focus {
              border-color: #dcdfe6;
            }
          }
        }
      }

      .question_list {
        display: flex;
        flex-direction: column;
        width: 100%;
        padding: 0 20px;
        overflow: auto;
        box-sizing: border-box;
        flex: 1;

        .question_item {
          background: #ffffff;
          border-radius: 10px 10px 10px 10px;
          border: 1px solid #dcdfe6;

          :deep(.question_preview) {
            padding: 16px;
            box-sizing: border-box;
          }

          &:first-child {
            margin-top: 0;
          }

          margin-top: 20px;

          .question_footer {
            padding: 20px 16px;
            background-color: #f8f8f9;
            border-top: 1px solid #dcdfe6;
            display: flex;

            // align-items: center;
            &.img_list {
              padding: 16px;

              .footer_title {
                line-height: 48px;
              }
            }

            .footer_title {
              font-weight: 500;
              font-size: 14px;
              color: #333333;
              line-height: 24px;
            }

            .upload_answer {
              flex: 1;
              display: flex;
              flex-wrap: wrap;

              .img_uploader {
                // display: flex;
                // flex-direction: row-reverse;
                // justify-content: flex-end;
                // align-items: center;
                :deep(.el-upload-list--picture-card) {
                  .el-upload-list__item {
                    width: 64px;
                    height: 48px;
                    margin: 0 20px 8px 0;
                    background-color: #f0f4f8;
                    border-radius: 2px 2px 2px 2px;
                    border: 1px solid #ebeef5;
                  }
                }

                :deep(.el-upload--picture-card) {
                  background-color: transparent;
                  border: 0;
                  height: 48px;
                  width: auto;
                  line-height: 48px;
                  border-radius: 0;
                  margin-right: 22px;
                }

                .upload_btn {
                  border: 1px solid #2e64fa;
                  font-weight: 400;
                  font-size: 14px;
                  color: #2e64fa;
                  padding: 9px 15px;
                }
              }

              .upload_list_item {
                width: 64px;
                height: 48px;
                margin: 0 20px 8px 0;
                background-color: #f0f4f8;
                border-radius: 2px 2px 2px 2px;
                border: 1px solid #ebeef5;
                box-sizing: border-box;
                overflow: hidden;
                position: relative;
                cursor: pointer;

                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }

                .upload_list_item_delete {
                  position: absolute;
                  top: 3px;
                  right: 3px;
                  font-size: 16px;
                  cursor: pointer;
                  color: rgba(0, 0, 0, 0.5);
                }
              }
            }

            .radio_group {
              :deep(.el-radio) {
                line-height: 24px;
                font-weight: 400;
                font-size: 14px;
                color: #333333;
                margin-right: 20px;

                .el-radio__input {
                  &.is-checked + .el-radio__label {
                    color: #333333;
                  }

                  &.is-checked .el-radio__inner {
                    border-color: #2e64fa;
                    background-color: #ffff;
                  }

                  .el-radio__inner {
                    width: 16px;
                    height: 16px;
                    border-color: rgba(0, 0, 0, 0.2);

                    &::after {
                      width: 10px;
                      height: 10px;
                      background-color: #2e64fa;
                    }
                  }
                }

                .el-radio__label {
                  padding-left: 4px;
                }
              }
            }

            .checkbox_group {
              //多选
              :deep(.el-checkbox) {
                line-height: 24px;
                font-weight: 400;
                font-size: 14px;
                color: #333333;
                margin-right: 20px;

                .is-checked + .el-checkbox__label {
                  color: #333333;
                }

                .is-checked .el-checkbox__inner {
                  border-color: #2e64fa;
                }

                .el-checkbox__input {
                  .el-checkbox__inner {
                    width: 16px;
                    height: 16px;
                    border-color: rgba(0, 0, 0, 0.2);

                    &::after {
                      left: 5px;
                    }
                  }
                }

                .el-checkbox__label {
                  padding-left: 4px;
                  line-height: 24px;
                }
              }
            }
          }
        }
      }
    }
  }
}

.dialog_img {
  height: 70vh;
  text-align: center;
  overflow: auto;
}

.dialog_paper {
  padding: 8px 4px;
  display: flex;
  flex-direction: column;
  gap: 20px;

  .dialog_paper_item {
    height: 36px;
    display: flex;
    align-items: center;

    .dialog_paper_title {
      font-weight: 400;
      font-size: 14px;
      color: #303133;
      margin-right: 10px;
    }

    .radio_group {
      :deep(.el-radio) {
        line-height: 24px;
        font-weight: 400;
        font-size: 14px;
        color: #333333;
        margin-right: 40px;

        .el-radio__input {
          &.is-checked + .el-radio__label {
            color: #333333;
          }

          &.is-checked .el-radio__inner {
            border-color: #2e64fa;
            background-color: #ffff;
          }

          .el-radio__inner {
            width: 16px;
            height: 16px;
            border-color: rgba(0, 0, 0, 0.2);

            &::after {
              width: 10px;
              height: 10px;
              background-color: #2e64fa;
            }
          }
        }

        .el-radio__label {
          padding-left: 4px;
        }
      }
    }
  }
}
</style>
