<template>
  <div class="container">
    <Header
      :isWeb="isWeb"
			:token="token"
			:is-scroll="isScroll"
			:share-title1="shareTitle1"
			:share-title2="shareTitle2"
			:share-icon-url="shareIconUrl"
      :isShowRightIcon="isShowRightIcon"
      :tempId="activityId"
      :userName="userName"
      :encryptId="encryptId"
      :avatarl="myAvatarl"
      :taskId="taskId"
		/>
    <!-- 顶部 -->
    <div class="top-container">
      <img class="rule" @click="ruleDetail" src="../static/images/rule.png" />
      <img class="rank" @click="gotoRank" v-bp="{ component_tag: '360#360003'}" src="../static/images/rank.png" />
      <!-- 勤奋分进度 -->
      <div class="progress-container">
        <div class="score-info">
          <div v-if="userMobile" class="text">
            <img :src="myAvatarl" />
            <span class="tc">我的勤奋分<span>{{myScore}}</span></span>
            <span class="bt" @click="selfInfo" v-bp="{ component_tag: '360#360002'}">个人明细 ></span>
          </div>
          <div v-if="!userMobile" class="text">
            <span class="tc">登录可参加活动</span>
            <span class="bt" @click="goToLogin">去登录 ></span>
          </div>
        </div>
        <status-bar 
        class="progress-bar"
        :userMobile="userMobile"
        :minValue="myScore"
        :maxValue="maxValue"/>
      </div>
    </div>
    
    <!-- 活动阶段 -->
    <img class="title-text st" src="../static/images/step-title.png"/>
    <div class="activity-step">
      <div class="step bt">
        <step 
        :stepFlag="stepFlag"
        :imgSrc="imgSrc1"
        :numText="numText1"
        :stepText="stepText1"
        :stepTime="stepTime1"/>
        <task-activity
        v-if="taskTimeFlag"
        :isWeb="isWeb"
        :acToken="token"
        :userMobile="userMobile"
        :acTempId="activityId"
        @activityTaskJump="activityTaskJump"
        @getTaskId="getTaskId" 
        @firstEnterActivity="firstEnterActivity"/>
      </div>
      <div class="step bt">
        <step 
        :imgSrc="imgSrc2"
        :numText="numText2"
        :stepText="stepText2"
        :stepTime="stepTime2"/>
      </div>
      <div class="step">
        <step 
        :imgSrc="imgSrc3"
        :numText="numText3"
        :stepText="stepText3"
        :stepTime="stepTime3"/>
      </div>
    </div>
    <img class="title-text" src="../static/images/award.png"/>
    <!--瓜分云鹊豆模块———start-->
    <carve-up
      v-if="showCarveUp"
      :isFirstCarve="isFirstCarve"
      :hasQualification="hasQualification"
      :beanCarveCount="beanCarveCount"
      :unableReason="unableReason"
    >
    </carve-up>
    <!--瓜分云鹊豆模块 ————end-->
    <!--首次进入活动任务弹框———start-->
    <first-enter-dialog
      v-if="showFirstEnter"
      :beanNum="beanNum"
      @handlerCancel="cancelFirstEnter"
    >
    </first-enter-dialog>
    <!--首次进入活动任务弹框———end-->
  </div>
</template>

<script>
import TaskActivity from '../components/task-activity';
import Header from '../components/header/index';
import Step from '../components/step';
import StatusBar from '../components/bussiness/status-bar';
import CarveUp from '../components/carve-up';
import FirstEnterDialog from '../components/first-enter-dialog';
import { 
  checkToken, 
  selectAppModuleParam,
  getSelfAllScore,
  checkFirstEnter,
  getEncryptId,  
  getActivityTime,
  inviteFirstEnter,
  getCarveStatus,
  getRedPacketsLog } from "@/service";
import { setEventByModuleCode } from "@/utils"
import { ENV_CONFIG } from '@/utils/enumerate';
import { Base64 } from 'js-base64';
import { setCookie, getCookie, delCookie } from '@/utils/index';

