<template>
  <div class="answer_main" id="title">
    <div class="">
      <!-- 大题 -->
      <div style="display: flex; justify-content: flex-start">
        <div>{{ currentQuestion.seq || 1 }}、</div>
        <div class="answer_main_title" style="flex: 1" v-html="currentQuestion.title"></div>
      </div>
      <!-- 小题 -->
      <div style="padding-left: 50px" v-if="currentQuestion.subQuestions">
        <div style="margin-bottom: 15px" v-for="(subItem, ix) in currentQuestion.subQuestions" :key="ix">
          <div v-html="ix + 1 + '、' + subItem.title"></div>
          <template v-if="subItem.options&&subItem.options.length">
            <div style="margin-top: 20px">
              <div v-for="(itemOpt, idx) in subItem.options" :key="idx">
                <div style="margin-bottom: 15px" v-html="selectOpt[idx] + ' 、 ' + itemOpt"></div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </div>
    <div>
      <template v-if="currentQuestion.typeId == 1">
        <!--                <div style="padding-left: 50px;" v-for="(itemOpt, idx) in currentQuestion.options">-->
        <!--                  <div>{{selectOpt[idx] + ' 、 ' + itemOpt}}</div>-->
        <!--                </div>-->
        <div style="margin-top: 20px">
          <div v-for="(itemOpt, idx) in currentQuestion.options" :key="idx">
            <el-radio style="margin-bottom: 15px" v-model="currentQuestion.answer" :label="selectOpt[idx]" border
              size="medium">{{ selectOpt[idx] + " 、 "
              }}<span style="white-space: normal" v-html="itemOpt"></span></el-radio>
          </div>
          <!--                  <el-radio v-model="radio2" label="1" border size="medium">备选项1</el-radio>-->
          <!--                  <el-radio v-model="radio2" label="2" border size="medium">备选项2</el-radio>-->
        </div>
      </template>
      <template v-if="currentQuestion.typeId == 3">
        <div style="margin-top: 20px" id="dati">
          <!-- 遍历客观题的答题项 -->
          <div v-for="(itemOpt, idx) in currentQuestion.options" :key="idx">
            <!-- todo 只在state为3和4的时候可以做题 -->
            <template v-if="true">
              <!-- 答题 -->
              <el-checkbox-group v-model="currentQuestion.answer" @change="changeCheckbox">
                <el-checkbox style="margin-bottom: 15px" :label="selectOpt[idx]" border size="medium">{{ selectOpt[idx] + ' 、 '
                }}<span style="white-space: normal" v-html="itemOpt"></span></el-checkbox>
              </el-checkbox-group>
            </template>
          </div>
        </div>
      </template>
      <template v-else-if="currentQuestion.typeId == 2">
        <div class="answer_main_btn">
          <el-button type="" @click="answerFunc(1)">手动答题</el-button>
          <el-button type="primary" @click="answerFunc(2)"><i class="el-icon-camera-solid"></i>拍照上传</el-button>
          <!--                <el-button type="primary" @click="answerFunc">解析</el-button>-->
          <!--                <el-button type="" @click="answerFunc">计分</el-button>-->
          <!--                <span class="font_color_brown">得分：6分</span>-->
        </div>
        <div class="upload_container" v-loading="loading">
          <template v-if="solvingType == 1">
            <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="currentQuestion.answer">
            </el-input>
          </template>
          <template v-if="solvingType == 2">
            <ul class="el-upload-list el-upload-list--picture-card">
              <li tabindex="0" class="el-upload-list__item is-ready el-list-enter-to"
                v-for="(img, index) in currentQuestion.cacheFiles" :key="index">
                <img :src="img" alt="" class="el-upload-list__item-thumbnail" />
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(img)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="deleteImg(index)"><i
                      class="el-icon-delete"></i></span>
                </span>
              </li>
            </ul>
            <label class="el-upload el-upload--picture-card"><i class="el-icon-plus"></i><input type="file" ref="upFile"
                name="file" accept="image/*" class="el-upload__input" @change="UploadImage" /></label>

            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </template>
        </div>
      </template>
      <div class="answer_footer_btn">
        <div>
          <el-button type="" class="color_green_b" @click="submitAnswer()">{{
            btnAnswerTitle
          }}</el-button>
        </div>
        <div v-if="subjectTime" class="ft_green">
          单题计时：{{ subjectTime }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    openWrongQuestion,
    openWrongSimilarQuestion,
    commitWrongQuestion,
  } from "@/api/webApi/front";
  import {
    uploadFile2OSS
  } from "@/api/webApi/common.js";
  import {
    formatDuration
  } from "@/utils/index";

  export default {
    // TODO: 和answer页面需要形成重用组件
    props: {
      questionId: {
        type: Number,
        default: 0,
      },
      simulateMode: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        loading: false,
        selectOpt: ["A", "B", "C", "D", "E", "F", "G"],
        currentQuestion: {},
        subjectTime: "-分-秒",
        solvingType: 2,
        imgFileList: [],
        dialogImageUrl: "",
        dialogVisible: false,
      };
    },
    watch: {
      "currentQuestion.title": function(value) {
        if (value) this.$nextTick(() => this.mxGlobal.MathQueue("title"));
      },
      solvingType: function(value) {
        if (value == 3) this.$nextTick(() => this.mxGlobal.MathQueue("parse"));
      },
    },
    created() {
      this.getQuestionById();
    },
    computed: {
      btnAnswerTitle() {
        return this.simulateMode ? "查看解析" : "提交答案";
      },
    },
    destroyed() {
      if (this.addTimer) clearInterval(this.addTimer);
      if (this.reduceTimer) clearInterval(this.reduceTimer);
    },
    methods: {
      getQuestionById() {
        if (!this.questionId) return;
        this.loading = true;
        const method = this.simulateMode ?
          openWrongSimilarQuestion :
          openWrongQuestion;
        const methodName = this.simulateMode ?
          "openWrongSimilarQuestion" :
          "openWrongQuestion";
        const params = {
          questionId: this.questionId
        };
        if (!this.simulateMode) params.isReview = false; // 不要返回答案
        method(params).then((rep) => {
          console.log(methodName + " rep=", rep);
          if (rep.code == 200 || rep.code == 0) {
            this.currentQuestion = rep.data || {};
            this.currentQuestion.seq = this.currentQuestion.seq || 1;
            this.currentQuestion.answerTime =
              this.currentQuestion.answerTime || 0;
            this.currentQuestion.cacheFiles = [];
            this.currentQuestion.answer = this.currentQuestion.typeId == 3 ? [] : ''
            this.timerFunc("add");
          } else {
            this.msgError(rep.msg || methodName + "请求异常");
          }
          this.loading = false;
        });
      },
      // 答题方式
      answerFunc(type) {
        this.solvingType = type;
      },
      submitAnswer() {
        // validate answer
        if (!this.currentQuestion.answer?.length && !this.currentQuestion.cacheFiles?.length) {
          this.msgError("请先完成作答");
          return;
        }
        clearInterval(this.addTimer);
        this.currentQuestion.duration = this.subjectTime;
        this.currentQuestion.attachments = this.currentQuestion.cacheFiles;
        if (this.simulateMode) {
          this.$emit("simulateCompleted", this.currentQuestion);
        } else {
          let formatAnswer = this.currentQuestion.answer
          if (Array.isArray(formatAnswer))
            formatAnswer = formatAnswer.sort().toString()
          const commitData = {
            questionId: this.currentQuestion.questionId,
            answer: formatAnswer,
            attachments: this.currentQuestion.cacheFiles,
            duration: this.currentQuestion.answerTime,
          };
          console.log("submitAnswer", commitData);

          const redoQuestion = {
            ...this.currentQuestion,
            ...commitData
          };
          commitWrongQuestion(commitData).then((rep) => {
            console.log("commitWrongQuestion rep=", rep);
            if (rep.code == 200 || rep.code == 0) {
              this.msgSuccess(rep.msg);
              this.$emit("redoCompleted", redoQuestion);
            } else {
              this.msgError(rep.msg);
            }
          });
        }
      },
      beforeAvatarUpload(file) {
        let imgType = [
          "image/jpeg",
          "image/JPEG",
          "image/jpg",
          "image/JPG",
          "image/png",
          "image/PNG",
          "image/bmp",
          "image/BMP",
        ];
        const isImg = -1 === imgType.indexOf(file.type) ? false : true;
        // const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isImg) {
          this.$message.error("上传文件只能是图片!");
        }
        // if (!isLt5M) {
        //   this.$message.error('上传图片大小不能超过 5MB!');
        // }
        // return isImg && isLt5M;
        return isImg;
      },
      deleteImg(index) {
        this.currentQuestion.cacheFiles.splice(index, 1);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file;
        this.dialogVisible = true;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      UploadImage(param) {
        if (!this.beforeAvatarUpload(param.target.files[0])) {
          return;
        }
        this.loading = true;
        const formData = new FormData();
        formData.append("file", param.target.files[0]);
        uploadFile2OSS(formData, 6)
          .then((response) => {
            this.currentQuestion.cacheFiles.push(response.msg);
            this.loading = false;
          })
          .catch((err) => {
            console.log(err);
          });
        this.$refs.upFile.value = "";
      },

      // 计时器
      timerFunc: function(type) {
        if ("reduce" == type) {
          // 倒计时
          if (this.timer > 0) {
            this.reduceTimer = setInterval(() => this.timerReduceFunc(), 1000);
            this.timerReduceFunc();
          } else {
            clearInterval(this.reduceTimer);
          }
        } else if ("add" == type) {
          // 计时
          this.addTimer = setInterval(() => this.timerAddFunc(), 1000);
          this.timerAddFunc();
        }
      },
      timerAddFunc: function() {
        this.subjectTime = formatDuration(this.currentQuestion.answerTime);
        this.currentQuestion.answerTime++;
      },
      timerReduceFunc: function() {
        if (this.timer <= 0) clearInterval(this.reduceTimer);
        --this.timer;
        this.countDown = formatDuration(this.timer);
      },
      changeCheckbox() {
        // let answer = []
        // this.selectOpt.forEach(item => {
        //   if (this.currentQuestion.answer.indexOf(item) > -1) {
        //     answer.push(item)
        //   }
        // })
        // this.currentQuestion.answer = answer //排序
        console.log(this.currentQuestion.answer)
      }
    },
  };
