<template>
  <!-- 专业选择列表 -->
  <div class="page-container">
    <CommonNavbar
      :bgColor="bgColor"
      v-show="isShowNavbar"
      :title="navTitle"
      :isFixNavbar="isFixNavbar"
      :burialPoint="pointStyle"
      borderStyle="1px solid #fff"
    ></CommonNavbar>
    <section class="page-content">
      <table class="page-content-table">
        <tr>
          <td @click="changeTab(1)" :class="{'active': tabIndex === 1}">
            <div class="tap-title">
              <span :style="{'color': tabIndex === 1 ? '#333' : '#999'}">高级职称</span>
              <span :class="{'android': isAndroid, 'ios': isIOS}"></span>
            </div>
          </td>
          <td @click="changeTab(2)" :class="{'active': tabIndex === 2}">
            <div class="tap-title">
              <span :style="{'color': tabIndex === 2 ? '#333' : '#999'}">中级职称</span>
              <span :class="{'android': isAndroid, 'ios': isIOS}"></span>
            </div>
          </td>
        </tr>
      </table>
      <article class="page-content-list" style="margin-top: 50px;">
        <CommonImgTitle></CommonImgTitle>
        <div :id="'subject_1_' + index" class="subject" v-for="(item, index) in gjFirstSubjectModelList" :key="index">
          <p>{{item.name}}<span v-show="item.code">（{{item.code}}）</span></p>
          <ul class="item-wrapper">
            <li @click="coopDetails(item, 1)" v-if="item.openFlag" class="item-rel">
              <img v-if="item.bindCardStatus" class="buy" src="../images/course/icon-buy.png" alt="">
              <div class="item">
                <img src="../images/course/icon-kc-1.png" alt="">
                <span>课程</span>
              </div>
            </li>
            <li v-if="!item.openFlag && item.resourceModelList.length" class="item-pre">
              <div class="pre">
                <img src="../images/course/icon-kc-2.png" alt="">
                <span class="pre">课程</span>
              </div>
              <p v-show="item.predictTime">{{formatTime2(item.predictTime)}}上线</p>
            </li>

            <li @click="coopDetails(item, 2)" v-if="item.directoryList.length" class="item-rel">
              <img v-if="item.bindDirectoryCardStatus" class="buy" src="../images/course/icon-buy.png" alt="">
              <div class="item tk">
                <img src="../images/course/icon-tk-1.png" alt="">
                <span>题库</span>
              </div>
            </li>
          </ul>
        </div>
      </article>
      <article ref="zjListRef" id="zjListRef" class="page-content-list">
        <CommonImgTitle imgType=2 title="中级职称"></CommonImgTitle>
        <div :id="'subject_0_' + index" class="subject" v-for="(item, index) in zjFirstSubjectModelList" :key="index">
          <p>{{item.name}}<span v-show="item.code">（{{item.code}}）</span></p>
          <ul class="item-wrapper">
            <li @click="coopDetails(item, 1)" v-if="item.openFlag" class="item-rel">
              <img v-if="item.bindCardStatus" class="buy" src="../images/course/icon-buy.png" alt="">
              <div class="item">
                <img src="../images/course/icon-kc-1.png" alt="">
                <span>课程</span>
              </div>
            </li>
            <li v-if="!item.openFlag && item.resourceModelList.length" class="item-pre">
              <div class="pre">
                <img src="../images/course/icon-kc-2.png" alt="">
                <span class="pre">课程</span>
              </div>
              <p v-show="item.predictTime">{{formatTime2(item.predictTime)}}上线</p>
            </li>
            <li @click="coopDetails(item, 2)" v-if="item.directoryList.length" class="item-rel">
              <img v-if="item.bindDirectoryCardStatus" class="buy" src="../images/course/icon-buy.png" alt="">
              <div class="item tk">
                <img src="../images/course/icon-tk-1.png" alt="">
                <span>题库</span>
              </div>
            </li>
          </ul>
        </div>
      </article>

      <!-- 修复一个神奇的bug：底部与背景色重叠 -->
      <div style="height: 10px;background: #F8F9FA;"></div>
    </section>

    <transition name="fade">
      <article v-show="needShowBackup" @click="scrollTop" class="back-up-icon">
        <img src="../images/cme/phrase2/back-top.png" alt />
      </article>
    </transition>
    <Loading v-if="showLoading" />
  </div>
