<template>
  <div v-if="questionTotal === 0"></div>
  <div v-else>
    <div class="testinfo">
      <div class="title3" v-if="showNumberTitle">
        <span class="tops">第 {{currentQuestionPage + 1}} 题 </span>
      </div>

      <div>
        <div style="float: left; text-align: left; line-height: 40px; width: 50%">
          <h3>{{currentQuestion.questionType | getQuestionTypeName}} ({{currentQuestion.mark}}分)</h3>
        </div>
        <div style="float: right;line-height: 40px; width: 50%">
          <el-button @click="openAnswerFlag = true" type="primary" style="position: relative;  left: 348px;"
            round>答题卡</el-button>
        </div>
      </div>

      <div class="testbox">
        <label style="font-size: 20px;">{{currentQuestionPage + 1}}.</label>
        <div style="float: right; margin-left: 10px" v-html="currentQuestion.content"></div>
      </div>

      <el-dialog title="答题卡" :visible.sync="openAnswerFlag" width="30%">
        <template>
          <el-button v-for="(question, index) in questionAnswerDataList" :key="++index" size="medium"
            @click="selectQuestion(index)" circle>{{index}}</el-button>
        </template>
      </el-dialog>

      <!-- 试题选项 -->
      <el-row class="test-opt" style="padding-left: 20px;margin-top: 15px">
        <!-- 单选题 -->
        <template v-if="currentQuestion.questionType === 1">
          <el-radio-group v-for="(item, index) in currentQuestion.optionList" :key="index"
            v-model="currentQuestion.studentAnswer">
            <el-radio :label="item.label">{{item.label}}. &nbsp;
              <label v-html="item.option_name"></label>
            </el-radio>
          </el-radio-group>
        </template>

        <!-- 多选题 -->
        <template v-if="currentQuestion.questionType === 2">

          <el-checkbox-group v-for="(item, index) in currentQuestion.optionList" :key="index"
            v-model="currentQuestion.studentAnswer">
            <el-checkbox :label="item.label">{{item.label}}. &nbsp;
              <label v-html="item.option_name"></label>
            </el-checkbox>
          </el-checkbox-group>
        </template>

        <!-- 判断题 -->
        <template v-if="currentQuestion.questionType === 6">
          <el-radio v-model="currentQuestion.studentAnswer" label="1">对</el-radio>
          <el-radio v-model="currentQuestion.studentAnswer" label="0">错</el-radio>
        </template>
      </el-row>
    </div>

    <div class="btnbox">
      <el-button type="danger" @click="openWritingBoard" v-show="currentQuestion.questionType !== 1 && currentQuestion.questionType !== 2
           && currentQuestion.questionType !== 6" round>GPS-REN学习法测评
      </el-button>

      <el-button type="warning" v-if="currentQuestionPage !== 0" round @click="changeQuestionIndex(-1)">
        <i class="el-icon-arrow-left"></i>
        上一题
      </el-button>

      <el-button v-if="questionTotal > 1 && currentQuestionPage !== questionTotal - 1" type="warning"
        @click="changeQuestionIndex(1)" round>下一题 <i class="el-icon-arrow-right"></i></el-button>

      <!-- <el-button
        type="danger"
        class="btn"
        round
        @click="commitQuestion">{{commitButtonText}}
      </el-button> -->
    </div>

    <!--
    <div v-if="currentQuestion.questionType !==1 && currentQuestion.questionType !==2 && currentQuestion.questionType !==6">
      <div  style="width: 150px; margin-left: 30px;">
        <h3 class="el-icon-s-promotion" style="font-size: 20px; line-height:30px;color: #239676; float:left;font-weight: 500;">&nbsp;&nbsp;</h3>
        <h3  style="font-size: 20px;color: black;font-weight: 700;">你的答案</h3>
      </div>
      <div style="padding-left: 30px; padding-top: 30px">
        <template>
          <ul class="el-upload-list el-upload-list--picture-card" style="display: inline-block">
            <li v-for="(enclosure, index) in currentQuestion.studentAnswer" :key="index" class="el-upload-list__item is-success">
              <img :src="fileUrl + enclosure" alt="" class="el-upload-list__item-thumbnail">
              <label class="el-upload-list__item-status-label">
                <i class="el-icon-upload-success el-icon-check"></i>
              </label>
              <span class="el-upload-list__item-actions">
                   <span class="el-upload-list__item-preview"
                         @click="lookAnswerImg(fileUrl + enclosure)">
                         <i class="el-icon-zoom-in"></i>
                   </span>

                   <span  class="el-upload-list__item-delete"
                          @click="deleteAnswerImg(enclosure)">
                     <i class="el-icon-delete"></i>
                   </span>
               </span>
            </li>
            <el-dialog :visible.sync="dialogAnswerImgVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </ul>
        </template>

        <template>
          <el-upload
            :action="uploadAction"
            :headers="headers"
            :before-upload="beforeUploadAnswerImg"
            :on-success="uploadAnswerImgSuccess"
            list-type="picture-card"
            :show-file-list="false">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">答案附件上传(只能上传jpg/png文件，且不超过1M)</div>
          </el-upload>
        </template>