</script>
<style scoped lang="scss">
  .btn {
    background-color: #ffffff;
    border: 1px solid #dcdfe6;
    color: #606266;
    display: inline-block;
    cursor: pointer;
  }

  .font_color_brown {
    color: #d77616;
    font-size: 20px;
    margin-left: 10%;
  }

  .color_gblue {
    background-color: #CFDCD5;
    color: #ffffff;
  }

  .color_blue {
    background-color: #47C6A2;
    color: #ffffff;
  }

  .color_brown {
    background-color: #F77E67;
    color: #ffffff;
  }

  .color_gbrown {
    background-color: #fbd0a6;
    color: #ffffff;
  }

  .color_gray {
    background-color: #FFCBC1;
    color: #ffffff;
  }

  .answer_title {
    text-align: center;
    position: relative;

    img {
      width: 50px;
      height: 50px;
    }

    .answer_title_info {
      position: absolute;
      left: 10px;
      top: 10px;
      text-align: left;

      span {
        margin-right: 10px;
      }
    }

    .answer_title_name {
      font-size: 32px;
      font-weight: 500;
      margin: 5px 0 15px;
      padding-bottom: 10px;
      border-bottom: 1px solid #dbdbdb;
    }
  }

  .answer_main {
    .answer_main_title {
      margin-bottom: 30px;
      word-break: break-all;
      
      img {
        max-width: 100%;
      }
    }

    .answer_main_btn {
      margin: 10px 0;

      button {
        // margin-left: 20px;
      }

      .question_function_container {
        position: absolute;
        top: 0;
        right: 0;
        text-align: right;
        display: flex;

        .question_function_item {
          margin-left: 20px;
          padding: 5px 0;
          cursor: pointer;
          display: flex;

          span {
            display: flex;
            justify-content: center;
            align-items: center;
          }

          i,
          img {
            margin-right: 5px;
          }

          .question_function_image {
            width: 24px;
            font-size: 24px;
            color: orange;
          }
        }
      }
    }

    .upload_container {
      border: 1px solid #6cd1b5;
      padding: 10px;
      border-radius: 8px;
      min-height: 200px;
    }

    .answer_footer_btn {
      display: flex;
      justify-content: space-between;
      margin: 15px 0 30px;

      .color_green_a {
        border: 1px solid #6cd1b5;
        color: #6cd1b5;
      }

      .prev_btn {
        padding: 0;
        border: 1px solid #dcdfe6;
        border-radius: 50%;
        color: #333;
        width: 35px;
        height: 35px;
        line-height: 35px;
        text-align: center;
      }

      .next_btn {
        padding: 0;
        border: 1px solid #dcdfe6;
        border-radius: 50%;
        color: #333;
        width: 35px;
        height: 35px;
        line-height: 35px;
        text-align: center;
      }

      .color_green_b {
        border: 1px solid #6cd1b5;
        background-color: #6cd1b5;
        color: #ffffff;
      }
    }

    .ft_green {
      color: #6cd1b5;
      margin: 30px 0;
    }
  }

  .answer_card {
    border: 1px solid #dcdfe6;
    padding-bottom: 15px;

    .card_title {
      text-align: center;
      font-size: 20px;
      padding: 15px;
    }

    .card_btn_container {
      padding: 15px 0 15px 15px;

      .card_btn {
        position: relative;
        padding: 0;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        text-align: center;
        margin-right: 15px;
        margin-bottom: 15px;

        .ebtn_mblem {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 20px;
          height: 20px;
          line-height: 20px;
          text-align: center;
          font-size: 14px;
          background-color: red;
          color: #ffffff;
          border-radius: 50%;
        }
      }
    }

    .card_timer {
      padding: 25px;
      text-align: center;
      color: #fd0303;
    }

    .card_footer {
      display: flex;
      justify-content: space-around;
    }
  }
</style>
<style scoped>
  .el-radio.is-bordered.is-error {
    border-color: #f56c6c;
  }

  .el-radio.is-bordered.is-checked {
    border-color: #47C6A2;
  }

  /deep/ .el-radio__input.is-checked .el-radio__inner {
    border-color: #47C6A2;
    background: #47C6A2;
  }

  .el-radio.is-bordered.is-error /deep/ .el-radio__label {
    color: #f56c6c;
  }

  .el-radio.is-bordered.is-checked /deep/ .el-radio__label {
    color: #47C6A2;
  }

  .fenshu /deep/ .el-input__inner {
    width: 50%;
    line-height: 40px;
    border: none;
    background: #eee;
    color: #333;
    text-align: center;
  }

  .el-radio--medium.is-bordered {
    height: auto;
    padding-bottom: 8px;
  }

  .fenshu:focus-visible {
    outline: none;
  }

  /deep/ .el-textarea__inner {
    height: 180px;
  }

  /deep/ .el-dropdown-link {
    cursor: pointer;
    font-size: 16px;
    color: #333333;
  }

  /deep/ .el-icon-warning {
    font-size: 24px;
    color: #999999;
  }

  .el-checkbox.is-bordered.el-checkbox--medium {
    height: auto;
  }
</style>
