<template>
  <div class="timedDraw" >
    <div :style="styleData.countDown" v-if="grantTime > new Date().getTime()">
      <!-- 距离下次开奖 -->
      <van-count-down :style="styleData.countDownBox" :time="grantTime - new Date().getTime()" format="DD 天 HH 时 mm 分 ss 秒" @finish="refresh">
        <template #default="timeData">
          距离本周期结束：
          <span class="block" :style="styleData.block">{{
            timeData.days >= 10 ? timeData.days : "0" + timeData.days
          }}</span>
          <span class="colon">天</span>
          <span class="block" :style="styleData.block">{{
            timeData.hours >= 10 ? timeData.hours : "0" + timeData.hours
          }}</span>
          <span class="colon">时</span>
          <span class="block" :style="styleData.block">{{
            timeData.minutes >= 10 ? timeData.minutes : "0" + timeData.minutes
          }}</span>
          <span class="colon">分</span>
          <span class="block" :style="styleData.block">{{
            timeData.seconds >= 10 ? timeData.seconds : "0" + timeData.seconds
          }}</span>
          <span class="colon">秒</span>
        </template>
      </van-count-down>
    </div>
    <div :style="styleData.cyclePrizeBox">
      <div :style="styleData.tutorial"></div>
      <div :style="styleData.allReceiveNum">已有
        <span :style="styleData.allReceiveNumSpan">{{allReceiveNum}}</span>
        人报名
        <span v-if="receiveStatus == 1 && grantTime">(已报名)</span>
      </div>
      <div :style="styleData.taskBtn" v-if="receiveStatus == 0" @click="receiveFun">去报名</div>
      <div :style="styleData.taskBtn" v-if="receiveStatus == 1 && grantTime" @click="dialogMore">做任务得抽奖码</div>
      <div :style="styleData.taskBtn1" v-if="receiveStatus == 1 && !grantTime" @click="noTask">做任务得抽奖码</div>
      <div :style="styleData.drawCodeNum"  v-if="receiveStatus == 1 && grantTime">
        当前周期已获得
        <span :style="styleData.drawCodeNumMsg">{{drawCodeNum}}</span>
        张抽奖码，请前往【我的抽奖码】查看
      </div>
    </div>
    
    <div class="" :style="styleData.prizebox">
      <!-- 奖品区域 -->
      <!-- prizeList -->
      <div v-if="prizeList.length == 1" class="onePrize" :style="styleData.onePrize">
        <div class="imgBox">
          <img :src="prizeList[0].showImg" alt="">
        </div>
        <div class="prizeName" :style="styleData.swiperPrizeName">{{prizeList[0].prizeName}}</div>
      </div>
       <div class="swipe_box" v-else>
        <swiper ref="mySwiper" :options="swiperOption" :style="styleData.swiperAll">
          <swiper-slide v-for="(item,index) in prizeList" :key="index" :style="styleData.swiperItem">
            <div :style="styleData.swiperImgBox">
              <img :src="item.showImg" alt="">
            </div>
            <div :style="styleData.swiperPrizeName">{{item.prizeName}} </div>
          </swiper-slide>
        </swiper>
       </div>
      <!-- <div v-else class="morePrize">
        <div class="aa" :style="{ width: `${prizeList.length * 2.4}rem` }">
          <div class="prizeItem" v-for="item in prizeList">
            <div class="imgBox">
              <img :src="item.showImg" alt="">
            </div>
            <div class="prizeName">{{item.prizeName}} </div>
          </div>
        </div>

      </div> -->

    </div>
    <div :style="styleData.myPrize" v-if="myCyclePrizeList.length > 0">
      <div :style="styleData.myPrizeTop"></div>
      <div :style="styleData.myPrizeMsg">（领取后可在我的奖品中查看）</div>
      <div :style="styleData.myPrizeUl">
        <div :style="styleData.myPrizeItem" v-for="item in myCyclePrizeList">
        <div :style="styleData.myPrizeItemTop">
          第{{item.position}}期({{ item.startTime | filterDate }}-{{ item.endTime | filterDate}})
        </div>
        <div :style="styleData.myPrizeItemImg">
          <img :src="item.prizeImg" alt="">
        </div>
        <div :style="styleData.myPrizeDetail">
          <div :style="styleData.detailName">{{item.prizeName}}</div>
          <div :style="styleData.detailTime">
            中奖时间：{{item.grantTime | filterDate}}
          </div>
        </div>
        <div :style="styleData.myPrizeBtn" @click="drawFun(item)">领取</div>
      </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { Swiper, SwiperSlide } from 'vue-awesome-swiper'
  import 'swiper/swiper.scss'
  import Vue from "vue";
  import { CountDown } from "vant";
  Vue.use(CountDown);
  import { removeUrlShareUserId } from "../../../util/tools";
  import store from "../../../store/store";
  import apis1 from '../../../util/apis1.js';
  let { timedDrawApi, timedDrawReceiveApi, timedDrawPrizeApi, getMyCyclePrizeApi, cycleAcquireDrawApi,getMyNowDrawCodeApi,updateCycleStatusApi } = apis1;
  import { AddressPopComService, TaskPopComServiceNew2, PrizeResultPopComService, NoPrizeResultPopComService } from "../../../util/hdzxtcomCreate";
  export default {
    props: ['datas', 'styleData', 'keyData', 'isTemplate', 'templateData', 'modifyContent', 'isWebClick'],
    components: {
      Swiper,
      SwiperSlide
    },
    data() {
      return {
        grantTime: '',
        receiveStatus: 0,
        opportunityType: 0,
        prizeList: [],
        showShare: false, //
        showFoll: false,
        showBuy: false,
        restDrawCount: 0,
        pointFoll: 1, // pop页显示分享任务
        pointShare: 3, // pop页显示关注任务
        pointBuy: 2, // pop页显示购买商品任务
        task: {},
        myCyclePrizeList: [],
        isPlayType: false,
        allReceiveNum: 0,
        swiperOption: {
          slidesPerView: 1.4,
          spaceBetween: 10,
          loop: false,
        },
        actEndStatus:0,
        drawCodeNum:0,
        cycleId:0,
        pageActStatus: ''
      }
    },
    computed: {
    swiper() {
      return this.$refs.mySwiper.swiper
    }
  },
    created() {
    this.actStatus = sessionStorage.getItem("actStatus");
      this.pageActStatus = this.actStatus || '';
      this.publicData.$on("activityLoaded", this.handleActivityLoaded);
      this.publicData.$on("xhyFollowSkuTask", xhyFollowSkuTask => {
        if (xhyFollowSkuTask) {
          this.timedDrawFun(true);
        }
      });
      this.initData();
    },
    beforeDestroy() {
      this.publicData.$off("activityLoaded", this.handleActivityLoaded);
    },
    methods: {
      handleActivityLoaded(data) {
        this.pageActStatus = data && data.actStatus != null ? String(data.actStatus) : '';
        if (this.pageActStatus === '1' || this.pageActStatus === '2') {
          this.grantTime = '';
        }
      },
      initData() {
        if (this.isTemplate) {
          var datasAll = this.templateData;
          if (datasAll) {
            this.receiveStatus = 0;
            this.prizeList = datasAll.draw.prizeList;
            this.allReceiveNum = datasAll.activity.initEnrollNum
          } else {
            this.grantTime = new Date().getTime() + 3600 * 24 * 1000;
            this.receiveStatus = 0;
            this.allReceiveNum = 500
            this.prizeList = [{
              prizeName: "奖品名称",
              showImg: "http://img13.360buyimg.com/n0/jfs/t1/234504/18/13946/52081/65e199cdF58b837c0/45b10688b0976b07.png",
            }]
          }

        } else {
          this.timedDrawFun(false)
          this.timedDrawPrizeFun()
          this.getMyCyclePrizeFun()
        }
      },
      getMyCyclePrizeFun() {
        getMyCyclePrizeApi(res => {
          this.myCyclePrizeList = res.data
        })
      },
      noTask(){
        this.$toast("本期活动已结束，感恩参与！");
      },
      dialogMore() {
        console.log(this.task, "9999");

        if (this.isTemplate) {
          // this.$toast('活动预览，仅供查看');
          return;
        }
        let actStatus = sessionStorage.getItem("actStatus");
        if (actStatus == 2) {
          this.$toast("活动已结束");
          return;
        }
        if (actStatus == 1) {
          this.$toast("活动未开始");
          return;
        }
        this.doFrontBuryPoint({ code: "cjq-gdjh", value: "", event: "click" });
        TaskPopComServiceNew2.create(
          this.isTemplate,
          this.showShare,
          this.showFoll,
          this.showBuy,
          this.restDrawCount,
          this.pointFoll,
          this.pointShare,
          this.pointBuy,
          this.task,
          this.styleData,
          this.datas,
          submit => {
            TaskPopComServiceNew2.close();
            if (submit) {
              let dataType = {};
              if (typeof submit == "string") {
                dataType = JSON.parse(submit);
              }
              if (
                dataType.taskItemData &&
                (dataType.taskItemData.type == "13" ||
                  dataType.taskItemData.taskType == "13")
              ) {
                return;
              } else {
                // this.initData(false);
              }
            } else {
              // this.initData(false);
            }
          }
        );
      },
      drawFun(row) {
        if (this.isTemplate) {
          this.$toast('活动预览，仅供参考');
          return;
        }
        let actStatus4 = sessionStorage.getItem('actStatus');
        if (actStatus4 == 1) {
          this.$toast('活动尚未开始');
          return;
        }
        if (actStatus4 == 2) {
          this.$toast("活动已结束");
          return;
        }
        if (this.isPlayType) {
          return;
        }
        this.isPlayType = true;
        sessionStorage.setItem('prizeInfoId', row.prizeInfoId);
        cycleAcquireDrawApi(row.prizeInfoId, row.drawCode, receiveData => {
          if (receiveData.resp_code == 0) {
            this.isPlayType = false;
            if (receiveData.data.result == true) {
              this.initData();
              // this.publicData.$emit('isNotyFiceWinnerReorrd', true, this.isTemplate);
              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, this.styleData, submit => {
                PrizeResultPopComService.close();
              });
            } else {
              NoPrizeResultPopComService.create(this.styleData, submit => {
                NoPrizeResultPopComService.close();
              });
              this.initData();
            }
          } else if (receiveData.resp_code == 60010) {
            this.isPlayType = false;
            this.$toast('抱歉，奖品已发完~');
            setTimeout(() => {
              this.initData();
            }, 1000);
          } else {
            this.isPlayType = false;
            this.$toast('抱歉，奖品领取失败~');
          }
        })
      },
      receiveFun() {
        if (this.isTemplate) {
          this.$toast("活动预览，仅供查看");
          return;
        }
        let actStatus = sessionStorage.getItem("actStatus");
        if (actStatus == 2) {
          this.$toast("活动已结束");
          return;
        }
        if (actStatus == 1) {
          this.$toast("活动未开始");
          return;
        }
        if(this.actEndStatus == 3){
          this.$toast("报名截止～");
          return;
        }
        console.log(this.opportunityType, "opportunityType");
        if (this.opportunityType == 1) {
          var datas = {
            isEditAddress: true,
            isAlLookAddress: false,
          };
          AddressPopComService.create(datas, this.styleData, (submit) => {
            AddressPopComService.close();
            if (submit) {
              timedDrawReceiveApi(res => {
                this.receiveStatus = 1
                this.allReceiveNum = this.allReceiveNum+1
                this.timedDrawFun()
                this.$toast("报名成功~");
              })
            } else {
              this.$toast("报名前请先填写收货信息，方便中奖后奖品的发放。");
            }
          });
        } else {
          timedDrawReceiveApi(res => {
            this.receiveStatus = 1
            this.allReceiveNum = this.allReceiveNum+1
            this.timedDrawFun()
            this.$toast("报名成功~");
          })
        }

      },
      timedDrawFun(isCallBack) {
        timedDrawApi(res => {
          this.receiveStatus = res.data.receiveStatus
          this.actEndStatus = res.data.actStatus
          this.opportunityType = res.data.opportunityType
          this.grantTime = res.data.grantTime
          this.allReceiveNum = res.data.allReceiveNum
          this.cycleId = res.data.cycleId
          this.task = res.data.taskList;
          let actStatus = this.pageActStatus || sessionStorage.getItem("actStatus") || '';
          if(actStatus === '1' || actStatus === '2'){
            this.grantTime = ''
          }
          console.log(this.grantTime,"lysssgrantTime")
          if (isCallBack) {
            this.publicData.$emit("taskCallBackData", res.data);
          }
          getMyNowDrawCodeApi(reslove =>{
            this.drawCodeNum = reslove.data
          })
          setTimeout(() => {
              if (res.data.status == 1) {
                this.$toast("助力成功");
              } else if (res.data.status == 2) {
                this.$toast("已助力");
              } else if (res.data.status == 3) {
                this.$toast("助力失败");
              } else if (res.data.status == 4) {
                this.$toast("自己不能给自己助力！");
              } else if (res.data.status == 5) {
                this.$toast("您已为其他好友助过力了~");
              } else if (res.data.status == 6) {
                this.$toast("您的好友助力任务已圆满完成，无需继续助力，感谢您对本活动的支持~");
              }
            }, 500);
           setTimeout(() => {
              if (store.state.shareUserId) {
                removeUrlShareUserId()
              }
            }, 800);
          
        })
      },
      timedDrawPrizeFun() {
        timedDrawPrizeApi(res => {
          this.prizeList = res.data
        })
      },
      refresh() {
        updateCycleStatusApi(this.cycleId,res =>{
          if(res.resp_code == 0){
            setTimeout(() => {
              this.initData()
            }, 500);
            // window.location.reload()
          }
        })
      }
    }
  }
</script>
<style lang="scss">
  .timedDraw {
    .onePrize {
      width: 6.9rem;
      height: 1.16rem;
      background: linear-gradient(#ff909d 0%, #f94349 100%);
      margin: 0 auto;
      border-radius: 5px;
      padding: 0 0.1rem;
      display: flex;
      align-items: center;
      .imgBox {
        width: 0.95rem;
        height: 0.95rem;
        background: #fff;
        border-radius: 5px;
        display: flex;
        align-items: center;
        justify-items: center;
      }
      .prizeName {
        height: 0.95rem;
        margin-left: 0.25rem;
        line-height: 0.95rem;
        color: #fff;
      }
    }
  }
</style>
