<template>
  <div class="bottomAll">
    <div class="time-range" v-if="status==='initial' || status==='none'">
      <div v-if="activity" :style="activityShow === true ? activityCss : null">
        {{activityName}}{{ activity.startTime |dateTime }} 至 {{ activity.endTime|dateTime }}
      </div>
    </div>
    <div class="gate-block" v-if="status==='initial'">
      <Button class="start-button" v-if="btnShareStatus" @click="setShareButton">分享给好友</Button>
      <Button class="start-buttont" :disabled="true" v-if="btnStatus==='receive4'">奖品已经被领光啦</Button>
      <Button class="start-button" @click="getPrize" v-if="btnStatus==='receive3'">领取奖品</Button>
      <Button class="start-buttont" :disabled="true" v-if="btnStatus==='receive2'">您已经领取过奖品啦</Button>
      <Button class="start-button" :disabled="true" v-if="btnStatus==='receive1'">
        领取奖品<span style="font-size: 0.19rem">(还差{{this.lackCount}}次助力)</span>
      </Button>
      <p class="tip" v-if="tip">{{ tip }}</p>
    </div>
    <div class="gridCss">
        <div  style="width:100%;" v-if="status==='initial'">
          <van-grid :border="false" :column-num="2" :gutter="11">
            <van-grid-item
              v-for="(item,index) in gridtextlist"
              :key="index">
                <img class="shaPictureimgNameCss" :src="item.img" @click="imageClick(item)"  />
                <div class="shaPictureCss" >
                  <div class="shaPictureNameCss" >
                    <span >{{item.title}}</span>
                  </div>
                </div>
            </van-grid-item>
          </van-grid>
        </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import {Button,Grid, GridItem} from "vant";
Vue.use(Grid);
Vue.use(GridItem);
import {callShare4MiniProgram} from '../../../util/share';
import apis1 from '../../../util/apis1.js';
import dateUtil from "../../../util/dateUtil.js";
import { getUrlQueryValueByKey } from '../../../util/tools.js';
import store from '../../../store/store.js';
import { PrizeResultPopComService, NoPrizeFinishedPopComService } from '../../../util/comCreate.js';
import { joinVipService } from '../../../util/comCreate.js';

let { setShare,myselfBargain,immediatelyDraw1,taskShareResourceActivity,taskShareResourceClicks,checkMember} = apis1;

