<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">
      <section v-show="!existBind" class="cb-wrapper padding-top-111">
        <CardBanner :hasLogin="hasLogin"></CardBanner>
      </section>
      <section class="body" :class="{'body-pt': !existBind}">
        <ul class="left fixed" :class="{'top': !existBind}">
          <li
            v-for="(model, mIndex) in titleTestModelList"
            :key="mIndex"
            :class="{active: currentModelIndex == mIndex}"
            @click="selectModel(model, mIndex)"
          >
            <span>{{model.title}}</span>
          </li>
        </ul>
        <ul class="left"></ul>
        <article class="right">
          <ul class="list-wrapper">
            <li class="list" v-for="(item, index) in listData" :key="index">
              <span class="title">{{item.name}}</span>
              <ul class="item">
                <li
                  :id="'subject_' + index + '_' + sIndex"
                  class="card"
                  :class="{'no-active' : subject.openFlag == 0, 'has-bind' : subject.bindCardStatus == 1}"
                  v-for="(subject, sIndex) in item.secondSubjectModelList"
                  :key="sIndex"
                  @click="coopDetails(subject)"
                >
                  <span>{{subject.name}}</span>
                  <span v-show="subject.code">({{subject.code}})</span>
                  <span v-show="subject.bindCardStatus == 1" class="buy">己购</span>
                  <span
                    v-show="subject.openFlag == 0"
                    class="time"
                  >{{formatTime2(subject.predictTime)}}上线</span>
                </li>
              </ul>
            </li>
            <li class="no-list" v-show="!listData.length">
              <img src="../images/subject/no-subject.png" alt />
              <span>正在更新中，敬请期待</span>
            </li>
          </ul>
        </article>
      </section>
    </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 CardBanner from "@/components/cme/card-banner";
import Loading from "@/components/common/common-loading";
import CommonTitle from "@/components/common/common-title";
import { mapGetters, mapActions } from "vuex";
import { getWebPageUrl, parseTime } from "@/utils/index";
import { Toast } from "vant";

