<template>
  <div class="home-box">
    <!-- <van-nav-bar
      title="京铁学堂"
      left-text=""
      right-text=""
      bind:click-left=""
      bind:click-right=""
    >
    </van-nav-bar> -->
    <div v-show="activeTabName === 0" class="dropdown-div">
    </div>
    <transition name="tab" mode="out-in">
      <component :is="currentComponents" class="page" />
    </transition>
    <van-tabbar
      v-model="activeTabName"
      active-color="#0088e9"
      inactive-color="#808080"
      @change="onChangeTabFun"
    >
      <van-tabbar-item v-for="(item, index) in tabbars" :key="index">
        <span>{{ item.title }}</span>
        <template #icon="props">
          <img :src="props.active ? item.iconActive : item.iconInactive" />
        </template>
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script>
import PageLearn from "./learn/page-learn";
import PageAnswer from "./answer/page-answer";
import PageExam from "./exam/page-exam";
import PagePerson from "./person/page-person";
import { mapState } from "vuex";
export default {
  name: "home",
  components: { PageLearn, PageAnswer, PageExam, PagePerson },
  data() {
    return {
      currentComponents: "pageLearn",
      activeTabName: 0,
      tabbars: [
        {
          title: "学习",
          pageName: "pageLearn",
          iconInactive: require("@/assets/image/homeTab/study.png"),
          iconActive: require("@/assets/image/homeTab/studyActive.png")
        },
        {
          title: "答题",
          pageName: "pageAnswer",
          iconInactive: require("@/assets/image/homeTab/answer.png"),
          iconActive: require("@/assets/image/homeTab/answerActive.png")
        },
        {
          title: "考试",
          pageName: "pageExam",
          iconInactive: require("@/assets/image/homeTab/exam.png"),
          iconActive: require("@/assets/image/homeTab/examActive.png")
        },
        {
          title: "我的",
          pageName: "pagePerson",
          iconInactive: require("@/assets/image/homeTab/person.png"),
          iconActive: require("@/assets/image/homeTab/personActive.png")
        }
      ],
      engineeringWorkChooseValue: null, // 工种选择的值
      engineeringWorkList: [] // 工种可选列表
    };
  },
  computed: {
    ...mapState({
      user: state => state.user,
      homeChangeTabIndex: state => state.study.homeChangeTabIndex
    })
  },
  created() {
    this.initFun();
    // this.getLanXinSignature();
    this.getLanXinCode();
  },
  activated() {
    this.setLanXinNavigator();
  },
  mounted() {

  },
  watch: {
    // 监听：首页切换tab的下标
    homeChangeTabIndex(value) {
      if (value === null || value === undefined) {
        return;
      }
      this.activeTabName = value;
      this.onChangeTabFun(this.activeTabName);
      this.$store.commit("updateStudyItemStore", {
        field: "homeChangeTabIndex",
        value: null
      });
    }
  },
  methods: {
    // 设置蓝信navigator
    setLanXinNavigator() {
      lx.ui.setNavigationBarTitle({
        title: "京铁学堂"
      });
    },
    // 初始化
    initFun() {
      // 获取所有用户
      this.$_http
        .get(this.$_API.JTXT_GET_USER_ADMIN_USERS)
        .then(res => {
          this.$store.commit("updateUserItemStore", {
            field: "userInfo",
            value: res.data.content[0]
          });
          // 获取所有收藏
          this.getCollection();
          // 获取所有考试历史
          this.getExamHistory();
          //   查询工作信息
          this.getEngineeringWorkList();
        })
        .catch(() => {
          this.$store.commit("toggleLoading", false);
        });
      this.activeTabName = 0;
      this.onChangeTabFun(this.activeTabName);
    },
    // 操作：切换tab
    onChangeTabFun(index) {
      this.currentComponents = this.tabbars[this.activeTabName].pageName;
    },
    // 获取所有收藏
    getCollection() {
      let path = {
        userName: this.user.userInfo.userName
      };
      this.$_http
        .get(this.$pathParams(this.$_API.JTXT_GET_USER_FAVORITES, path))
        .then(res => {
          if (res.data.materials) {
            this.$store.commit("updateFavoriteItemStore", {
              field: "materials",
              value: res.data.materials
            });
            this.$store.commit("updateFavoriteItemStore", {
              field: "titles",
              value: res.data.titles
            });
          } else {
            this.$store.commit("toggleLoading", false);
          }
          this.loading = false;
        })
        .catch(() => {
          this.$store.commit("toggleLoading", false);
        });
    },
    // 查询：考试记录
    getExamHistory() {
      this.$store.commit("toggleLoading", true);
      let params = {
        user: this.user.userInfo.userName
      };
      this.$_http
        .get(this.$_API.JTXT_GET_USER_EXAMS_HISTORY, { params })
        .then(res => {
          let obj = {};
          res.data.forEach(element => {
            obj[element.examId] = element;
          });
          this.$store.commit("updateExamItemStore", {
            field: "examHistoryObj",
            value: obj
          });
        })
        .catch(() => {
          this.$store.commit("toggleLoading", false);
        });
    },
    // 初始化工种信息
    getEngineeringWorkList() {
      //     this.engineeringWorkList = [
      //   { text: "桥隧工", value: "QiaoSuiGong" },
      //   // { text: "测量工", value: "CeLiangGong" },
      //   { text: "线路工", value: "XianLuGong" }
      // ];
      this.$_http
        .get(this.$_API.JTXT_GET_ENGINEERINGWORK_LIST)
        .then(res => {
          this.engineeringWorkList = res.data;
          this.engineeringWorkList.forEach(element => {
            element["text"] = element.name;
            element["value"] = element.name;
          });
          //   选择工作列表
          this.engineeringWorkChooseValue =
      this.chooseEngneeringWork && this.chooseEngneeringWork.value
        ? this.chooseEngneeringWork.value
        : this.engineeringWorkList[0].value;
          this.handleChangeEngneeringWorkFun(this.engineeringWorkChooseValue);
        })
        .catch(() => {
          this.$store.commit("toggleLoading", false);
        });
    },
    // 操作：选择了工种
    handleChangeEngneeringWorkFun(value) {
      let resultItem = null;
      for (let i = 0; i < this.engineeringWorkList.length; i++) {
        let item = this.engineeringWorkList[i];
        if (value === item.value) {
          resultItem = item;
          break;
        }
      }
      this.$store.commit("updateUserItemStore", {
        field: "chooseEngneeringWork",
        value: resultItem
      });
    },
    // 获取蓝信签名和鉴权
    getLanXinSignature() {
      this.$store.commit("toggleLoading", true);
      let params = {
        url: this.$route.fullPath
      };
      this.$_http
        .get(this.$_API.JTXT_GET_LAN_XIN_SIGNATURE, { params })
        .then(res => {
          console.log("蓝信签名---" + JSON.stringify(res));
          lx.config({
            appId: process.env.VUE_APP_LANXIN_APPID,
            timestamp: res.data.timestamp,
            nonceStr: res.data.noncestr,
            signature: res.data.signature
          });
        })
        .catch(() => {
          this.$store.commit("toggleLoading", false);
        });
    },
    // 获取蓝信免登陆授权吗
    getLanXinCode() {
      console.log("getLanXinCode--code-");
      lx.biz
        .getAuthCode({
          appId: process.env.VUE_APP_LANXIN_APPID
        })
        .then(res => {
          let authCode = res.authCode;
          this.getLanXinUserInfo(authCode);
        });
    },
    // 获取蓝信用户信息
    getLanXinUserInfo(authCode) {
      let params = { authCode: authCode };
      this.$_http
        .get(this.$_API.JTXT_GET_LAN_XIN_USER_INFO, { params })
        .then(res => {
          console.log("蓝信用户信息---" + JSON.stringify(res));
        })
        .catch(() => {
          this.$store.commit("toggleLoading", false);
        });
    },
    // 蓝信API调用例子
    lanXinTest() {
      lx.biz.chooseContacts(
        {
          title: "选择人员", // 选择窗体标题
          multiple: true, // 是否允许多选
          type: ["friend", "staff", "sector"], // 选择人员窗体tab选项卡类型，friend 好友，staff 组织人员， sector 组织部门
          canChooseExternal: false, // 是否可以选择跨组织的外部人员
          max: 10, // 可选最大数量，当允许多选时生效，默认根据当前组织云控配置
          maxTip: "最多选择10人", // 选择数量超出最大限制提示
          existentStaffs: [], // 已选择的人员staffId列表
          existentSectors: [], // 已选择的部门sectorId列表
          requiredStaffs: [], // 默认选中的人员staffId列表，不可取消选中
          selectGroupMembers: false // 是否默认选中群成员，仅在群入口生效，默认false
        },
        success => {},
        fail => {}
      );
    }
  }
};
</script>

<style lang="scss" scoped>
.home-box {
  height: 100%; // 不要设置vh，手机浏览器计算问题
  padding-bottom: 2rem; // 多2em，避免tab栏挡住内容
}
</style>
<style lang="scss">
</style>