export default {
  props: ['isTemplate', 'datas', 'styleData', 'keyData', 'templateData'],
  components: {
      Button,
      Grid,
      GridItem
    },
     data() {
         return {
             activityShow:false,
             activityName:'活动时间:',
             activityCss:{
                 'font-size': '12px',
                 '-webkit-transform':'scale(0.85)',
                 'margin-left':'-0.1rem',
             },
           /**
            * 活动状态
            * 0：默认状态,没有含义
            * 1:活动尚未开始
            * 2:活动已结束
            * 3:活动正常进行
            */
            actStatus: '0',
             //初期活动状态
            status: 'none',
             /**
             * 奖品领取按钮状态
             * receive1: 未达到领取条件
             * receive2: 已领取
             * receive3: 可领取
             * receive4: 奖品领完了
             */
            btnStatus: null,
            //分享给好友按钮
            btnShareStatus: false,
            // 活动信息
            activity: null,
            //剩余助力次数
            lackCount:null,
            //领取奖品ID
            prizeListId:null,
            //页面提示信息
            tip: null,
            //是否是分享者本人
            myself: false,
            //视频图片列表
            gridtextlist:[],
         }
      },
      // mounted() {
      //     this.publicData.$on('activityLoaded', this.activityLoaded);
      // },
      created() {

          this.publicData.$on('activityLoaded', this.activityLoaded);
      },
     methods : {
        // 活动加载完成
        activityLoaded(data) {
          if(this.isTemplate){
              //TOOD: 预览的假数据
              this.setPreviewData(this.datas.previewData);
          }else{
              this.activity = data;
              this.setGate();
          }
        },
         // 设置入口
         setGate() {
             this.actStatus = sessionStorage.getItem("actStatus");
             if (this.actStatus === '3') {
                 this.initData("");
             }
         },
        //数据加载
        initData(message) {
            if(store.state.shareUserId !== undefined && store.state.shareUserId !== null && store.state.shareUserId !== ''){
                checkMember().then(res => {
                    if (res.resp_code == 0) {
                        if(res.data !== undefined && res.data !== null){
                            if (res.data.joinInfo !== undefined && res.data.joinInfo !== null) {
                                joinVipService.create(res.data, submit => {
                                    joinVipService.close();
                                    return;
                                });
                            }
                        }
                        else{
                            taskShareResourceActivity({
                                //shareUserId
                                shareUserId: store.state.shareUserId
                            }).then(rest => {
                                this.initSetData(rest,message);
                            });
                        }
                    }
                });
            }
            else{
                taskShareResourceActivity({
                    //shareUserId
                    shareUserId: store.state.shareUserId
                }).then(res => {
                    this.initSetData(res,message);
                });
            }
        },

        initSetData(res,message){
             if (res.resp_code == 0) {

                 if(message != ""){
                     //未达到领取条件
                     this.$toast({
                         duration: 0, // 持续展示 toast
                         forbidClick: true,
                         message: message,
                     });
                     //3秒后消失
                     var x = setTimeout(() => {
                         this.publicData.$emit('follow', true);
                         clearTimeout(x);
                         this.$toast.clear();
                     }, 3000);
                 }
                 this.status = 'initial';
                 this.tip = '-每日首次浏览每个视频或者文章，有机会获得奖品-';
                 const data = res.data;
                 //被分享者判断
                 if(store.state.shareUserId !== undefined){
                     if(store.state.shareUserId !== ''){
                         if(data.shareFlag === "1"){
                             this.$toast({
                                 duration: 0, // 持续展示 toast
                                 forbidClick: true,
                                 message: '助力成功',
                             });
                             sessionStorage.setItem(location.href ,'1');
                         }
                         else if(data.shareFlag === "2"){
                             if(!sessionStorage.getItem(location.href))
                             {
                                 this.$toast({
                                     duration: 0, // 持续展示 toast
                                     forbidClick: true,
                                     message: '您已为该好友助力过了',
                                 });
                                 sessionStorage.setItem(location.href ,'1');
                             }
                         }
                         else if(data.shareFlag === "3"){
                             if(!sessionStorage.getItem(location.href))
                             {
                                 this.$toast({
                                     duration: 0, // 持续展示 toast
                                     forbidClick: true,
                                     message: '您已为其他好友助力过了，不能再助力了！',
                                 });
                                 sessionStorage.setItem(location.href ,'1');
                             }
                         }
                         //3秒后消失
                         var x = setTimeout(() => {
                             this.publicData.$emit('follow', true);
                             clearTimeout(x);
                             this.$toast.clear()
                         }, 3000);
                     }
                 }
                 //分享给好友按钮
                 this.btnShareStatus = true;
                 //region 画面数据绑定
                 //奖品领取状态
                 if(data.flag === '001'){
                     //未达到领取条件
                     this.btnStatus = 'receive1';
                     //剩余助力次数
                     this.lackCount = data.lackCount;
                     //助力完成可领取
                     if(this.lackCount === 0){
                         //可领取
                         this.btnStatus = 'receive3';
                     }
                 }
                 else if(data.flag === '002'){
                     //已领取
                     this.btnStatus = 'receive2';
                 }
                 else if(data.flag === '003'){
                     //可领取
                     this.btnStatus = 'receive3';
                 }
                 else if(data.flag === '004'){
                     //奖品领完了
                     this.btnStatus = 'receive4';
                 }
                 //领取奖品ID
                 this.prizeListId  = data.prizeListId;
                 //视频图片列表
                 this.gridtextlist = data.taskShareResourceDetails;
                 if(this.gridtextlist.length > 2){
                     var obj = document.getElementById("index");
                     obj.style.height= "100%";
                 }
                 //endregion
             }
             else if(res.resp_code == 50009){
                 location.reload();
             }
             else if(res.resp_code == 60010){
                 this.tip = res.resp_msg;
             }
             else if(res.resp_code == 50003){
                 this.$toast({
                     duration: 0, // 持续展示 toast
                     forbidClick: true,
                     message: res.resp_msg,
                 });
                 //3秒后消失
                 var a = setTimeout(() => {
                     this.publicData.$emit('follow', true);
                     clearTimeout(a);
                     this.$toast.clear()
                 }, 3000);
             }
             else if(res.resp_code == 50023 || res.resp_code == 50024){
                 //50023:您已为该好友助力过了
                 //50024:您已为其他好友助力过了，不能再助力了
                 this.$toast({
                     duration: 0, // 持续展示 toast
                     forbidClick: true,
                     message: res.resp_msg,
                 });
                 //3秒后消失
                 var a = setTimeout(() => {
                     this.publicData.$emit('follow', true);
                     clearTimeout(a);
                     this.$toast.clear()
                 }, 3000);
             }
         },

        //领取奖品
        getPrize(){
          immediatelyDraw1(this.prizeListId, receiveData => {
            if (receiveData.resp_code == 0) {
                //领取失败提示
                if(receiveData.data.status != 1){
                    this.initData("领取失败");
                    return;
                }
                if (receiveData.data.result == true) {
                    var obj = {
                        datas: {},
                        keyData: {
                            prizeUrl: 'showImg',
                            prizeName: 'prizeName',
                            prizeType: 'prizeType',
                            priceInfo: 'priceInfo',
                            discountType: 'discountType',
                            couponType: 'couponType'
                        }
                    };
                    obj.datas = receiveData.data;
                    PrizeResultPopComService.create(obj, receiveData.data, submit => {
                        this.initData("");
                        PrizeResultPopComService.close();
                    });
                } else {
                    NoPrizeFinishedPopComService.create(
                        '奖品已领光啦~',
                        '//img10.360buyimg.com/imgzone/jfs/t1/152859/24/15591/14697/6008f58fE1744005f/765fe66b5a48aefc.png',
                        submit => {
                            this.initData("");
                            NoPrizeFinishedPopComService.close();
                        }
                    );
                }
            }
            else if (receiveData.resp_code == 50009) {
                location.reload();
            }
            else if (receiveData.resp_code == 60010) {
                NoPrizeFinishedPopComService.create(
                    '奖品已领光啦',
                    '//img10.360buyimg.com/imgzone/jfs/t1/152859/24/15591/14697/6008f58fE1744005f/765fe66b5a48aefc.png',
                    submit => {
                        this.initData("");
                        NoPrizeFinishedPopComService.close();
                    }
                );
            }
          });
        },

        //点击图片查看视频
        imageClick(item){
            if(item.id === undefined){
                window.open(item.link);
                return;
            }
            taskShareResourceClicks({
              // 采集信息（活动设置采集信息且用户之前未采集时必传）
              resourceId: item.id,
            }).then(res => {
                if (res.resp_code == 0) {
                    const data = res.data;
                    if(data.beanNum != undefined && data.prizeName){
                        //1.5秒后消失
                        this.$toast({
                            duration: 0, // 持续展示 toast
                            forbidClick: true,
                            message: '恭喜获得' + data.prizeName,
                        });

                        //1.5秒后消失
                        var a = setTimeout(() => {
                            this.publicData.$emit('follow', true);
                            clearTimeout(a);
                            this.$toast.clear()
                            this.initData("");
                            window.open(item.link);
                        }, 3000);
                    }
                }
                else if (res.resp_code == 50009) {
                    location.reload();
                }
                else{
                    window.open(item.link);
                }
            });
        },

        /**
         * 活动状态.
         * 1:活动尚未开始
         * 2:活动已结束
         * 3:活动进行中
         */
        setShareButton() {
          if(this.isTemplate) {//非预览模式
              this.$toast('活动预览，仅供查看');
              return;
          }
          // 1.从sessionStroage中取得活动的状态.
          let actStatus = sessionStorage.getItem('actStatus');

          if (!this.isTemplate) {//不是模板的场合.
            if (actStatus == 2) {
              this.$toast('活动已结束');
              return;
            }
            if (actStatus == 1) {
              this.$toast('活动尚未开始');
              return;
            }
            if (actStatus == 3) {//活动进行中
              setShare(data => {
                var cur_url = location.href;
                var shareUserId = getUrlQueryValueByKey('shareUserId', cur_url);
                var aUrl = cur_url.substring(0, cur_url.indexOf('shareUserId') + 1);
                if (shareUserId) {
                  var invitionUrl = aUrl + '&shareUserId=' + data.data.shareUserId;
                } else {
                  var invitionUrl = location.href + data.data.shareUserId;
                }
                //Test
                store.state.clientType = '01';
                if (store.state.clientType == '01') {
                  var title = store.state.shareTitle;
                  var content = store.state.shareTitle;
                  var logoUrl = store.state.shareImage;
                  var mpIconUrl = store.state.shareImage;

                  var isHeader = false; //false 头部分享 true 按钮分享
                  var url = invitionUrl;
                  var shopid = store.state.shopId;
                  var userpin = store.state.userPin;
                  var jdactivityid = store.state.jdActivityId;
                  console.log("分享口令url  " + url);
                  callShare4MiniProgram(
                    title,
                    content,
                    url,
                    logoUrl,
                    callBack => {
                      console.log('测试分享');
                    },
                    isHeader,
                    mpIconUrl,
                    shopid,
                    userpin,
                    jdactivityid
                  );
                }
              });
            }
          }else {
             this.show = true;
             this.url = invitionUrl.replace('index/', '');
          }
        },
         // 设置预览数据
        setPreviewData(data) {
            this.status = 'initial';
            //手机预览的情况
            let letBrowser = this.getBrowser();
            if(letBrowser.plat === "android" || letBrowser.plat === "iphone"){
            }
            else{
                this.activityShow = true;
                this.activityName = '活动时间:';
            }
            //分享给好友按钮
            this.btnShareStatus = true;
            //未达到领取条件
            this.btnStatus = 'receive1';
            //视频文章预览
            this.gridtextlist = data.gridtextlist;
            //剩余助力次数
            this.lackCount = 2;
            this.tip = '-每日首次浏览每个视频或者文章，有机会获得奖品-';
            if(this.gridtextlist.length > 2){
                var obj = document.getElementById("index");
                obj.style.height= "110vh";
            }
        },
         //判断是否手机端浏览
         getBrowser(){
             var ua = navigator.userAgent.toLowerCase();
             var btypeInfo = (ua.match( /firefox|chrome|safari|opera/g ) || "other")[ 0 ];
             if( (ua.match( /msie|trident/g ) || [] )[ 0 ] )
             {
                 btypeInfo = "msie";
             }
             var pc = "";
             var prefix = "";
             var plat = "";
             //如果没有触摸事件 判定为PC
             var isTocuh = ("ontouchstart" in window) || (ua.indexOf( "touch" ) !== -1) || (ua.indexOf( "mobile" ) !== -1);
             if( isTocuh )
             {
                 if( ua.indexOf( "ipad" ) !== -1 )
                 {
                     pc = "pad";
                 } else if( ua.indexOf( "mobile" ) !== -1 )
                 {
                     pc = "mobile";
                 } else if( ua.indexOf( "android" ) !== -1 )
                 {
                     pc = "androidPad";
                 } else
                 {
                     pc = "pc";
                 }
             } else
             {
                 pc = "pc";
             }
             switch( btypeInfo )
             {
                 case "chrome":
                 case "safari":
                 case "mobile":
                     prefix = "webkit";
                     break;
                 case "msie":
                     prefix = "ms";
                     break;
                 case "firefox":
                     prefix = "Moz";
                     break;
                 case "opera":
                     prefix = "O";
                     break;
                 default:
                     prefix = "webkit";
                     break
             }
             plat = (ua.indexOf( "android" ) > 0) ? "android" : navigator.platform.toLowerCase();
             return {
                 version: (ua.match( /[\s\S]+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[ 1 ],     //版本
                 plat: plat,                   //系统
                 type: btypeInfo,              //浏览器
                 pc: pc,
                 prefix: prefix,                //前缀
                 isMobile: (pc == "pc") ? false : true              //是否是移动端
             };
         },
     },

      filters: {
          //时间转换
          dateTime(val) {
              if (val) {
                  return dateUtil.formatTime(val, 'yyyy-MM-dd hh:mm');
              }
              return val;
          }
      }
};
</script>

<style lang="scss" scoped>
.bottomAll{
    background-image: url('//img10.360buyimg.com/imgzone/jfs/t1/108784/13/29053/654203/62943844Eae805673/6524ac32926ce81b.png');
  width: 7.5rem;
  height: 8.54rem;
}
.time-range {
   font-size: 0.22rem;
   color: #d8e4ff;
   text-align: center;
   position: absolute;
   top: 1.65rem;
   left: 0;
   width: 100%;
 }

.shareImage {
  width: 3rem;
  height: 2rem;
}
.gate-block {
  position: absolute;
  z-index: 10;
  margin-top: -2.3rem;
  left: 50%;
  width: 100%;
  transform: translateX(-50%);
  .start-button {
    padding-top:0.06rem;
    width: 3.4rem;
    height: 0.74rem;
    background-image: linear-gradient(0deg, #fde79e 1%, #f9d489 50%, #f4c174 100%), linear-gradient(#dcaf57, #dcaf57);
    background-blend-mode: normal, normal;
    border-radius: 0.1rem;
    font-size: 0.31rem;
    font-weight: normal;
    font-stretch: normal;
    line-height: 0.36rem;
    letter-spacing: 0;
    color: #070a1e;
    border: none;

    &:disabled {
      background-image: linear-gradient(0deg, #b7b7b7 1%, #c4c4c4 50%, #d3d3d3 100%), linear-gradient(#b7b7b7, #d3d3d3);
      color: #070a1e;
      opacity: 1;
    }
  }
  .start-buttont {
    padding-top:0rem;
    width: 3.4rem;
    height: 0.74rem;
    background-image: linear-gradient(0deg, #fde79e 1%, #f9d489 50%, #f4c174 100%), linear-gradient(#dcaf57, #dcaf57);
    background-blend-mode: normal, normal;
    border-radius: 0.1rem;
    font-size: 0.30rem;
    font-weight: normal;
    font-stretch: normal;
    line-height: 0.36rem;
    letter-spacing: 0;
    color: #070a1e;
    border: none;

    &:disabled {
      background-image: linear-gradient(0deg, #b7b7b7 1%, #c4c4c4 50%, #d3d3d3 100%), linear-gradient(#b7b7b7, #d3d3d3);
      color: #070a1e;
      opacity: 1;
    }
  }

  .tip {
    font-size: 0.26rem;
    color: #fefefe;
    margin: 0.5rem;
    line-height: 1;
    margin-top: 0.87rem;
  }
}
.gridCss {
  position: absolute;
  width: 100%;
//   margin-top: 2.5rem;
  padding-bottom:1rem;
height: 8.5rem;
    overflow-y: scroll;
}
.van-toast--text{//不好用需要调查， 弹出消息样式无法重写
  background-color: red!important;
}
.shaPictureimgNameCss{
  height: 3.55rem;
  width: 3.36rem;
}
.shaPictureCss{
  margin-top:-0.02rem;
  width: 100%;
  height: 0.90rem;
  width: 3.36rem;
  font-family: SourceHanSansCN-Regular;
  font-size: 0.28rem;
  font-weight: normal;
  font-stretch: normal;
  line-height: 0.45rem;
  letter-spacing: 0rem;
  color: #ffffff;
  background-color: #8393AC;
  border-bottom-left-radius: 0.1rem;
  border-bottom-right-radius: 0.1rem;
  text-align:center;
}
.shaPictureNameCss{
  position: absolute;
  width: 2.89rem;
  text-align:center;
  margin-left: 0.2rem;
}
</style>
<style lang="scss">

  .van-grid-item__content{
    width: 3.36rem;
    display:-webkit-box;
    display:-webkit-flex;display:flex;
    -webkit-box-orient:vertical;
    -webkit-box-direction:normal;
    -webkit-flex-direction:column;
    flex-direction:column;
    box-sizing:border-box;
    padding:0px!important;
    border-top-left-radius: 0.1rem;
    border-top-right-radius: 0.1rem;
    border-bottom-left-radius: 0.1rem;
    border-bottom-right-radius: 0.1rem;
  }
  .van-button--normal{
    padding: 0rem;
  }
  </style>