export default {
  components: {
    TaskActivity,
    Header,
    Step,
    StatusBar,
    CarveUp,
    FirstEnterDialog
  },
  data() {
    return {
      taskTimeFlag: true, // 任务在有效时间内
      isShowRightIcon: true, // 是否显示分享按钮
      isLogin: false,
      userMobile: '',
      stepFlag: true,
      isWeb: false,
      activityId: 0,
      token: '',
      shareTitle1: '',
      shareTitle2: '做任务瓜分500W云鹊豆，点一下你也能获得75分哦',
      shareTitle3: '',
      shareTitle4: '',
      shareIconUrl: 'https://file.yunqueyi.com/h5/images/commons/share_hd1.png',
      isScroll: false,
      imgSrc1: require('@/static/images/score.png'),
      numText1: 1,
      stepText1: '做任务拿勤奋分',
      stepTime1:'3月25日10:00-4月6日24:00',
      imgSrc2: require('@/static/images/beans.png'),
      numText2: 2,
      stepText2: '瓜分云鹊豆',
      stepTime2:'4月7日17:00-4月11日24:00',
      imgSrc3: require('@/static/images/get-award.png'),
      numText3: 3,
      stepText3: '公布排名获奖名单',
      stepTime3:'4月7日17:00-4月11日24:00',
      maxValue: 200,
      myAvatarl: '',
      myScore: 0,
      showCarveUp: false, //是否展示瓜分弹框
      userId: '',
      userName: '',
      taskId: '',
      origin: 'tims',
		  encryptId: '',
      showFirstEnter: false, //是否展示第一次进入获得勤奋分弹框
      beanNum: 0, //第一次进入奖励弹框的奖励额度
      isFirstCarve: true, //红包是否是未拆状态
      hasQualification: true, //是否有资格瓜分
      beanCarveCount: 0, //可瓜分云鹊豆数量
      unableReason: 0, //不可瓜分的原因，1或2是资格不够，3或4是未参加
    }
  },
  async asyncData({ $axios }) {

  },
  created() {
    
  },
  mounted() {
    let _this = this;
    if (process.client) {
      _this.activityId = _this.$route.query.id || 9;
      _this.isWeb = _this.$rocNative.isWeb;
      window.__refresh = function() {
        _this.getUserInfo();
      }
    }
    if(!_this.isWeb && _this.$rocNative.appInit()){
			_this.getUserInfo();
    };
    _this.getActivityTime();
    _this.$sendBuriedData({ 
      action: '查看量',
      component_tag: '360#360000'
    });
  },
  methods: {
    // 获取服务器当前时间
    getActivityTime() {
      getActivityTime().then(res => {
        if(res.code == '000000') {
          let nowTime = res.data;
          let lastTime =  (new Date("2020/04/06 24:00:00")).getTime();
          if(lastTime < nowTime) {
            this.taskTimeFlag = false;
          }
          //判断是否到瓜分云鹊豆的时间
          let carveTime = (new Date("2020/04/07 17:00:00")).getTime();//"2020/04/07 17:00:00"
          if (carveTime <= nowTime) {
            this.getRedPacketsLog();
          }
        }
      });
    },
    // 首次进入活动页面
    firstEnterActivity(data) {
      checkFirstEnter({
        activityId: this.activityId
      }).then(res => {
        if(res.data == 1) {  //0未知，1第一次 2非第一次
          this.beanNum = data.firstEnterScore;
          this.showFirstEnter = true;
        }
      })

    },
    getUserInfo() {
			this.$rocNative
				.getUserInfo()
				.then(params => {
					let _t = params.userToken;
					let _this = this;
          _this.token = params.userToken;
          delCookie('token');
          setCookie('token', _this.token);
					checkToken({ _t }).then(res => {
						if(res.code == '200000' || res.code == '200006') {
              _this.userMobile = '';
              delCookie('token');
						}else {
              _this.userMobile = params.userMobile;
              delCookie('token');
              setCookie('token', _this.token);
              _this.getSelfAllScore();
              _this.getEncryptId();
						}
					})
				});
    },
    // 获取加密后的doctorId
    getEncryptId() {
      getEncryptId().then(res => {
        if( res.code == '000000' ){
          this.encryptId = res.data;
        }
      })
    },
    // 获取个人信息
    getSelfAllScore() {
      let _this = this;
      getSelfAllScore({ id: this.activityId, token: this.token }).then(res => {
        if(res.code == '000000') {
          _this.myAvatarl = res.data.avatarImageUrl;
          _this.myScore = res.data.totalScore;
          _this.userId = res.data.id;
          _this.userName = res.data.name;
          _this.shareTitle1 = `${_this.userName}医生邀请您为他助力`;
        }
      })
    },
    // 查看活动规则
    ruleDetail() {
      // this.$router.push({path: "/login-point/point-result",query: {}});
    },
    // 查看排名
    gotoRank() {
      if(getCookie('token')) {
        let queryData = {
            id: this.activityId,
            token: this.token
        };
        this.$router.push({path: "/ranks",query: queryData});
      }else {
        this.$rocNative.goToLogin();
      }
    },
    // 去登录
    goToLogin() {
      this.$rocNative.gotoLogin();
    },
    // 查看个人明细
    selfInfo() {
      let queryData = {
          id: this.activityId, 
          avatarImage: this.myAvatarl, 
          score: this.myScore,
          token: this.token
        };
      this.$router.push({path: "/perdetails",query: queryData});
    },
    // 获取点赞任务id
    getTaskId(data) {
      this.taskId = data.taskId;
      this.inviteFirstEnter();
    },
    // 点赞后进入活动主页
    inviteFirstEnter() {
      inviteFirstEnter({taskId: this.taskId, activityId: this.activityId}).then(res => {});
    },
    // 活动任务
		activityTaskJump(data) {
      let shareUrl = '';
      const { NUXT_ENV_APP } = process.env;
      if(data.resourceType == 11) {  // 邀请好友点赞
        const { activityId, token, encryptId, userName, myAvatarl, shareTitle1, shareTitle2, shareIconUrl } = this;
        shareUrl = ENV_CONFIG[NUXT_ENV_APP]['shareUrl'] + `/compaign_ssr/login-point?activityId=${activityId}&taskId=${data.id}&id=${encryptId}&name=${userName}&avatar=${myAvatarl}`;
        //shareUrl = `http://10.177.10.217:3000/compaign_ssr/login-point?activityId=${activityId}&taskId=${data.id}&id=${encryptId}&name=${userName}&avatar=${myAvatarl}`;
        this.$rocNative.shareWechat({
          type: 6,
          shareId: 0,
          shareUrl: shareUrl,
          title1: shareTitle1,
          title2: shareTitle2,
          shareImageUrl: shareIconUrl || 'https://file.yunqueyi.com/logo.png?version=' + new Date().getTime()
        });
      }else if(data.resourceType == 9) { // 绑定居民微信
        const { userId, origin, activityId, shareTitle3, shareTitle4, shareIconUrl } = this;
        let doctorId = Base64.encode(userId);
        shareUrl = `${ENV_CONFIG[NUXT_ENV_APP]['shareUrl']}/active_news/activity/qrcode?doctorId=${doctorId}&origin=${origin}&activityId=${activityId}&taskId=${data.id}`;
        this.$rocNative.shareWechat({
          type: 6,
          shareId: 0,
          shareUrl: shareUrl,
          title1: shareTitle3,
          title2: shareTitle4,
          shareImageUrl: shareIconUrl || 'https://file.yunqueyi.com/logo.png?version=' + new Date().getTime()
        });
      }else {
        this.jumpPage(data.href, data.id);
      }
    },
    async jumpPage(url, id) {
			const _this = this;
			if (!!url) { // 判断是否有跳转
				const { token, isWeb } = _this;
				const { data } = await selectAppModuleParam({
					id: url,
					token
				});
				const itemData = data.model;
        // 增加点击图片时候，是否有loginFlag参数，有，则校验并登录。如未登录去登录，已登录，老逻辑。
        const loginFlag = this.checkLoginFlag(itemData.paramList);
        if(loginFlag){
          _this.$rocNative.getToken().then(res => {
            const { userToken } = res;
            checkToken({ token: userToken }).then(res=>{
              if(res.code == '200000' || res.code == '200006') {
                _this.$rocNative.gotoLogin();
              }else{
                _this.oldJumpHandle(itemData, userToken);
              }
            })
          });
        }else{
          _this.oldJumpHandle(itemData, _this.token);
        }
      }
    },
    // 原先的点击图片跳转逻辑
		oldJumpHandle(itemData, token){
			if (itemData.code == 'M301') {
				itemData.code = 'M300';
				this.$rocNative.getToken().then(res => {
					const { userToken } = res;
					setCookie('token', userToken);
				});
			} else {
				const paramList = setEventByModuleCode(
					itemData,
					token
				);
				this.$rocNative.dispatchEventByModuleCode({
					modeCode: itemData.code,
					jsonString: paramList
				});
			}
		},
		// 增加一个点击图片请求selectAppModuleParam这个接口时候的 loginFlag 字段校验
		checkLoginFlag(paramList){
			let flag = false;
			for(let i=0;i<paramList.length;i++){
				if(paramList[i].key === 'loginFlag' && paramList[i].value === '1'){
					flag = true;
					break;
				}
			}
			return flag;
		},
    cancelFirstEnter(val) { //关闭首次进入活动奖励弹框
      this.showFirstEnter = val;
    },
    getCarveStatus() { //第一次拆红包
      getCarveStatus({
        activityId: this.activityId
      }).then(res => {
        this.isFirstCarve = false;
        if(res.data.stauts == 1) { //可以参加
          this.hasQualification = true;
          this.beanCarveCount = res.data.totalBonus;
        } else { //2分数不够，3未参加
          this.hasQualification = false;
          this.unableReason = res.data.status;
        }
      })
    },
    getRedPacketsLog() { //判断瓜分红包状态
      getRedPacketsLog({
        activityId: this.activityId
      }).then(res => {
        if(res.data.status == 2) { //红包未拆
          this.isFirstCarve = true;
          this.getCarveStatus(); //去拆红包
        } else {
          this.isFirstCarve = false;
          if(res.data.status == 3) {
            this.hasQualification = true;
            this.beanCarveCount = res.data.totalBonus;
          } else { //1分数不够，4未参加
            this.hasQualification = false;
            this.unableReason = res.data.status;
          }
        }
        this.showCarveUp = true;//展示瓜分组件
      })
    }
  } 
}
</script>

