<template>
  <div class="swiper-container">
    <div v-show="(slideNum - 1) !== activeIndex" v-if="isHide" class="right-arrow">
      <img class="r1" src="~@/images/annual/right-1.png" alt />
      <img src="~@/images/annual/right-2.png" alt />
    </div>
    <div class="swiper-wrapper">
      <div v-if="!anualData.haveFlag" class="swiper-slide">
        <Card1No :anualData="anualData"></Card1No>
      </div>
      <div v-if="anualData.haveFlag" class="swiper-slide">
        <Card1 :anualData="anualData"></Card1>
      </div>
      <div v-if="anualData.haveFlag" class="swiper-slide">
        <Card2 :anualData="anualData"></Card2>
      </div>
      <div v-if="anualData.orderNum && anualData.haveFlag" class="swiper-slide">
        <Card3 :anualData="anualData"></Card3>
      </div>
      <div v-if="anualData.learnEarliestTimeFlag && anualData.haveFlag" class="swiper-slide">
        <Card4 :anualData="anualData" type=1></Card4>
      </div>
      <div v-if="anualData.learnLatestTimeFlag && anualData.haveFlag" class="swiper-slide">
        <Card4 :anualData="anualData" type=2></Card4>
      </div>
      <div v-if="anualData.learnTime4Show && anualData.haveFlag" class="swiper-slide">
        <Card4 :anualData="anualData" type=3></Card4>
      </div>
      <div v-if="anualData.haveFlag" class="swiper-slide">
        <Card5 :anualData="anualData"></Card5>
      </div>
      
      <div v-if="anualData.haveFlag" class="swiper-slide">
        <Card6 :anualData="anualData" :isHide="isHide" :appVersion="appVersion" @save="savePage2Picture" @share="share"></Card6>
      </div>
    </div>
    <Loading v-show="showLoading" />
  </div>
</template>
<script>
import Loading from "@/components/common/common-loading";
import { Progress, Toast } from "vant";
import { getWebPageUrl } from "@/utils";
import { mapGetters, mapActions } from "vuex";
import Swiper from "swiper";

import Card1 from "@/components/annual-summary/card-1";
import Card1No from "@/components/annual-summary/card-1-no";
import Card2 from "@/components/annual-summary/card-2";
import Card3 from "@/components/annual-summary/card-3";
import Card4 from "@/components/annual-summary/card-4";
import Card5 from "@/components/annual-summary/card-5";
import Card6 from "@/components/annual-summary/card-6";

let _this = null,
  swiperInstance = null;

