<template>
  <section class="question-detail-wrapper" :style="{'position': needFixed ? 'fixed': 'static'}">
    <question-header
      :title="currentTitle"
      :order="currentQuestion.titleNo"
      :total="titleConfig.totalCount"
    ></question-header>
    <article class="body">
      <question-content ref="questionContentRef" v-show="questionList.length"></question-content>
      <no-content v-show="!questionList.length" :commitKind="commitKind"></no-content>
    </article>
    <free-tips v-show="showFreeTips" :total="titleConfig.totalCount" @buyCard="buyCard(2)"></free-tips>
    <question-footer v-show="questionList.length" @statistics="statistics" @scrollTop="scrollTop" @pageQuestion="pageQuestion"></question-footer>
    <ExperienceDialog
      :showDialog="experienceDialog"
      :statisConfig="statisConfig"
      @activeCard="activeCard"
      @buyCard="buyCard(1)"
      @close="closeExpDialog"
    ></ExperienceDialog>

    <!-- 去激活 -->
    <ChangeCard
      :changeErrorMsg="changeCardErrorMsg"
      :isShow="showChangeCard"
      @cancle="cancleChangeCard"
      @confirm="beforeChangeCardAction"
    ></ChangeCard>

    <Loading v-show="showLoading" />
    <div class="pt-70" :class="{'pt-110': showFreeTips}"></div>
  </section>
</template>
<script>
import QuestionHeader from "@/components/question/question-header";
import QuestionContent from "@/components/question/question-content";
import QuestionFooter from "@/components/question/question-footer";
import noContent from "@/components/question/no-content";
import ExperienceDialog from "@/components/question/experience-dialog";
import FreeTips from "@/components/question/free-tips";
import Loading from "@/components/common/common-loading";
import CourseDialog from "@/components/course/course-dialog";
import ChangeCard from "@/components/cme/change-card";

import { mapGetters, mapActions } from "vuex";
import { Toast } from "vant";
import { findQuestionIndexNo, contactArray, getWebPageUrl } from "@/utils";