<style lang="less">
.container {
  margin: 0 auto;
  min-height: 100vh;
  background: #B72541;
  .top-container {
    position: relative;
    width: 100%;
    height: 430px;
    background-image:url('../static/images/head_bg.png');
    background-size: 100% 100%;
    .rule {
      position: absolute;
      top: 75px;
      right: 0px;
    }
    .rank {
      position: absolute;
      top: 115px;
      right: 15px;
    }
    .progress-container {
      position: absolute;
      left: 0;
      top: 330px;
      width: 94%;
      margin: 0px 10px 15px;
      .score-info {
        padding: 0 17px;
        height: 48px;
        background:linear-gradient(180deg,rgba(214,86,53,1) 0%,rgba(189,38,65,1) 100%);
        border-radius:10px 10px 0px 0px;
        .text {
          line-height: 48px;
          img {
            float: left;
            width: 30px;
            height: 30px;
            padding: 10px 10px 0px 0px;
          }
          span.tc {
            font-size: 14px;
            font-weight: 700;
            color: #fff;
            span {
              padding-left: 10px;
              font-size: 18px;
              color: #FFE8A5;
            }
          }
          span.bt {
            font-size: 12px;
            float: right;
            color:#FFE8A5;
          }
        }
      }
      .progress-bar {
        padding: 5px 17px;
        height: 87px;
        border-radius: 0px 0px 10px 10px;
      }
    }
  }
  .title-text {
    width: 100%;
  }
  .title-text.st {
    margin-top: 65px;
  }
  .activity-step {
    margin: 0 10px 15px;
    border-radius: 5px;
    background: #9A1F36;
    .step {
      margin: 0 10px;
    }
    .step.bt {
      border-bottom: 1PX solid #FFE0D9;
    }
  }
  
}
</style>