export default {
  components: {
    Loading,
    Card1,
    Card1No,
    Card2,
    Card3,
    Card4,
    Card5,
    Card6
  },
  data() {
    return {
      token: "",
      isWeb: window.__isWeb,
      isInfresh: false,
      showLoading: false,
      isHide: true,
      activeIndex: 0,
      slideNum: 1,
      appVersion: '',
      anualData: {
        orderNum: 0,
        learnTime4Show: 0
      },
      backBDList: [
        {
          desc: '第一次注册',
          text: '#firstMeet#第一次注册',
          isShow: true,
        },
        {
          desc: '学习总时长',
          text: '#studyTime#学习总时长',
          isShow: true,
        },
        {
          desc: '找药',
          text: '#findMedicine#找药',
          isShow: true,
        },
        {
          desc: '早起',
          text: '#morning#早起',
          isShow: true,
        },
        {
          desc: '夜深了',
          text: '#night#夜深了',
          isShow: true,
        },
        {
          desc: '中午',
          text: '#middle#中午',
          isShow: true,
        },
        {
          desc: '云鹊豆',
          text: '#manyBean#获得豆子',
          isShow: true,
        },
        {
          desc: '最终页面',
          text: '#final#最终页面',
          isShow: true,
        },
      ],
    };
  },

  computed: {
    ...mapGetters(["userInfo"])
  },

  created() {
    _this = this;

    // 全局埋点--对外埋点
    this.$sendBuriedData({
      action: "ACTION_WEB_ENTER",
      component_tag: `560#0`
    });

    // 截屏时通知前端
    window.__screenCaptureEvent = function() {
      console.log("in screenCaptureEvent");
      _this.$sendBuriedData({
        action: "ACTION_SCREEN_SHOT",
        component_tag: "559#559003"
      });
    };

    // 保存图片的回调
    window.__savePage2Picture = function(param) {
      _this.isHide = true;
      console.log("__savePage2Picture", param);
    };

    // 先调用存储权限（只有安卓手机需要）
    this.isAndroid && rocNative.openExternalStoragePermission();

    window.__getUserInfoAS = function(param) {
      console.log("__getUserInfoAS", param);
      _this.token = param.userToken;
      _this.appVersion = (param.appVersion || '').split('.').join('');
      _this.setUserInfo(param);
      _this.checkToken();
      _this.initData();
    };
    if (_this.isWeb) {
      _this.initData();
    }
    window.__refresh = function() {
      _this.isInfresh = true;
      _this.getUserInfo();
    };
  },

  mounted() {
    _this.getUserInfo();
  },

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

    // 先构造埋点的基础数据
    handle4DBText() {
      let anualData = this.anualData;
      if(!anualData) return;
      let slideNum = 8;
      // 如果没有数据，则直接设置埋点数据
      if(!anualData.haveFlag) {
        this.setBackBDText('#newUser#21年用户');
        slideNum = 1;
        return;
      }
      // 如果订单为空，则没有找药页面
      if(!anualData.orderNum) {
        this.backBDList[2].isShow = false;
        slideNum --;
      }
      // 没有早起
      if(anualData.learnEarliestTimeFlag == 0) {
        this.backBDList[3].isShow = false;
        slideNum --;
      }
      // 没有晚睡
      if(anualData.learnLatestTimeFlag == 0) {
        this.backBDList[4].isShow = false;
        slideNum --;
      }

      // 早晚都没有时间点
      if(anualData.learnTime4Show == 0) {
        this.backBDList[5].isShow = false;
        slideNum --;
      }

      // 没有云鹊豆
      if(anualData.creditNum == 0) {
        this.backBDList[6].text = '#noBean#未得豆子';
      }
      this.slideNum = slideNum;
      console.log('this.slideNum', this.slideNum);
    },

    // 根据当前页面ID，设置埋点数据
    setBackBDTextByAID(activeIndex) {
      let backBDList = this.backBDList, index = -1;
      for(let i = 0, l = backBDList.length; i < l; i ++) {
        if(backBDList[i].isShow) {
          index ++;
          if(index == activeIndex) {
            console.log('in setBackBDTextByAID', backBDList[i].text);
            this.setBackBDText(backBDList[i].text);
            break;
          }
        }
      }
    },

    // 获取数据
    initData() {
      let param = {
        token: this.token || "1C6B1E90B51248AEA7F28C118828074B",
        yearType: "2020",
        setEntry: true
      };
      this.showLoading = true;
      this.GET(`stats/year/end/report/app`, param).then(res => {
        if (res.code == "000000") {
          this.handlerDate(res.data || {});
          this.handle4DBText();
          this.$forceUpdate();
          this.$nextTick(() => {
            setTimeout(() => {
              this.showLoading = false;
              this.initSwiper();
            }, 100);
          });
        } else {
          Toast(res.message);
        }
      });
    },

    // 对数据进行处理
    handlerDate(anualData) {
      let learnTime4Show = 0,
        loginTotalTime = 0,     // 学习时长：秒
        loginTotalTimeM = 0,    // 分钟
        loginTotalTimeH = 0,    // 小时
        orderTotalAmount = 0,   // 分
        orderTotalAmountY = 0;  // 元
      if (anualData.learnEarliestTimeFlag == 1) {
      } else if (anualData.learnLatestTimeFlag == 1) {
      } else if(anualData.learnEarliestTimeFlag == 0 && anualData.learnLatestTimeFlag == 0){
        learnTime4Show =
          anualData.learnEarliestTime || anualData.learnLatestTime;
      }
      anualData.learnTime4Show = learnTime4Show;

      loginTotalTime = anualData.loginTotalTime || 0;
      if (loginTotalTime) {
        loginTotalTimeM = Math.floor(loginTotalTime / 60);
        loginTotalTimeH = Math.floor(loginTotalTime / 60 / 60);
      }
      anualData.loginTotalTimeM = loginTotalTimeM;
      anualData.loginTotalTimeH = loginTotalTimeH;

      orderTotalAmount = anualData.orderTotalAmount || 0;
      if (orderTotalAmount) {
        orderTotalAmountY = (orderTotalAmount / 100).toFixed(2);
      }
      anualData.orderTotalAmountY = orderTotalAmountY;
      this.anualData = anualData;
    },

    // 初始化Swiper
    initSwiper() {
      swiperInstance = new Swiper(".swiper-container", {
        // direction: "vertical",
        speed: 300,
        slidesPerView: 1,
        observer: true, //修改swiper自己或子元素时，自动初始化swiper
        observeParents: true, //修改swiper的父元素时，自动初始化swiper
        // // slidesPerGroup : 5,
        on: {
          init: function() {
            swiperAnimateCache(this);
            console.log("---111");
            swiperAnimate(this);
          },
          slideChangeTransitionEnd: function(se) {
            _this.activeIndex = se.activeIndex;
            swiperAnimate(this);
            _this.setBackBDTextByAID(se.activeIndex);
            console.log("@@@@@@_this.activeIndex", _this.activeIndex);
          }
        }
      });
    },

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

    // 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();
            this.$router.back(-1);
          } else {
            rocNative.gotoLogin();
          }
          this.isInfresh = false;
        } else {
        }
      });
    },

    // 保存图片
    savePage2Picture() {
      this.isHide = false;
      this.$sendBuriedData({
        component_tag: '560#560002'
      });
      this.$forceUpdate();
      setTimeout(() => {
        this.$nextTick(() => {
          rocNative.savePage2Picture({
            __funcName: "__savePage2Picture"
          });
        });        
      }, 100);
    },

    // 调用原生分享（弹框）
    share() {
      let shareUrl = getWebPageUrl(
        `annualsummary/#/as-share?uuid=${this.anualData.uuid}&from=h5`
      );
      rocNative &&
        rocNative.shareWechat({
          type: 6,
          shareId: 0,
          shareUrl: shareUrl,
          title1: "云鹊医2020年度个人学习报告",
          title2: "点击查看我的专属学习报告",
          shareImageUrl:
            "https://file.yunqueyi.com/logo.png?version=" + new Date().getTime()
        });
    },

    beforeDestroy() {
      console.log("in beforeDestroy");
      swiperInstance.destroy(true);
    }
  }
};
</script>