let titleArray = ["", "错题集", "收藏夹", "题库"];
export default {
  components: {
    QuestionHeader,
    QuestionContent,
    QuestionFooter,
    noContent,
    ExperienceDialog,
    Loading,
    CourseDialog,
    ChangeCard,
    FreeTips
  },
  data() {
    return {
      token: "",
      directoryId: "",
      cardType: 3,
      goodsType: 3,
      currentTitle: "试题集",
      commitKind: 1, // 答题来源 1：错题集 2：收藏 3：题库
      experienceDialog: false, // 体验结束弹框
      showChangeCard: false, //是否展示激活弹框,
      changeCardErrorMsg: "",
      cmeCardModels: {
        cardNo: "",
        cardKey: "",
        cardType: 3,
        orderId: 0
      },
      subContent: "",
      showLoading: false,
      cardInfo: {
        id: 0
      },
      queryParams: {
        commitKind: 3,        // 答题来源 1：错题集 2：收藏 3：题库
        directoryId: 1748,    // 题库ID，获取错题集或收藏时传0
        secondSubjectId: 106, // 二级学科分类ID：用于判断学科下目录免费题数
        titleNo: 0,           // 起始或结束题目ID，首次进入页面时传0，系统自动定位到上次做的题
        pageFlag: 0,          // 翻页标记：0往前翻页 1往后翻页
        pageSize: 5,          // 每页大小
        seqNo: 1,
      },
      statisConfig: {
        rightNum: 0,
        errorNum: 0,
        rate: 0
      }
    };
  },
  computed: {
    ...mapGetters([
      "userInfo",
      "questionList",
      "currentQuestion",
      "totalCount",
      "commonConfig",
      "titleConfig"
    ]),
    needFixed() {
      return (
        this.experienceDialog || this.showChangeCard
      );
    },
    showFreeTips() {
      return this.commonConfig.freeFlag == 1 && this.commitKind == 3 && !this.titleConfig.bindStatus
    }
  },
  created() {
    let _this = this;
    this.directoryId = this.$route.query.directoryId || 1748; // 题库ID，获取错题集或收藏时传0
    this.secondSubjectId = this.$route.query.secondSubjectId || 106; // 学科id
    this.cardId = this.$route.query.cardId || 3;
    this.cardType = this.$route.query.cardType || 3; // 卡类型
    this.goodsType = this.$route.query.goodsType || 3; // 商品类型
    this.commitKind = this.$route.query.commitKind || 3; // 答题来源 1：错题集 2：收藏 3：题库
    this.freeFlag = this.$route.query.freeFlag || 0; // 0: 免费; 1: 收费;
    this.currentTitle = this.$route.query.currentTitle || this.currentTitle; // 顶部导航文案
    if(this.commitKind == 3) {
      titleArray[3] = this.currentTitle;
    }
    this.queryParams.commitKind = this.commitKind;
    this.queryParams.directoryId = this.directoryId;
    this.queryParams.secondSubjectId = this.secondSubjectId;
    this.queryParams.seqNo = this.$route.query.seqNo || 0;

    window.__getUserInfoForQD = function(param) {
      _this.token = param.userToken;
      _this.setUserInfo(param);
      _this.init();
    };
    if (__isWeb) {
      _this.init();
    } else {
      this.getUserInfo();
    }

    window.__refresh = function() {
      // _this.isInfresh = true;
      _this.getUserInfo();
    };

  },
  methods: {
    ...mapActions(["setUserInfo", "handlerQuestionList"]),

    init() {
      this.currentTitle = titleArray[this.commitKind] || "习题集";
      this.$store.commit("SET_COMMON_CONIFG", {
        // 0: 免费; 1: 收费;  没有绑卡且是收费题库（bindStatus == 0 && freeFlag == 1）可以走免费体验流程
        freeFlag: this.freeFlag,
        directoryId: this.directoryId,
        secondSubjectId: this.secondSubjectId,
        cardType: this.cardType,
        goodsType: this.goodsType,
        commitKind: this.commitKind // 答题来源 1：错题集 2：收藏 3：题库
      });
      this.getPractiseTitles(true);
    },

    // 开始翻页
    pageQuestion(pageFlag, titleNo) {
      this.queryParams.pageFlag = pageFlag;
      this.queryParams.titleNo = titleNo;
      this.getPractiseTitles();
    },

    // 统计当前信息
    statistics() {
      // 如果是收费的题库（不是错题集或收载），并且没有绑定卡
      console.log(this.commonConfig.freeFlag, this.commitKind == 3, !this.titleConfig.bindStatus);
      if(!this.showFreeTips) {
        Toast("已是最后一题");
        return;
      }
      let rightNum = 0,
        errorNum = 0,
        rate = 0;
      this.questionList.forEach(item => {
        if (item.commitFlag) {
          if(item.myAnswer == item.answer) {
            rightNum ++;
          } else {
            errorNum ++;
          }
        }
      });
      console.log();
      if((rightNum + errorNum) > 0) {
        rate = (rightNum * 100 / (rightNum + errorNum)).toFixed(0);
        this.statisConfig = {
          rightNum,
          errorNum,
          rate
        }
      }

      this.experienceDialog = true;
    },

    //获取用户信息
    getUserInfo() {
      rocNative.getUserInfo({
        __funcName: "__getUserInfoForQD"
      });
    },

    // 去激活（体验完弹窗-打开激活弹框）
    activeCard() {
      this.$sendBuriedData({
        component_tag: `886#88606`
      });
      this.checkTokenForNative(() => {
        this.experienceDialog = false;
        this.showChangeCard = true;
      });
    },

    // 去购买（体验完弹窗-跳转到购买页面）
    buyCard(type) {
      console.log("in buyCard", type);
      this.checkTokenForNative(() => {
        this.confirmGoBuy();
      });
      if(type == 1) {
        this.$sendBuriedData({
          component_tag: `886#88607`
        });
      } else if(type == 2) {
        this.$sendBuriedData({
          component_tag: `886#88609`
        });
      }
    },

    // 新购买方法
    confirmGoBuy() {
      console.log('new confirm');
      this.$sendBuriedData({
        component_tag: `882#88203`
      });
      let pageUrl = getWebPageUrl(
        `profexam/#/question-bank?id=${this.secondSubjectId}&secondSubjectId=${this.secondSubjectId}`
      );

      let courseUrl = encodeURIComponent(pageUrl);
      let paramPageUrl = getWebPageUrl(`profexam/#/goods-detail?goodsId=${this.cardId}&projectId=${this.secondSubjectId}&courseUrl=${courseUrl}`);
      let paramList = [
        {
          key: "pageUrl",
          value: paramPageUrl,
          type: 4,
          seqNo: 1
        }      
      ]
      rocNative.dispatchEventByModuleCode({
        modeCode: "M300",
        jsonString: paramList
      });
    },

    // 跳转到（原生）购买页面
    confirmGoBuyOld() {
      let appVersion = this.userInfo.appVersion || "";
      let appVersionNum = appVersion.split(".").join("");
      if (appVersionNum < 344) {
        this.$toast("请您下载新版本App");
        return;
      }

      this.experienceDialog = false;
      // 直接传入学科ID(secondSubjectId)
      let pageUrl = getWebPageUrl(
        `/profexam/#/question-bank?id=${this.secondSubjectId}&secondSubjectId=${this.secondSubjectId}`
      );
      let paramList = [
        {
          key: "className",
          value:
            "com.picahealth.yunque.activitys.studycard.StudyCardDetailActivity###PicaDo.LearningCardVC",
          type: 4,
          seqNo: 1
        },
        {
          key: "goodId",
          value: this.cardId,
          type: 4,
          seqNo: 1
        },
        {
          key: "courseUrl",
          value: encodeURIComponent(pageUrl),
          // value: projectId,
          type: 4,
          seqNo: 1
        }
      ];
      rocNative.dispatchEventByModuleCode({
        modeCode: "M200",
        jsonString: paramList
      });
    },

    // 关闭体验完弹窗
    closeExpDialog() {
      this.experienceDialog = false;
      this.$sendBuriedData({
        component_tag: `886#88608`
      });
    },

    // 关闭激活弹框
    cancleChangeCard() {
      this.showChangeCard = false;
    },

    // 激活前
    beforeChangeCardAction(cardKey) {
      this.checkTokenForNative(() => {
        this.changeCardAction(cardKey);
      });
    },

    // 分页获取题目（前、后翻页）
    getPractiseTitles(isFirst) {
      if(isFirst) {
        this.$store.commit("SET_QUESTION_LIST", []);
      }
      isFirst && (this.showLoading = true);
      this.queryParams.token = this.userInfo.userToken || this.token;
      this.queryParams.setEntry = true;
      this.GET(`portal/titleTest/practise/titles`, this.queryParams).then(({ data }) => {
        this.currentTitleNo = data.currentTitleNo;
        data.isFirst = isFirst;
        this.handlerQuestionList(data);
        setTimeout(() => {
          this.showLoading = false;
        }, 100);
      });
    },


    // 处理返回的数据，并存储到store中
    handlerPractiseData(questionList) {
      let handlerList = [],
        question,
        option,
        optionList = [],
        myAnswer = "",
        answer = "";
      questionList.forEach((item, index) => {
        question = JSON.parse(JSON.stringify(item));
        question.isAnalyzed = false;
        option = {};
        optionList = [];
        question.options.forEach((text, i) => {
          option.isCorrect = false;
          option.isSelected = false;
          option.text = text;
          optionList.push(JSON.parse(JSON.stringify(option)));
        });
        question.options = optionList;
        console.log("handlerList", index);
        handlerList.push(question);
      });
      console.log("in handlerList", handlerList);
      let cIndex = findQuestionIndexNo(
        handlerList,
        "titleNo",
        this.currentTitleNo
      );
      this.$store.commit("SET_CURRENT_QUESTION", handlerList[cIndex]);
      this.$store.commit("SET_QUESTION_LIST", handlerList);
    },

    // 激活Action  返回值：0绑定失败，1绑定成功
    changeCardAction(cardKey) {
      let _this = this;
      let param = {
        idType: 2,
        cardKey: cardKey,
        cardType: this.cardType || 3,
        goodsType: this.goodsType || 3,
        channel: 1,
        portalProjectId: this.directoryId,
        setEntry: true
      };
      _this.changeCardErrorMsg = "";
      this.POST("cme/projectCard/bind", param)
        .then(res => {
          if (res.code == "000000") {
            if (!res.data) {
              _this.changeCardErrorMsg = "请输入正确的激活码";
            } else {
              _this.showChangeCard = false;
              Toast("激活成功，开始练习");
              // 重新获取题库内容（从头开始）
              _this.init();
            }
          } else {
            Toast(res.message);
          }
        })
        .catch(e => {
          _this.changeCardErrorMsg = "请输入正确的激活码";
        });
    },

    // 滚动到最上面
    scrollTop() {
      console.log("in scrollTop");
      window.scrollTo(0, 2000);
    }
  }
};
</script>
<style lang="less" scoped>
.question-detail-wrapper {
  padding-top: 68px;
  .pt-70 {
    padding-bottom: 70px;
  }
  .pt-110 {
    padding-bottom: 110px;
  }
}
</style>