</template>
<script>
import CommonNavbar from "@/components/common/common-navbar";
import Loading from "@/components/common/common-loading";
import CommonImgTitle from "@/components/course/common-img-title";
import { mapGetters, mapActions } from "vuex";
import { getWebPageUrl, parseTime } from "@/utils/index";
import { Toast } from "vant";
let zjListOffsetTop = 0;
let screenHeight = 667;
export default {
  data() {
    return {
      existBind: 0,
      showLoading: false,
      isWeb: window.__isWeb,
      isAndroid: window.__isAndroid,
      isIOS: window.__isIOS,
      bgColor: "#fff",
      isShow: false,
      navTitle: "选择专业",
      isShowNavbar: true,
      isFixNavbar: true,
      pointStyle: "activity",
      tabIndex: 1,
      joinProjectList: [], // 我的项目
      otherProjectList: [], // 全部项目
      token: "",
      userMobile: "",
      needShowBackup: false,
      listData: [],
      zjFirstSubjectModelList: [],
      gjFirstSubjectModelList: [],
      isInfresh: false,
      hasLogin: false,
      hasResetPosition: false
    };
  },
  computed: {
    ...mapGetters(["userInfo"])
  },

  components: {
    CommonNavbar,
    Loading,
    CommonImgTitle
  },
  
  created() {
    var _this = this;
    window.__getUserInfo = function(param) {
      _this.setUserInfo(param);
      _this.token = param.userToken;
      _this.checkToken();
      _this.userMobile = param.userMobile;
      _this.getListData();
    };
    _this.getUserInfo();
    if (__isWeb) {
      _this.getListData();
    }
    window.__refresh = function() {
      _this.isInfresh = true;
      _this.getUserInfo();
    };

    window.addEventListener("scroll", this.scrollFun);
  },

  mounted() {

  },

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

    // 切换列表, 滚动到列表指定位置
    changeTab(index) {
      if(index == 1) {
        window.scrollTo(0, 0);
      } else {
        let scrollTop = zjListOffsetTop - 132;
        if(this.isAndroid) {
          scrollTop = zjListOffsetTop - 116;
        }
        window.scrollTo(0, scrollTop);
      }
      this.tabIndex = index;
    },

    // 跳转到项目页面或课程
    coopDetails(item, type) {
      // if (item.openFlag == 0) return;
      this.$sendBuriedData({
        component_tag: `886#8864#${item.id}#${item.name}` //'210#210002#0#'+item.projectName
      });

      // 临时添加
      if (window.__isWeb) {
        if(type == 1) {
          this.$router.push({
            path: "/coop",
            query: {
              id: item.projectId
            }
          });
        } else {
          this.$router.push({
            path: "/question-bank",
            query: {
              secondSubjectId: item.id
            }
          });
        }
        return;
      }

      let appVersion = this.userInfo.appVersion;
      let appVersionNum = appVersion.split(".").join("");
      console.log("appVersionNum", appVersionNum);
      if (appVersionNum < 341) {
        Toast("请您下载新版本App");
        return;
      }

      let pageUrl = getWebPageUrl(`profexam/#/coop?id=${item.projectId}`);
      if(type == 2) {
        pageUrl = getWebPageUrl(`profexam/#/question-bank?secondSubjectId=${item.id}`)
      }
      let paramList = [
        {
          key: "pageUrl",
          value: pageUrl,
          type: 4,
          seqNo: 1
        }
      ];
      rocNative.dispatchEventByModuleCode({
        modeCode: "M300",
        jsonString: paramList
      });
    },

    //获取版本号
    getUserInfo() {
      rocNative.getUserInfo({
        __funcName: "__getUserInfo"
      });
    },

    // 查询列表
    getListData() {
      let _this = this;
      let param = {
        token: _this.token || '531EB4560CBB4653B1F2C65B7F1816EF',
        setEntry: true
      };
      this.showLoading = true;
      this.GET(`portal/titleTestApp/list`, param).then(res => {
        this.showLoading = false;
        if (res.code == "000000") {
          this.existBind = res.data.existBind || 0;
          this.zjFirstSubjectModelList = res.data.titleTestModelList[0].firstSubjectModelList[0] && res.data.titleTestModelList[0].firstSubjectModelList[0].secondSubjectModelList || [];
          this.gjFirstSubjectModelList = res.data.titleTestModelList[2].firstSubjectModelList[0] && res.data.titleTestModelList[2].firstSubjectModelList[0].secondSubjectModelList || [];
          
          // 如果有绑定的卡，并且之前没有做定位，则进行定位
          if (this.existBind && !this.hasResetPosition) {
            this.hasResetPosition = true;
            let titleTestModelList = res.data.titleTestModelList || [];
            titleTestModelList.splice(1, 1);
            this.resetPosition(titleTestModelList);
          }
          this.$forceUpdate();
          // 延迟获取中级职称
          this.$nextTick(() => {
            setTimeout(() => {
              zjListOffsetTop = document.getElementById('zjListRef').offsetTop;
              screenHeight = screen.height;
              console.log('zjListOffsetTop, screenHeight', zjListOffsetTop, screenHeight);
            }, 100);
          });
          
        } else {
          this.$toast(res.message);
        }
      });
    },

    // 查找对应的职称与专业
    resetPosition(list) {
      if (!list.length) return;
      let parentIndex = 0,
        // fIndex = 0,
        subIndex = 0,
        firstSub = [],
        secondSub = [];
      outloop: for (let i = list.length - 1; i >= 0; i --) {
        firstSub = list[i].firstSubjectModelList;
        for (let j = 0; j < firstSub.length; j++) {
          secondSub = firstSub[j].secondSubjectModelList;
          for (let k = 0; k < secondSub.length; k++) {
            if (secondSub[k].bindCardStatus || secondSub[k].bindDirectoryCardStatus) {
              parentIndex = i;
              // fIndex = j;
              subIndex = k;
              break outloop;
            }
          }
        }
      }
      this.$forceUpdate();
      this.resetProjectPosition(parentIndex, subIndex);
    },

    // 查找对应的职称与专业
    resetPositionNew(list) {
      console.log('in resetPosition', list);
      if (!list.length) return;
      let fIndex = 0,
        level = 1,
        firstSub = [],
        secondSub = [];
      outloop: for (let i = 0; i < list.length; i++) {
        firstSub = list[i].firstSubjectModelList;
        for (let j = 0; j < firstSub.length; j++) {
          secondSub = firstSub[j].secondSubjectModelList;
          if(secondSub.length) {
            if(secondSub[0].bindCardStatus) {
              level = 1;
            }
            if(secondSub[0].bindCardStatus || secondSub[0].bindDirectoryCardStatus) {
              fIndex = j;
              break outloop;              
            }
          }
        }
      }
      this.$forceUpdate();
      this.resetProjectPosition(fIndex);
    },

    // 将定位到的元素，滚动到最上面
    resetProjectPosition(parentIndex, subIndex) {
      this.$nextTick(() => {
        setTimeout(() => {
          let scrollTop = document.getElementById(
            `subject_${parentIndex}_${subIndex}`
          ).offsetTop;
          console.log('resetProjectPosition', scrollTop);
          window.scrollTo(0, (scrollTop - 120));
        }, 100);
      });
    },

    // 监听滚动事件
    scrollFun() {
      let scrollTop = window.scrollY;

      if(scrollTop + screenHeight - 20 > zjListOffsetTop) {
        this.tabIndex = 2;
      } else {
        this.tabIndex = 1;
      }

      if (scrollTop >= 500) {
        this.needShowBackup = true;
      } else {
        this.needShowBackup = false;
      }

      this.$nextTick( () => {
        if(window.scrollY <= 5) {
          this.tabIndex = 1;
        }
      })
      // console.log('in scrollTop + screenHeight, zjListOffsetTop', scrollTop + screenHeight, zjListOffsetTop);
    },

    // 滚动到顶部
    scrollTop() {
      window.scrollTo(0, 0);
    },

    // 格式化时间
    formatTime(time, cFormat) {
      return parseTime(time, cFormat);
    },

    formatTime2(time) {
      if(!time) return '';
      let year = time.substr(0, 4);
      let month = time.substr(5, 2);
      return `${year}年${month}月`;
    },

    // token是否失效校验
    checkToken() {
      let _this = this;
      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 {
          _this.hasLogin = true;
        }
      });
    }
  },
  
  // 页面销毁前注销滚动的监听事件
  beforeDestroy() {
    // window.removeEventListener('scroll');
  },
};
</script>
<style lang="less" scoped>
.page-container {
  font-size: 14px;
  padding-top: 74px;
  min-height: 100vh;
  background: #F8F9FA;
  .page-content {
    // padding-top: 155px;
    // min-height: 100vh;
    &-table {
      position: fixed;
      top: 64px;
      left: 0;
      z-index: 100;
      width: 100%;
      text-align: center;
      // border-bottom: 1px solid #e7e7e7;
      background: #fff;
      box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.04);
      tr {
        font-size: 15px;
        font-weight: 700;
        height: 44px;
        td {
          width: 50%;
          padding-top: 6px;
          .tap-title {
            display: flex;
            flex-direction: column;
            align-items: center;
            color: #999;
            span:nth-child(2) {
              position: relative;
              left: 0;
              bottom: -8px;
              z-index: 2;
              width: 10px;
              height: 3px;
              background: rgba(255, 255, 255, 1);
              border-radius: 3px;
            }
          }
          &.active {
            span:nth-child(2) {
              background: rgba(68, 146, 132, 1);
            }
            span.android:nth-child(2) {
              bottom: -9px;
            }
            span.ios:nth-child(2) {
              bottom: -7px;
            }
          }
        }
      }
    }
    &-list {
      margin: 0 15px 10px;
      padding: 0 15px;
      background: #fff;
      padding-bottom: 10px;
      border-radius: 6px;
      // height: 700px;
      .subject {
        // padding-bottom: 10px;
        & > p, & > p > span {
          padding: 5px 0 10px;
          font-size: 16px;
          font-weight: 700;
          color: #333333;

        }
        .item-wrapper {
          display: flex;
          flex-direction: row;
          justify-content: space-between;
          margin-bottom: 20px;
          .item-rel {
            position: relative;
            top: 0;
            left: 0;
            z-index: 3;
          }
          .item {
            position: relative;
            top: 0;
            left: 0;
            z-index: 4;
            display: flex;
            width: 150px;
            height: 40px;
            background: rgba(59, 134, 253, 0.05);
            border-radius: 6px;
            border: 1px solid #3B86FD;
            align-items: center;
            justify-content: center;
            box-sizing: content-box;
            & > img {
              width: 14px;
              height: 14px;
            }
            & > span {
              margin-left: 4px;
              font-size: 14px;
              color: #3B86FD;
            }
          }
          .buy {
            position: absolute;
            top: 1px;
            right: 0px;
            z-index: 3;
            width: 34px;
            height: 16px;
          }
          .item-pre {
            display: flex;
            flex-direction: column;
            width: 150px;
            height: 40px;
            background: rgba(59, 134, 253, 0.05);
            border-radius: 6px;
            border: 1px solid #D7DFF0;
            align-items: center;
            justify-content: center;
            & > .pre {
              display: flex;
              flex-direction: row;
              align-items: center;
              justify-content: center;
              & > img {
                width: 14px;
                height: 14px;
              }
              & > span {
                margin-left: 4px;
                color: #D7DFF0;
              }
            }
            & > p {
              line-height: 1.2;
              font-size: 12px;
              color: #94A3C1;
            }
          }
          .tk {
            background: rgba(255, 90, 110, 0.05);
            border-radius: 6px;
            border: 1px solid #FF5A6E;
            span {
              color: #FF5A6E;
            }
          }
        }
      }
    }
  }
}
.back-up-icon {
  position: fixed;
  z-index: 10;
  bottom: 50px;
  right: 15px;
  img {
    width: 35px;
    height: 35px;
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-active {
  opacity: 0;
}
</style>