export default {
  data() {
    return {
      existBind: 0,
      currentModelIndex: 2,
      titleTestModelList: [],
      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: [
        {
          name: "中医",
          list: [
            { name: "全科中医", code: 201, bindStatus: 0 },
            { name: "中医内科学中医内科学", code: 201, bindStatus: 0 },
            { name: "全科中医", code: 201, bindStatus: 0 }
          ]
        },
        {
          name: "妇科",
          list: [
            { name: "妇产科学", code: 201, bindStatus: 0 },
            { name: "中医内科学中医内科学", code: 201, bindStatus: 0 },
            { name: "全科中医", code: 201, bindStatus: 0 }
          ]
        },
        {
          name: "内科",
          list: [
            { name: "肾内科学", code: 201, bindStatus: 0 },
            {
              name: "肾内科学肾内科学肾内科学肾内科学",
              code: 201,
              bindStatus: 0
            },
            { name: "全科中医", code: 201, bindStatus: 0 }
          ]
        }
      ],
      isInfresh: false,
      hasLogin: false,
      hasResetPosition: false
    };
  },
  computed: {
    ...mapGetters(["userInfo"])
  },

  components: {
    CardBanner,
    CommonNavbar,
    Loading,
    CommonTitle
  },
  created() {
    var _this = this;
    _this.currentModelIndex = 2;
    window.__getUserInfo = function(param) {
      _this.setUserInfo(param);
      _this.token = param.userToken;
      _this.checkToken();
      _this.userMobile = param.userMobile;
      _this.getListData();
      console.log("__getUserInfo", param);
    };
    _this.getUserInfo();
    if (__isWeb) {
      _this.getListData();
    }
    window.__refresh = function() {
      _this.isInfresh = true;
      // _this.currentModelIndex = 0;
      console.log(_this.currentModelIndex);
      _this.getUserInfo();
    };

    // 打开页面埋点
    // this.$sendBuriedData({
    //   component_tag: "210#0#0#0"
    // });

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

  mounted() {
    this.listData = [];
    // this.currentModelIndex = 0;
  },

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

    // 选择职称
    selectModel(model, index) {
      this.currentModelIndex = index;
      this.listData =
        this.titleTestModelList[index].firstSubjectModelList || [];
        this.$sendBuriedData({
          component_tag: model.titleCode === '1001' ? '886#8861' : (model.titleCode === '1002' ? '886#8862' : '886#8863')
        });
    },

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

      // 临时添加
      if (window.__isWeb) {
        this.$router.push({
          path: "/coop",
          query: {
            id: item.projectId
          }
        });
        return;
      }

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

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

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

    // 查询列表
    getListData() {
      let _this = this;
      let param = {
        token: _this.token,
        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.titleTestModelList = res.data.titleTestModelList || [];
          let len = this.titleTestModelList.length > 0 ? (this.titleTestModelList.length - 1) : 0;
          // 如果有绑定的卡，并且之前没有做定位，则进行定位
          if (this.existBind && !this.hasResetPosition) {
            this.hasResetPosition = true;
            this.resetPosition(this.titleTestModelList);
            // 否则直接使用当前的位置信息
          } else {
            this.listData =
              res.data.titleTestModelList[
                len
              ].firstSubjectModelList;
            this.currentModelIndex = len;
          }
        } else {
          this.$toast(res.message);
        }
      });
    },

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

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

    // 监听滚动事件
    scrollFun() {
      let scrollTop = window.scrollY;
      if (scrollTop >= 500) {
        this.needShowBackup = true;
      } else {
        this.needShowBackup = false;
      }
    },

    // 滚动到顶部
    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);
      // if(month < 10) {
      //   month = time.substr(6, 1);
      // }
      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;
        }
      });
    }
  }
};
</script>
<style lang="less" scoped>
.page-content {
  padding-top: 74px;
  min-height: 100vh;
  .body {
    // min-height: 90vh;
    display: flex;
    flex-direction: row;
    font-size: 14px;
    color: #676869;
    &.body-pt {
      padding-top: 40px;
    }
    .left {
      width: 130px;
      background: #fff;
      li {
        position: relative;
        display: block;
        height: 60px;
        line-height: 60px;
        padding-left: 15px;
        &.active {
          color: #449284;
          background: #fff;
          &.active::before {
            position: absolute;
            left: 0;
            top: 20px;
            z-index: 1;
            content: "";
            height: 20px;
            width: 3px;
            border-radius: 2px;
            background: #449284;
          }
        }
      }
      &.fixed {
        position: fixed;
        top: 74px;
        left: 0;
        bottom: 0;
        right: 130px;
        z-index: 1;
        background: #f8f9fa;
        &.top {
          top: 114px;
        }
      }
    }
    .right {
      flex: 1;
      padding: 0 15px 30px;
      .list-wrapper {
        .list {
          .title {
            display: inline-block;
            // height: 35px;
            padding: 6px 0 10px;
            // line-height: 1.2;
            margin-top: 14px;
            font-size: 15px;
            font-weight: 700;
            color: #373839;
          }
          .item {
            li {
              min-height: 60px;
              position: relative;
              top: 0;
              left: 0;
              z-index: 1;
              display: flex;
              flex-direction: column;
              // height: 55px;
              padding: 12px 0;
              margin-bottom: 6px;
              justify-content: center;
              text-align: center;
              border-radius: 4px;
              background: #f8f9fa;
              align-items: center;
              span {
                display: inline-block;
                // height: 20px;
                line-height: 20px;
                padding: 0 20px;
              }
              &.has-bind {
                color: #449284;
                background: rgba(68, 146, 132, 0.1);
                .buy {
                  position: absolute;
                  top: 0;
                  right: 0;
                  z-index: 1;
                  height: 15px;
                  line-height: 15px;
                  padding: 0 4px;
                  border-radius: 0px 4px 0px 4px;
                  font-size: 11px;
                  color: #fff;
                  background: #449284;
                }
              }
              &.no-active {
                color: #c7c8c9;
                .time {
                  position: absolute;
                  top: 0;
                  right: 0;
                  z-index: 1;
                  height: 15px;
                  line-height: 15px;
                  padding: 0 4px;
                  border-radius: 0px 4px 0px 4px;
                  opacity: 0.4;
                  font-size: 11px;
                  background: rgba(0, 0, 0, 1);
                }
              }
            }
          }
        }
        .no-list {
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-content: center;
          align-items: center;
          margin-top: 60px;
          // width: 50px;
          // height: 50px;
          img {
            width: 100px;
            height: 100px;
          }
          span {
            font-size: 12px;
            color: #c7c8c9;
          }
        }
      }
    }
  }
  .cb-wrapper {
    position: fixed;
    z-index: 2;
    width: 100%;
  }
}
.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>