<style lang="less" scoped>
// background: red;
.swiper-container {
  transform: translate3d(0, 0, 0);
  overflow: hidden;
  .right-arrow {
    display: flex;
    flex-direction: row;
    position: fixed;
    width: 40px;
    height: 36.5px;
    top: 50%;
    right: 6px;
    z-index: 4;
    margin-top: -18px;
    animation: right-arrow 1.5s infinite;
    -webkit-animation: right-arrow 1.5s infinite;
    -webkit-animation-fill-mode: both;
    img {
      width: 24px;
      height: 100%;
      &.r1 {
        margin-right: -12px;
      }
    }
  }
  @keyframes right-arrow {
    0% {
      right: 7px;
      opacity: 0.8;
    }
    50% {
      right: 3px;
      opacity: 0.9;
    }
    100% {
      right: 0;
      opacity: 1;
    }
  }
  @-webkit-keyframes right-arrow {
    0% {
      right: 10px;
      opacity: 0.8;
    }
    50% {
      right: 5px;
      opacity: 0.9;
    }
    100% {
      right: 0;
      opacity: 1;
    }
  }
}
.swiper-slide {
  transform: translate3d(0, 0, 0);
}

.swiper-container {
  height: 100vh;
  width: 100%;
  /* height: 300px;
  margin: 20px auto; */
}
.card {
  height: 100vh;
}
</style>