-->
    <template>
      <el-dialog :visible.sync="dialogVisible" fullscreen top="0" custom-class="GPSREN" :before-close="handleClose">

        <div slot="title" class="cust-title">
          GPS-REN学习法
        </div>

        <el-form :model="form" ref="form" label-width="100px" class="demo-ruleForm" label-position="top">

          <el-col :span="24">
            <el-form-item label="G（目标导向）:" class="cust-label">
              <div v-html="currentQuestion.content" style="font-weight: 100;font-size: 16px;"></div>
            </el-form-item>
          </el-col>

          <el-steps :active="active" finish-status="success" simple style="margin-top: 20px">
            <el-step>
              <div slot="title"
                style="border: #eee 1px solid;background-color: aliceblue;padding: 10px;border-radius: 10px;">
                <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                  <span>P</span>
                  <span>问题定义</span>
                </div>
              </div>
            </el-step>
            <el-step>
              <div slot="title"
                style="border: #eee 1px solid;background-color: aliceblue;padding: 10px;border-radius: 10px;">
                <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                  <span>S</span>
                  <span>系统拆解</span>
                </div>
              </div>
            </el-step>
            <el-step>
              <div slot="title"
                style="border: #eee 1px solid;background-color: aliceblue;padding: 10px;border-radius: 10px;">
                <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                  <span>R</span>
                  <span>结果整合</span>
                </div>
              </div>
            </el-step>
            <el-step>
              <div slot="title"
                style="border: #eee 1px solid;background-color: aliceblue;padding: 10px;border-radius: 10px;">
                <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                  <span>E</span>
                  <span>结果评估</span>
                </div>
              </div>
            </el-step>
            <el-step>
              <div slot="title"
                style="border: #eee 1px solid;background-color: aliceblue;padding: 10px;border-radius: 10px;">
                <div style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
                  <span>N</span>
                  <span>总结新知识</span>
                </div>
              </div>
            </el-step>
          </el-steps>
          <!-- <div>
            <el-button icon="el-icon-discover" size="small" type="success">AI助手</el-button>
          </div> -->
          <br />
          <el-col :span="24" v-if="active==0">
            <el-form-item class="cust-label">

              <el-input type="textarea" class="custom-height" v-model="form.p" placeholder="根据目标准确地描述问题。要求：
1.功能描述准确。问题需求描述与目标一致，无偏差或遗漏。
2.术语表达规范。正确使用数据结构与算法的专业术语，避免口语化表达，符合计算机学科表述规范。
3.上下文抽象。能剔除无关背景信息，保留与问题相关的关键上下文，对复杂问题进行抽象精炼表达。
4.接口定义清晰。输入/输出参数类型、范围、约束条件明确定义，函数/方法接口设计符合模块化原则。"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-else-if="active==1">
            <el-form-item class="cust-label">
              <el-input type="textarea" class="custom-height" v-model="form.s" placeholder="`对问题进行系统性的拆解。要求：
1.拆解维度合理。单一性问题按流程、复杂性问题按要素（如：结构、算法、边界、流程）、综合性问题按模块分层级。
2.逻辑结构完整。覆盖问题所有关键子问题（如DFS需包含递归终止条件、访问标记、回溯机制）。
3.颗粒度适中。 根据自身认知水平，已认知子问题不拆开，未认知的子问题要拆解为单一性问题。`"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-else-if="active==2">
            <el-form-item class="cust-label">
              <el-input type="textarea" class="custom-height" v-model="form.r" placeholder="`利用AI工具获取结果并整合。要求：
