<template>
  <section class="qeustion-footer-wrapper">
    <article class="left" @click="toggleAnalysis()">
      <img src="../../images/question/analysis.png" alt />
      <span class="text">解析</span>
    </article>
    <article class="center" @click="toggleCollect()">
      <img v-show="currentQuestion.favorFlag == 0" src="../../images/question/heart-b.png" alt />
      <img v-show="currentQuestion.favorFlag != 0" src="../../images/question/heart.png" alt />
      <span class="text">收藏</span>
    </article>
    <article class="right">
      <span class="pre" :class="{'disabled': currentQuestion.titleNo == 1}" @click="previous">上一题</span>
      <span class="next" :class="{'disabled': currentQuestion.titleNo == totalCount}" @click="next">下一题</span>
    </article>
  </section>
</template>
<script>
import { Toast } from "vant";
import { mapGetters, mapActions } from "vuex";
import { findQuestionIndexNo } from "@/utils";

export default {
  props: {},
  data() {
    return {
      queryParams: {
        commitKind: 3,            // 答题来源 1：错题集 2：收藏 3：题库
        directoryId: 1748,        // 题库ID，获取错题集或收藏时传0
        pageFlag: 0,              // 翻页标记：0往前翻页 1往后翻页
        pageSize: 5,              // 每页大小
        secondSubjectId: 106,     // 二级学科分类ID：用于判断学科下目录免费题数
        titleNo: 0,               // 起始或结束题目序号，首次进入页面时传0，系统自动定位到上次做的题
      }
    };
  },
  computed: {
    ...mapGetters([
      "commitKind",
      "questionList",
      "currentQuestion",
      "totalCount",
      "userInfo",
      "titleConfig",
      "commonConfig",
    ])
  },
  methods: {
    // 上一页 // 有可能要触发上分页（前端的个数只有一条）
    previous() {
      if(!this.canRun()) return;
      this.$sendBuriedData({
        component_tag: `886#88601`
      });
      if (this.currentQuestion.titleNo == 1) {
        Toast("已是第一题");
      } else {
        let cIndex = findQuestionIndexNo(this.questionList, "titleNo", this.currentQuestion.titleNo);
        // 如果没有找到，则不做后面操作
        if(!this.questionList[cIndex - 1]) return;
        this.$store.commit(
          "SET_CURRENT_QUESTION",
          this.questionList[cIndex - 1] || { answerList: [] }
        );
        console.log(cIndex == 1, this.currentQuestion.titleNo >= 2);
        if(cIndex == 1 && this.currentQuestion.titleNo >= 2) {
          this.$emit("pageQuestion", 0, this.questionList[0].titleNo);
        }
      }
    },

    // 下一页 // 有可能要触发下分页（后面的个数只有一条）
    next() {
      if(!this.canRun()) return;
      this.$sendBuriedData({
        component_tag: `886#88602`
      });
      if (this.currentQuestion.titleNo == this.totalCount
      // if (this.currentQuestion.titleNo == this.questionList.length 
        || this.currentQuestion.titleNo == this.questionList[this.questionList.length - 1].titleNo) {
        this.$emit("statistics");
      } else {
        let cIndex = findQuestionIndexNo(this.questionList, 'titleNo', this.currentQuestion.titleNo);
        this.$store.commit(
          "SET_CURRENT_QUESTION",
          this.questionList[cIndex + 1] || { answerList: [] }
        );
        console.log(this.currentQuestion.isAnalyzed || (this.currentQuestion.commitFlag == 2));
        if((cIndex == this.questionList.length - 2) && (this.questionList.length < this.totalCount)) {
          this.$emit("pageQuestion", 1, this.questionList[this.questionList.length - 1].titleNo);
        }
      }
    },

    // 解析
    toggleAnalysis() {
      this.currentQuestion.isAnalyzed = true;
      if(!this.currentQuestion.commitFlag) {
        this.commitAnswer();
      } else {
        setTimeout(() => {
          this.$emit("scrollTop");
        }, 200);
      }
      this.$sendBuriedData({
        component_tag: `886#88603`
      });
    },

    // 收藏/不收藏
    toggleCollect() {
      this.favor(this.currentQuestion);
      // this.$store.commit('SET_CURRENT_QUESTION', this.currentQuestion);
    },

    // 收藏/取消收藏
    favor() {
      if(!this.canRun()) return;
      let favorFlag = this.currentQuestion.favorFlag;
      let sPoint = favorFlag == 1 ? "88605" : "88604";
      this.$sendBuriedData({
        component_tag: `886#${sPoint}`
      });
      let param = {
        dataType: 2,
        directoryId: this.currentQuestion.directoryId,
        examTitleId: this.currentQuestion.titleId,
        operateType: favorFlag == 1 ? 2 : 1, // 操作类型：1：收藏 2：取消收藏
        paperId: this.currentQuestion.paperId,
        paperIndex: this.currentQuestion.paperIndex,
        token: this.userInfo.userToken || this.token,
        setEntry: true
      };
      this.currentQuestion.favorFlag = this.currentQuestion.favorFlag == 0 ? 1 : 0;

      let operateText = "收藏成功";
      if(param.operateType == 2) {
        operateText = "取消收藏";
      }
      Toast(operateText);
      this.POST("onlineexam/collectExamTitle", param).then(res => {
        if (res.code == "000000") {
          if(res.data) {
            // let cIndex = this.questionList.findIndex( item => {
            //   return item.titleNo = this.currentQuestion.titleNo;
            // });
            // this.questionList[cIndex].favorFlag = favorFlag == 0 ? 1 : 0;
            // this.currentQuestion.favorFlag = favorFlag == 0 ? 1 : 0;
          }
        }
      });
    },

    // 提交答案
    commitAnswer() {
      this.checkTokenForNative( () => {
        let params = {
          commitKind: this.commonConfig.commitKind, // 答题来源 1：错题集 2：收藏 3：题库
          directoryId: this.currentQuestion.directoryId, // 题库ID
          myAnswer: this.currentQuestion.myAnswer, // 我的答案，单选时单个答案，如A；多选答案，按照顺序使用
          paperId: this.currentQuestion.paperId, // 试卷ID
          paperIndex: this.currentQuestion.paperIndex, // 试卷索引（随机试卷的第n套）
          resultId: this.titleConfig.resultId, // 刷题库轮次ID，刷收藏和错题集时为0
          // rightFlag: 1,                                // 答题对错：1对 2错
          titleId: this.currentQuestion.titleId, // 题目ID
          titleNo: this.currentQuestion.titleNo, // 题目ID
          setEntry: true,
          token: this.userInfo.userToken,
        };
        let isRight = this.currentQuestion.myAnswer == this.currentQuestion.answer;
        if (isRight) {
          this.currentQuestion.commitFlag = 1;
        } else {
          this.currentQuestion.commitFlag = 2;
        }
        this.currentQuestion.isAnalyzed = true;
        // this.$forceUpdate();
        setTimeout(() => {
          this.$emit("scrollTop");
        }, 200);
        this.POST(`onlineexam/practise/commit`, params).then(({ data }) => {
          console.log('in commitAnswer res', data);
          // if(data.resultType == 1) {
          //   this.currentQuestion.commitFlag = 1;
          // } else {
          //   this.currentQuestion.commitFlag = 0;
          // }
        }).catch( error => {
          this.currentQuestion.commitFlag = 0;
          this.currentQuestion.isAnalyzed = false;
        })
      });
    }    
  }
};
</script>
<style lang="less" scoped>
.qeustion-footer-wrapper {
  position: fixed;
  width: 100%;
  left: 0;
  bottom: 0;
  display: flex;
  height: 60px;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  background: #ffffff;
  font-size: 14px;
  box-shadow: 0px -2px 10px 0px rgba(0, 0, 0, 0.1);
  padding: 0 5px 0 15px;
  .left {
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    align-items: center;
    & > img {
      width: 18px;
      height: 18px;
    }
    .text {
      font-size: 12px;
    }
  }
  .center {
    display: flex;
    flex-direction: column;
    align-items: center;
    & > img {
      width: 18px;
      height: 18px;
    }
    .text {
      font-size: 12px;
    }
  }
  .right {
    display: flex;
    flex-direction: row;
    align-items: center;
    text-align: center;
    width: 210px;
    color: #373839;
    span {
      display: inline-block;
      width: 100px;
      height: 40px;
      line-height: 40px;
      &.pre {
        border-radius: 20px 0 0 20px;
        border: 1px solid #979899;
        &.disabled {
          color: #979899;
        }
      }
      &.next {
        border-radius: 0 20px 20px 0;
        border: 1px solid #979899;
        border-left: 0px;
      }
    }
  }
}
</style>