<template>
  <div class="question-bank-wrap">
    <CommonNavbar
      ref="navBarCom"
      :bgColor="bgColor"
      v-if="isShowNavbar"
      :title="navTitle"
      :isFixNavbar="isFixNavbar"
      borderStyle="1px solid #fff"
    ></CommonNavbar>
    <DirectoryInfo
      :directoryInfo="directoryInfo"
      @handlerBook="handlerBook"
    ></DirectoryInfo>
    <div class="question-bank-content" :class="!isWeb ? 'add-padding' : ''">
      <div class="question-intro" v-if="directoryInfo.directoryImageUrl || directoryInfo.directoryIntro">
        <img v-if="directoryInfo.directoryImageUrl" :src="directoryInfo.directoryImageUrl">
        <p v-if="directoryInfo.directoryIntro">{{directoryInfo.directoryIntro}}</p>
      </div>
      <div class="course-list" v-if="subDirectoryModelList && subDirectoryModelList.length > 0">
        <p class="title"><span class="line"></span>考点</p>
        <div class="course-item" v-for="(item, index) in subDirectoryModelList" :key="index">
          <div class="left-c">
            <p class="title-c">{{item.directoryName}}</p>
            <p class="join-c" v-if="!bindStatus">共{{item.sumTitle}}题 | {{item.joinUserNum}}人已参与</p>
            <div class="progress-course" v-else>
              <div class="progress-w"><van-progress :percentage="item.finishedRatio" :stroke-width="6" color="#449284" :show-pivot="false"/></div>
              <span class="mg-set">{{item.finishedRatio}}%</span><span>共{{item.sumTitle}}道</span>
            </div>
          </div>
          <div class="right-btn">
            <span v-if="!bindStatus && (item.freeFlag == 0)" @click="goStudy(item, '开始练习')">开始练习</span>
            <span v-if="!bindStatus && (item.freeFlag == 1) && (item.freePractice > 0)" @click="goStudy(item, '免费练习')">免费练习</span>
            <p v-if="!bindStatus && (item.freeFlag == 1) && (item.freePractice > 0)">可练习{{item.freePractice}}题</p>

            <img v-if="!bindStatus && (item.freeFlag == 1) && (item.freePractice == 0)" src="../images/question/lock.png" @click="unlockHand">
            <span v-if="bindStatus == 1" @click="goStudy(item, setTxt(item.finishedRatio))">{{setTxt(item.finishedRatio)}}</span>
          </div>
        </div>
      </div>
    </div>
    <BindCardButton
      v-if="!bindStatus"
      :cardInfo="cardInfo"
      desc="激活或购买后可做题"
      @changeClick="changeClick"
      @gotoBuy="confirm"
    ></BindCardButton>
    <ChangeCard
      :changeErrorMsg="changeCardErrorMsg"
      :isShow="showChangeCard"
      @cancle="cancleChangeCard"
      @confirm="beforeChangeCardAction">
    </ChangeCard>
    <CourseDialog
      :subContent="subContent"
      confirmBtnText="激活"
      needSubContent
      :isShowDialog="showBindCardTips"
      @handlerAction="handlerAction"
    ></CourseDialog>
    <Loading v-show="showLoading" />
  </div>
</template>
<script>
  import CommonNavbar from "@/components/common/common-navbar";
  import BindCardButton from "@/components/cme/bind-card-button";
  import ChangeCard from "@/components/cme/change-card";
  import CourseDialog from "@/components/course/course-dialog";
  import Loading from "@/components/common/common-loading";
  import DirectoryInfo from "@/components/question/directory-info";
  import {Progress, Toast} from 'vant';
  import { mapGetters, mapActions } from "vuex";
  import { getWebPageUrl } from "@/utils/index";