1.有效性。为最终可执行的代码。`"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-else-if="active==3">
            <el-form-item class="cust-label">
              <el-input type="textarea" class="custom-height" v-model="form.e" placeholder="`先设计评估的方法与标准。然后评估结果是否达成目标。若未达成，则可从步骤P或S进行迭代。要求:
1.评估方案合理。评估方案可执行。提供测试用例，对程序的约束条件、边界、接口进行充分的评估。
2.评估过程真实（否决项）。切实地开展评估，提交执行测试的实证材料。
3.评估结果达成度。根据目标评估结果的达成度。`"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-else-if="active==4">
            <el-form-item class="cust-label">
              <el-input type="textarea" class="custom-height" v-model="form.n" placeholder="`反思总结新知识。
1.关联性。总结的知识点与问题解决过程直接相关。
2.新增性。知识点相对于此前的学习过程，属于新增内容。
3.联结性。用已有的知识描述新知识，建立新旧知识的关联。
4.准确性。使用记录性的文字，准确地表达具体知识内容。`"></el-input>
            </el-form-item>
          </el-col>

        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button icon="el-icon-arrow-right" size="small" type="primary" plain v-if="active>0"
            @click="()=>{active--}">上一步</el-button>
          <el-button icon="el-icon-arrow-right" size="small" type="primary" plain v-if="active<4"
            @click="onNext">下一步</el-button>
          <el-button type="primary" @click="onNext" size="small" v-if="active==4">提交</el-button>
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        </span>
      </el-dialog>
    </template>

    <template>
      <el-dialog :visible.sync="dialogResultVisible" width="50%" top="0" custom-class="GPSREN"
        close-on-click-modal="false">
        <div slot="title" class="cust-title">
          AI评价 <i :class="aiTestClass"></i>
        </div>

        <div class="block">
          <el-timeline>
            <el-timeline-item v-for="(item,index) in aiTestItem" :timestamp="item.time" placement="top" :key="index">
              <el-card>
                <h3>{{ item.title }}</h3>
                <p style="color:blue;font-weight: bold;">{{item.process}}</p>
                <br>
                <p v-html="item.content"></p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>

        <span slot="footer" class="dialog-footer" v-if="aiTestClass=='el-icon-reading'">
          <el-button icon="el-icon-arrow-right" size="small" type="primary" plain v-if="active<4"
            @click="()=>{active++;dialogResultVisible = false;}">下一步</el-button>
          <!-- <el-button icon="el-icon-arrow-right" size="small" type="primary" plain v-else-if="active==4"
            @click="()=>{active++;dialogResultVisible = false;}">提交</el-button> -->
          <el-button type="primary" @click="()=>{dialogResultVisible = false;dialogVisible = false}" size="small"
            v-else-if="active==4">提交</el-button>
          <el-button @click="dialogResultVisible = false" size="small">修改</el-button>
          <el-button @click="()=>{dialogResultVisible = false; active=0;}" size="small">重新答题</el-button>
        </span>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import { getDictValueByType } from '../api/dict'

import { mockAI, steps } from '../mock/gpsren';
let thisPage = null

let stepMapToCnt = {}

export default {
  name: 'question-info',
  props: {
    // 试题及试题答案列表
    questionInfoAnswerList: {
      type: Array,
      default() {
        return []
      }
    },

    showNumberTitle: {
      type: Boolean,
      default: true
    },

    timeOutFlag: {
      type: Boolean,
      default: false
    },

    commitButtonText: {
      type: String,
      default: '提 交'
    }
  },

  watch: {
    questionInfoAnswerList(val) {
      this.questionAnswerDataList = val
      this.questionTotal = this.questionAnswerDataList.length
      this.currentQuestion = this.questionAnswerDataList[0]
      this.parserQuestion()
    },

    timeOutFlag(val) {
      if (val) {
        this.commitQuestion() // 时间结束自动提交试卷
      }
    }
  },

  data() {
    return {
      headers: {
        Authorization: this.$store.state.user.token,
        Platform: 'educationStudent'
      },
      id: '',
      openAnswerFlag: false,
      sumSource: 0,
      dialogImageUrl: '',
      questionTypeList: [],
      fileUrl: this.$store.state.common.fileHost,
      dialogAnswerImgVisible: false,
      uploadAction: this.$httpApi.httpUrl('/api/upload/2'),
      currentQuestion: {}, // 当前试题
      currentQuestionPage: 0,
      questionAnswerDataList: [], // 试题答案列表
      questionTotal: 0,
      dialogVisible: false,
      form: {
        r:`//根据用户输入的P问题定义，S系统拆解，自动生成代码