export default {
  components: {
    CommonNavbar,
    BindCardButton,
    ChangeCard,
    Progress,
    CourseDialog,
    Loading,
    DirectoryInfo
  },
  data() {
    return {
      token: '',
      isWeb: window.__isWeb,
      isInfresh: false,
      bgColor: "#fff",
      isShowNavbar: true,
      navTitle: '',
      isFixNavbar: false,
      secondSubjectId: null,
      directoryInfo: {
        finishedNum: 0,
        wrongTitle: 0,
        correctRatio: 0,
      },
      subDirectoryModelList: [],
      userId: null,
      bindStatus: 0,
      cardInfo: {
        id: 0
      },
      subContent: '',
      cmeCardModels: {},
      showBindCardTips: false,
      showChangeCard: false,
      changeCardErrorMsg: "",
      hasNoUsedCard: false,
      showLoading: false
    }
  },
  created() {
    let _this = this;
    _this.secondSubjectId = _this.$route.query.secondSubjectId || 106;
    window.__getUserInfoQB = function(param) {
      console.log("__getUserInfoQB", param);
      _this.token = param.userToken;
      _this.userMobile = param.userMobile;
      _this.setUserInfo(param);
      _this.initData();

    };
    _this.getUserInfo();
    if (_this.isWeb) {
      _this.initData();
    }
    window.__refresh = function() {
      _this.isInfresh = true;
      _this.getUserInfo();
    };

    window.__getPositionData = function(param) {
      console.log(param);
      // _this.showLoading = false;
      param.setEntry = true;
      _this.getProvinceIdByPosition(param);
    };
  },
  mounted() {},
  computed: {
    ...mapGetters(["userInfo"]),
    setTxt() {
      let txt = '';
      return function (val) {
        if (val == 0) {
          txt = '开始练习';
        }else if (val == 100) {
          txt = '重新练习';
        }else {
          txt = '继续练习';
        }
        return txt;
      }
    },
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    //获取用户信息
    getUserInfo() {
      rocNative.getUserInfo({
        __funcName: "__getUserInfoQB"
      });
    },
    initData() {
      let param = {
        token: this.token,
        setEntry: true
      };
      this.showLoading = true;
      this.GET(`portal/titleTest/user/getBrushTitleInfo/${this.secondSubjectId}`, param).then(res => {
        if (res.code == "000000") {
          this.directoryInfo = JSON.parse(JSON.stringify(res.data));
          const { subDirectoryModelList, userId, cardType, goodsType, organizationId, provinceId, bindStatus, firstSubjectCodeName, secondSubjectName, secondSubjectCode } = this.directoryInfo;
          this.subDirectoryModelList = subDirectoryModelList;
          this.userId = userId;
          this.bindStatus = bindStatus;
          this.navTitle = `${secondSubjectName}${secondSubjectCode}`;
          // this.navTitle = `${firstSubjectCodeName}-${secondSubjectName}${secondSubjectCode}`;

          setTimeout(() => {
            this.showLoading = false;
          }, 100);
          //获取底部卡信息
          // 如果 bindStatus 为false，则获取卡信息  0：未绑卡 1：已绑卡
          if (!this.bindStatus) {
            this.preJumper();
          //  查询有无已买未激活的卡
            this.hasNoUsedCardAction();
          }
        } else {
          this.$toast(res.message);
        }
      });
    },
    // token是否失效校验
    checkToken() {
      let param = {
        token: this.userInfo.userToken || this.token,
        setEntry: true
      };
      this.GET("campaign/admin/task/checkToken", param).then(res => {
        if (res.code !== "000000") {
          //未登录 跳转登录页
          console.log("跳登录", this.isInfresh);
          if(this.isInfresh) {
            rocNative.goBack();
          } else {
            rocNative.gotoLogin();
          }
          this.isInfresh = false;
        }else {

        }
      });
    },
    // 跳转前判断是否有机构，否则使用定位信息
    preJumper() {
      // TODO 测试代码
      if (window.__isWeb) {
        this.getCardInfoByProvinceId(310);
      } else {
        if (this.directoryInfo.organizationId != 0 && this.directoryInfo.provinceId != 0) {
          this.getCardInfoByProvinceId(this.directoryInfo.provinceId);
        } else {
          this.getPositionData();
        }
      }
    },
    // 根据省ID，获取学习卡信息
    getCardInfoByProvinceId(provinceId) {
      let param = {
        area: provinceId + "",
        cardType: this.directoryInfo.cardType || 3,
        cardTypeList: [ this.directoryInfo.cardType || 3],
        goodsType: this.directoryInfo.goodsType,
      };
      param.setEntry = true;
      this.POST("trade/goods/cardList_v2", param).then(res => {
        if (res.code == "000000") {
          // this.showLoading = false;
          this.cardInfo = (res.data && res.data[0]) || { id: 0, name: "职称考精讲课程卡" };
          this.subContent = `您已购买“${this.cardInfo.goodsName}”，是否使用此卡绑定并激活当前内容？一旦使用，不可更改或退回`
        }
      });
    },
    // 获取地理位置信息
    getPositionData() {
      // this.showLoading = true;
      console.log("getPositionData");
      rocNative.getPositionData({
        __funcName: "__getPositionData"
      });
    },
    // 根据位置信息获取省ID
    getProvinceIdByPosition(param) {
      param.setEntry = true;
      this.POST("aggregate/cme/convertLocationToProvinceId", param)
        .then(res => {
          if (res.code == "000000") {
            this.getCardInfoByProvinceId(res.data);
          }
        }
      );
    },
    // 查询是否买过类似的卡，但还没有绑定激活
    hasNoUsedCardAction() {
      let param = {
        setEntry: true
      };
      this.GET(`cme/projectCard/queryNoUsedCard/${this.directoryInfo.goodsType}/${this.directoryInfo.cardType}`, param).then(({ data }) => {
        //hasNoUsedCard是否有购买未使用的学习卡：1有，0没有
        this.hasNoUsedCard = data.hasNoUsedCard;
        if (data.hasNoUsedCard == 1) {
          this.cmeCardModels = data.cmeCardModels[0] || {};
          this.showBindCardTips = true;
        }
      });
    },
    // 处理提示信息框
    handlerAction(type) {
      if(type == 1) {
        this.$sendBuriedData({
          component_tag: `885#88518`
        });
        this.showBindCardTips = false;
      } else {
        this.$sendBuriedData({
          component_tag: `885#88519`
        });
        this.beforeChangeCardAction(this.cmeCardModels.cardKey, true)
      }
    },
    //错题集或收藏夹
    handlerBook(val) {
      let commitKind = null,currentTitle = '';
      if (val == 1) {
        commitKind = 1;
        currentTitle = '错题集';
        this.$sendBuriedData({
          component_tag: `885#88501`
        });
      }else if (val == 2) {
        commitKind = 2;
        currentTitle = '收藏';
        this.$sendBuriedData({
          component_tag: `885#88502`
        });
      }
      this.checkTokenForNative(() => {
        this.$router.push({
          path: '/question-detail',
          query: {
            directoryId: 0,
            secondSubjectId: this.secondSubjectId,
            cardType: this.directoryInfo.cardType,
            goodsType : this.directoryInfo.goodsType,
            commitKind : commitKind,
            freeFlag: 1,
            currentTitle: currentTitle,
            seqNo: 0,
            cardId: this.cardInfo.id,
          }
        })
      });
    },
    //去激活
    changeClick() {
      this.checkTokenForNative(() => {
        this.showChangeCard = true;
      });

      this.$sendBuriedData({
        component_tag: `885#88516`
      });
    },



    //去购买操作-先校验登录
    confirm() {
      this.checkTokenForNative(() => {
        this.confirmGoBuy();
      })
      this.$sendBuriedData({
        component_tag: `885#88517`
      });
    },

    // 新购买方法
    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.cardInfo.id}&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;
      }

      // 直接传入职称考项目ID(projectId)
      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.cardInfo.id,
          type: 4,
          seqNo: 1
        },
        {
          key: "courseUrl",
          value: encodeURIComponent(pageUrl),
          // value: projectId,
          type: 4,
          seqNo: 1
        }
      ];
      rocNative.dispatchEventByModuleCode({
        modeCode: "M200",
        jsonString: paramList
      });
    },
    //确认激活操作-先校验登录
    beforeChangeCardAction(cardKey, isInTips) {
      this.checkTokenForNative(() => {
        this.changeCardAction(cardKey, isInTips);
      });
    },
    changeCardAction(cardKey, isInTips) {
      let param = {
        idType: 2,
        cardKey: cardKey,
        cardType: this.directoryInfo.cardType,
        goodsType: this.directoryInfo.goodsType,
        channel: 1,
        portalProjectId: this.secondSubjectId,
        setEntry: true
      };
      this.changeCardErrorMsg = "";
      this.POST("cme/projectCard/bind", param).then(res => {
        isInTips && (this.showBindCardTips = false);
        if (res.code == "000000") {
          if(res.data == 0) {
            if(isInTips) {
              Toast(res.message);
            } else {
              this.changeCardErrorMsg = "请输入正确的激活码";
            }
          } else {
            this.showChangeCard = false;
            Toast("激活成功，开始学习");
            this.initData();
          }
        } else {
          Toast(res.message);
        }
      }).catch( e => {
        console.log('in catch', isInTips);
        if(isInTips) {
          Toast("无效的激活码");
          this.showBindCardTips = false;
        } else {
          this.changeCardErrorMsg = "请输入正确的激活码";
        }
      });
    },
    //关闭激活弹层
    cancleChangeCard() {
      this.showChangeCard = false;
    },
    //各种练习
    goStudy(obj, btnText) {
      this.checkTokenForNative(() => {
        this.$router.push({
          path: '/question-detail',
          query: {
            directoryId: obj.directoryId,
            secondSubjectId: this.secondSubjectId,
            cardType: this.directoryInfo.cardType,
            goodsType : this.directoryInfo.goodsType,
            commitKind : 3,
            freeFlag: obj.freeFlag,
            currentTitle: obj.directoryName,
            seqNo: obj.seqNo,
            cardId: this.cardInfo.id,
          }
        })
      });
      let sPoint = ""
      if(btnText === "免费练习" || btnText === "开始练习") {
        sPoint = "88503";
      } else if(btnText === "继续练习") {
        sPoint = "88504";
      } else if(btnText === "重新练习") {
        sPoint = "88505";
      }
      if(sPoint) {
        this.$sendBuriedData({
          component_tag: `885#${sPoint}#${obj.directoryId}#${obj.directoryName}`
        });
      }

    },
    //解锁
    unlockHand() {
      this.$toast('购买后可练习');
      this.$sendBuriedData({
        component_tag: `885#88515`
      });
    },
  },
}
</script>
<style lang="less" scoped>
.question-bank-wrap{
  background-color: #FFFFFF;
  width: 100%;
  padding-bottom: 60px;
  box-sizing: border-box;

  .question-bank-content{
    padding: 126px 16px 0;
    box-sizing: border-box;
    position: relative;
    &.add-padding{
      padding-top: 135px;
    }
    .question-intro{
      margin-top: 15px;
      background-color: #FFFFFF;
      box-sizing: border-box;
      box-shadow: 0 1px 12px 0 rgba(0, 0, 0, 0.05);
      border-radius: 12px;
      img{
        width: 100%;
        border-radius: 6px 6px 0 0;
        display: block;
        max-height: 80px;
      }
      p{
        color: #676869;
        font-size: 12px;
        line-height: 18px;
        padding: 12px;
        /*&:first-child{
          margin-top: 12px;
        }*/
      }
    }
    .course-list{
      margin-top: 30px;
      .title{
        font-size: 18px;
        line-height: 22px;
        color: #373839;
        .line{
          display: inline-block;
          width: 3px;
          height: 15px;
          background-color: #F68367;
          border-radius: 1.5px;
          margin-right: 8px;
          margin-bottom: -1px;
        }
      }
      .course-item{
        padding: 20px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-bottom: 1px solid #E7E8E9;
        .left-c{
          /*flex: 1;*/
          width: 230px;
          .title-c{
            font-size: 15px;
            color: #333333;
            font-weight: 700;
            line-height: 22px;
          }
          .join-c{
            font-size: 12px;
            color: #979899;
            line-height: 14px;
            margin-top: 7px;
          }
          .progress-course{
            margin-top: 8px;
            font-size: 12px;
            color: #979899;
            display: flex;
            align-items: center;
            .progress-w{
              width: 100px;
            }
            .mg-set{
              margin-left: 6px;
              margin-right: 10px;
            }
          }
        }
        .right-btn{
          display: flex;
          flex-direction: column;
          align-items: center;
          span{
            display: inline-block;
            height: 25px;
            line-height: 23px;
            padding: 0 10px;
            color: #449284;
            border: 1px solid #449284;
            border-radius: 15px;
            font-size: 12px;
            font-weight: 700;
            box-sizing: border-box;
          }
          img{
            width: 15px;
            height: 15px;
            margin-right: 22.5px;
          }
          p {
            margin-top: 4px;
            font-size: 12px;
            color: #CAA861;
          }
        }
      }
    }
  }
}
</style>