public void startMove() {
    int n = 3;
    char start = 'A';
    char auxiliary = 'B';
    char target = 'C';
    hanoi(n, start, auxiliary, target);
}

public void hanoi(int n, char start, char auxiliary, char target) {
    if (n == 1) {
        System.out.printf("Move disk %d from %c to %c%n", n, start, target);
        return;
    }
    hanoi(n - 1, start, target, auxiliary);
    System.out.printf("Move disk %d from %c to %c%n", n, start, target);
    hanoi(n - 1, auxiliary, start, target);
}`
      },
      config: {
        zIndex: 0
      },
      active: 0,
      dialogResultVisible: false,
      aiTestItem: [],
      aiTestClass: "el-icon-reading",
    }
  },

  beforeCreate() {
    thisPage = this
  },

  mounted() {
    getDictValueByType('question_type').then(response => {
      this.questionTypeList = response.data.data
    })
    this.questionAnswerDataList = this.questionInfoAnswerList
    if (this.questionAnswerDataList.length > 0) {
      this.currentQuestion = this.questionAnswerDataList[0]
    }
  },


  methods: {

    onNext() {
      //下一步，即时AI评价


      //弹出AI验证界面
      this.aiTestItem.length = 0
      this.dialogResultVisible = true
      this.aiTestClass = "el-icon-loading"
      let i = 0

      let step = steps[this.active]
      stepMapToCnt[step] = stepMapToCnt[step] || 0

      let run = () => {
        let st = setTimeout(() => {
          let ts = new Date().toLocaleString()
          let p = Math.floor(50 + Math.random() * 40)
          let data = mockAI[step][stepMapToCnt[step]]
          this.aiTestItem.push({
            title: data.title,
            process: data.aires.p,
            content: data.aires.c,
            time: ts
          })
          this.aiTestClass = "el-icon-reading"
          stepMapToCnt[step]++
          if (stepMapToCnt[step] >= mockAI[step].length) {
            stepMapToCnt[step] = mockAI[step].length - 1
          }
        }, 2000)
      }

      run()
      // if (this.active == 3) {
      // } else {
      //   this.active++
      // }
    },

    changeQuestionIndex(index) {
      if (index === -1 && this.currentQuestionPage !== 0) { // 切换上一题
        this.currentQuestionPage -= 1
      }

      if (index === 1 && this.currentQuestionPage < this.questionTotal) {
        this.currentQuestionPage += 1
      }

      else if (this.currentQuestionPage === this.questionTotal - 1) {
        this.$message.error('亲, 已经是最后一题了')
      }
      this.parserQuestion()

    },

    parserQuestion() {
      this.currentQuestion = this.questionAnswerDataList[this.currentQuestionPage]
      if (this.currentQuestion.options) {
        this.currentQuestion.optionList = JSON.parse(this.currentQuestion.options)
      }
    },

    // 答题卡切换试题
    selectQuestion(index) {
      this.currentQuestionPage = index - 1
      this.parserQuestion()
      this.openAnswerFlag = false
    },


    openWritingBoard() {
      // location.href = this.$store.state.host + '/static/writingBoard/writingBoard.html'
      // this.$emit('openWritingBoard')
      // window.open(this.$store.state.common.host + '/static/writingBoard/writingBoard.html')


      this.dialogVisible = true
    },

    lookAnswerImg(url) {
      this.dialogAnswerImgVisible = true
      this.dialogImageUrl = url
    },

    deleteAnswerImg(url) {
      this.$confirm('确定移除该答案吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let index = this.currentQuestion.studentAnswer.indexOf(url)
        this.currentQuestion.studentAnswer.splice(index, 1)
      })
    },

    // 提交
    commitQuestion() {
      let noAnswerCount = 0

      let questionAnswerParam = []
      this.questionAnswerDataList.forEach(item => {
        let studentAnswerStr = ''
        if (item.studentAnswer instanceof Array) {
          if (item.studentAnswer.length === 0) {
            noAnswerCount++
          } else {
            item.studentAnswer.forEach(value => {
              studentAnswerStr += value + ','
            })
            studentAnswerStr = studentAnswerStr.substr(0, studentAnswerStr.length - 1)
          }

        } else {
          if (!item.studentAnswer) {
            noAnswerCount++
          } else {
            studentAnswerStr = item.studentAnswer
          }
        }

        questionAnswerParam.push({
          questionInfoId: item.questionInfoId,
          answer: item.answer,  // 试题答案
          questionType: item.questionType, // 试题类型
          questionMark: item.mark, // 试题得分
          studentAnswer: studentAnswerStr,  //学员试题答案
        })
      })

      if (this.timeOutFlag) {
        this.$emit('afterCommit', questionAnswerParam)
      } else {
        // 未答试题数量
        let message = "确定提交吗?"
        if (noAnswerCount > 0) {
          message = '您还有' + noAnswerCount + '题尚未做答, 确定提交吗?'
        }
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$emit('afterCommit', questionAnswerParam)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消提交'
          })
        })
      }
    },

    beforeUploadAnswerImg(file) {
      let isImage = (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif');
      let isLimit = file.size / 1024 / 1024 < 1;

      if (!isImage) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLimit) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return isImage && isLimit;
    },

    uploadAnswerImgSuccess(res) {
      if (res.code === 1) {
        this.currentQuestion.studentAnswer.push(res.url)
        this.$message.success('答案上传成功')
      } else {
        this.$message.error(res.message)
      }
    }
  },

  filters: {
    getQuestionTypeName(questionType) {
      for (let i = 0; i < thisPage.questionTypeList.length; i++) {
        if (thisPage.questionTypeList[i].code === questionType) {
          return thisPage.questionTypeList[i].value
        }
      }
      return '无'
    }
    /* parserAnswer (val) {
       if (val instanceof Array) {
         let value = ''
         for (let item in val) {
           value += val[item] + ","
         }
         return value.substr(0, value.length - 1)
       }
       return  val
     }*/
  }
}
</script>

<style lang="scss"> 

.el-dialog__header {
  background-color: #477efa !important;
  color: aliceblue !important;
}

.el-dialog__close{
  color: aliceblue !important;
}

.GPSREN {
  margin-bottom: 0px !important;

  .cust-title {
    text-align: center;
    font-size: 20px;
  }

  .cust-label {
    font-weight: bold;
  }

  .custom-height .el-textarea__inner {
    height: 250px;
    /* 设置你想要的高度 */
  }
}

.testbox p {
  display: inline-block;
}


/*.el-upload--picture-card {*/
/*  width: 100px !important;*/
/*  height: 90px !important;*/
/*  line-height: 100px !important;*/
/*  vertical-align: top;*/
/*}*/
.tops {
  display: inline-block;
  text-align: center;
  width: 100px;
  height: 40px;
  line-height: 40px;
  border-radius: 40px;
  background-color: #FAD303;
  box-shadow: 3px 2px 0 0 rgba(250, 213, 3, 0.445);
}

.el-pagination {
  margin-top: 15px;
  text-align: center;
}

.title3 .count {
  position: relative;
  overflow: overlay;
  display: inline-block;
  font-weight: bolder;
  left: 86px;
  color: red;
  font-size: 45px;
}

.title3 .mark {
  width: 205px;
  top: 85px;
  left: 57%;
  height: 64px;
  position: absolute;
}

.el-radio-button__inner,
.el-radio-group {
  padding-top: 20px !important;
  display: block !important;
}

.testinfo {
  padding-left: 30px;
  padding-top: 22px;
}

.title3 {
  width: 100%;
  height: 30px;
  text-align: center;
}

.subbtnbox {
  width: 100%;
  text-align: center;
  padding: 20px;

  .btn {
    width: 100px;
    background-color: red;
  }
}

.testbox {
  display: inline-block;
  margin-top: 20px
}

.btnbox {
  display: flex;
  display: -webkit-flex;
  justify-content: space-around;
  padding-left: 100px;
  margin-top: 30px;
  padding-right: 100px;
}

.play {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding-left: 10px;
  color: red;
  cursor: pointer;

  .cp {
    font-size: 20px;
    vertical-align: middle;
  }

  .ai-ana {
    color: skyblue;
  }
}


.typing-effect {
  overflow: hidden;
  /* 确保超出部分的内容不显示 */
  border-right: .15em solid orange;
  /* 光标效果 */
  white-space: nowrap;
  /* 防止文本换行 */
  animation: typing 3s steps(20, end), blink-caret .75s step-end infinite;
}

@keyframes typing {
  from {
    width: 0
  }

  to {
    width: 100%
  }
}

@keyframes blink-caret {

  from,
  to {
    border-color: transparent
  }

  50% {
    border-color: orange
  }
}
</style>
