<template>
  <page-layout class="award-container">
    <nav-bar title="我的奖品" @init="onInitNavbar"></nav-bar>
    <u-scroll-view :tabbar-conflict="false">
      <view class="main-container">
        <view class="theme-title">
          <text class="title">我的奖品</text>
          <image mode="aspectFit" class="title-bg"
                 src="https://www.productronicachina.com.cn/resources/files/0221/67b7dd27b30b7/标题星星.png"></image>
        </view>
        <view class="award-index">
          <view class="award-head">
            <view class="award-title">
              路线进度
            </view>
            <view @click="gotoCheck()" class="award-button">
              继续打卡
            </view>
          </view>
          <view class="award-progress">
            <view class="award-progress-bar"></view>
            <view class="award-progress-value" :style="{width: getProcess}"></view>
            <view class="award-progress-point-list">
              <view v-for="(item,index) in giftList" :style="{left:((index+1)/giftList.length)*90+'%'}" :key="item.id"
                    :class="['award-progress-point-item',checked>=item.route_count?'active':'']">
                <view class="point"></view>
                <text>已满{{ item.route_count }}条</text>
              </view>
            </view>
          </view>
          <view class="award-body">
            <view class="award-title">
              您目前的奖品
            </view>
            <view class="award-list">
              <view v-for="(item,index) in giftList" :key="item.id" class="award-list-item">
                <image :src="item.picture_url" alt="image" mode="widthFix"></image>
                <view class="award-info">
                  <view class="award-info-title">
                    {{ item.name }}
                  </view>
                  <view class="award-info-desc">
                    成功打卡
                    <text>{{ item.route_count }}条路线</text>
                    即可获取
                  </view>
                  <mp-html class="award-info-desc" :content="item.description"></mp-html>
                </view>
                <view class="award-option">
                  <view @click="getGift(item,index)" :class="['award-option-btn',getClass(item,index)]">
                    {{ getText(item, index) }}
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="award-footer">
          <view class="award-footer-title">
            {{ rule_title }}
          </view>
          <mp-html :content="rule" class="award-footer-desc"></mp-html>
        </view>
      </view>
    </u-scroll-view>
    <view v-if="show_qr" class="pop-up-bg">
      <view :class="['QRcode',check_finish?'checked':'']">
        <view class="tickt-1">
          <view :style="{textDecoration:check_finish?'line-through':''}" class="text">
            {{ check_finish ? current_gift.name + '已核销' : current_gift.name + '核销券' }}
          </view>
          <view class="image">
            <image class="image-inner" mode="aspectFit" :src="qr_code"></image>
          </view>
        </view>
        <view class="tickt-2">
          <view class="image">
            <image class="image-inner" mode="aspectFit" :src="qr_code"></image>
          </view>
          <view class="text">
            请将此二维码交由工作人员核销
          </view>
        </view>
      </view>
      <view @click="closeQR()" class="iconfont icon-Cancel-copy close"></view>
    </view>
    <view v-if="pop_up" class="pop-up-bg">
      <view class="pop-up">
        <view class="title">
          <view>这是您专属的幸运时刻，请填写以下信息参与抽奖：</view>
          <view>恭喜您获得本年度大满贯抽奖资格！</view>
        </view>
        <view class="input">
          <view class="placeholder">您的公司名称<span>*</span> ：</view>
          <input v-model="verify_note.company_name" class="text-input"/>
        </view>
        <view class="input">
          <view class="placeholder">您的姓名<span>*</span> ：</view>
          <input v-model="verify_note.verify_name" class="text-input"/>
        </view>
        <view class="input">
          <view class="placeholder">您的手机号<span>*</span> ：</view>
          <input v-model="verify_note.verify_phone" class="text-input"/>
        </view>
        <view class="description">
          温馨提示：本次抽奖奖品丰厚，机会难得，请确保信息真实有效。填写完毕后，点击"立即抽奖"按钮，即可开启您的幸运之旅!
        </view>
        <view class="description">祝你好运！</view>
        <view class="tips">注：本活动真实有效，最终解释权归主办方所有</view>
        <view class="button-list">
          <view @click="pop_up=false" class="button cancel">取消</view>
          <view @click="getNow()" class="button confime">立即抽奖</view>
        </view>
      </view>
    </view>
  </page-layout>
</template>

<script>
import PageLayout from "@/components/layout/page-layout";
import NavBar from "@/components/layout/nav-bar";
import UTabs from "@/components/common/u-tabs";
import UScrollView from "@/components/common/u-scroll-view";
import NewsItem from "@/pages/news/components/news-item";
import DisclaimerText from "@/components/disclaimer-text";
import floatButton from "@/components/layout/float-button";
import {checkInCount, claim, receiptNote, getActivityInfo, getRouteList, getGiftList} from "@/api/checkIn";

export default {
  components: {
    PageLayout,
    NavBar,
    UTabs,
    UScrollView,
    NewsItem,
    DisclaimerText,
    floatButton
  },
  data() {
    return {
      activeIndex: null,
      awardProgressValue: '0%',
      giftList: [],
      routes: [],
      route_count: 1,
      checked: 0,
      pop_up: false,
      show_qr: false,
      qr_code: '',
      check_finish: false,
      current_gift: {

      },
      timer: null,
      rule: '',
      rule_title: '',
      is_receipts: 0,
      verify_note: {
        company_name: '',
        verify_name: '',
        verify_phone: ''
      }
    };
  },
  mounted() {
    this.getGiftListEvent()
    this.getActiveInfo()
    this.getRouteListInfo()
  },
  onUnload() {
    clearTimeout(this.timer)
  },
  computed: {
    getProcess() {
      if (!(this.giftList && this.giftList.length > 0)) {
        return '0%'
      }
      let subList = []
      for (var i = this.giftList.length - 1; i > 0; i--) {
        subList.unshift(this.giftList[i].route_count - this.giftList[i - 1].route_count)
      }
      subList.unshift(this.giftList[0].route_count)

      let process = 0
      let count = this.checked
      let per_process = 100 / this.giftList.length
      subList.forEach(item => {
        if (count >= item) {
          count -= item
          process += per_process
        } else {
          process += per_process * (count / item)
          count = 0
        }
      })
      return process + '%'
    },
  },
  methods: {
    getRouteListInfo(callback) {
      getRouteList().then(res => {
        this.is_receipts = res.data.is_receipts
        if (callback) {
          callback()
        }
      })
    },
    getActiveInfo() {
      getActivityInfo().then(res => {
        this.rule = res.data.gifts_rules_content
        this.rule_title = res.data.gifts_rules_name
      })
    },
    getGiftListEvent() {
      getGiftList().then(res => {
        this.giftList = res.data;
        this.getCheckinCount()
      })
    },
    getCheckinCount(callback) {
      checkInCount().then(res => {
        this.routes = res.data.routes
        this.route_count = res.data.route_count
        this.checked = res.data.route_checkin_count
        console.log(this.checked, 'this.checked')
        console.log(this.giftList)
        this.giftList.forEach((item, index) => {
          if (this.checked >= item.route_count) {
            this.activeIndex = index
          }
        })
        if (callback) {
          callback()
        }
      })
    },
    gotoCheck() {
      uni.navigateTo({
        url: '/pages/checkIn/checkInRoute'
      });
    },
    closeQR() {
      this.show_qr = false;
      clearTimeout(this.timer)
    },
    claimDataEvent() {
      //生成二维码方法
      claim({
        gift_id: this.current_gift.id,
      }).then(res => {
        if (res.code === 0) {
          this.qr_code = res.data.qrcode_url
          this.current_gift.form_id = res.data.id
          //展示二维码
          this.show_qr = true
          this.checkGiftState(() => {
            if (this.current_gift.route_count === 9) {
              //轮询确认核销后，展示抽奖环节
              this.pop_up = true
            }
          })
        }
      })
    },
    getGift(item, index) {
      //获取当前产品信息
      if (item.is_receipts > 0 || this.activeIndex !== index) {
        return false
      }
      this.current_gift = item
      this.getRouteListInfo(() => {
        //获取当前是否生成过奖品二维码 is_receipts
        if (this.is_receipts > 0) {
          //获取二维码
          this.claimDataEvent()
        } else {
          //确认是否领取奖品
          uni.showModal({
            title: '确定领取该奖品吗？',
            content: '领取该礼品后将无法再领取其它礼品',
            success: (res) => {
              if (res.confirm) {
                //获取二维码
                this.claimDataEvent()
              }
            }
          })
        }
      })
    },
    checkGiftState(callback) {
      getGiftList().then(res => {
        this.giftList = res.data;
        this.giftList.forEach(item => {
          if (item.id === this.current_gift.id) {
            if (item.is_receipts) {
              console.log('轮询已核销')
              clearTimeout(this.timer)
              this.checkAnimation()
              if (callback) {
                callback()
              }
            } else {
              console.log('轮询未核销')
              this.timer = setTimeout(() => {
                this.checkGiftState(callback)
              }, 1000)
            }
          }
        })
      })
    },
    getClass(item, index) {
      if (item.is_receipts)
        return 'cheked'
      if (this.activeIndex !== index)
        return 'disable'
    },
    getText(item, index) {
      if (item.is_receipts)
        return '已领取奖品'
      if (this.activeIndex === index) {
        return '立即领取'
      } else {
        return '不可领取'
      }
    },
    getNow() {
      if (this.verify_note.company_name == '' || this.verify_note.verify_name == '' || this.verify_note.verify_phone == '') {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
      } else {
        receiptNote({
          id: this.current_gift.form_id,
          verify_note: this.verify_note
        }).then(res => {
          uni.showToast({
            title: '提交抽奖信息成功',
            icon: 'none'
          })
          this.pop_up = false
          this.getGiftListEvent()
          this.getCheckinCount()
        })

      }
    },
    checkAnimation() {
      this.check_finish = true
      setTimeout(() => {
        this.show_qr = false
      }, 2000)
    }
  }
}
</script>

<style lang="scss" scoped>
.pop-up-bg {

  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: #00000066;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .QRcode {
    width: 60%;
    display: flex;
    flex-direction: column;

    &.checked {
      .tickt-1 {
        animation: checked 600ms forwards;
      }

      @keyframes checked {
        0% {
          transform: rotate(0deg);
        }
        50% {
          transform: rotate(8deg);
        }
        100% {
          transform: rotate(6deg);
        }
      }
    }

    .tickt-1 {
      background-image: url('https://www.productronicachina.com.cn/resources/files/0227/67c02d4916542/tickt1.png');
      background-size: 100% 100%;
      width: 100%;
      aspect-ratio: 2/1;
      position: relative;
      overflow: hidden;
      transform-origin: 100% 100%;

      .text {
        margin-top: 40rpx;
        text-align: center;
        color: grey;
      }

      .image {
        position: absolute;
        left: 50%;
        bottom: 0;
        transform: translate(-50%, 70%);
        width: 70%;
        aspect-ratio: 1;

        .image-inner {
          width: 100%;
          height: 100%;
        }
      }
    }

    .tickt-2 {
      position: relative;
      background-image: url('https://www.productronicachina.com.cn/resources/files/0227/67c02d4915cc2/tickt2.png');
      background-size: 100% 100%;
      width: 100%;
      aspect-ratio: 1;

      .text {
        width: 100%;
        position: absolute;
        bottom: 50rpx;
        text-align: center;
        color: grey;
        font-size: 24rpx;
      }

      .image {
        position: absolute;
        left: 50%;
        top: 0;
        transform: translate(-50%, -30%);
        width: 70%;
        aspect-ratio: 1;

        .image-inner {
          width: 100%;
          height: 100%;
        }
      }

      overflow: hidden;
    }
  }

  .close {
    margin-top: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 80rpx;
    height: 80rpx;
    border: 4rpx solid white;
    color: white;
    border-radius: 50%;
  }

  .pop-up {
    display: flex;
    flex-direction: column;
    grid-gap: 20rpx;
    width: 80%;
    background-color: #FAFAFA;
    border-radius: 20rpx;
    padding: 57rpx 38rpx 102rpx;

    .button-list {
      display: flex;
      grid-gap: 13rpx;
      justify-content: flex-end;

      .button {
        padding: 15rpx 0;
        width: 144rpx;
        text-align: center;
        font-weight: bold;
        font-size: 14rpx;
        border-radius: 6rpx;

        &.confime {
          background-color: #E57519;
          color: white;
        }

        &.cancel {
          border: 1rpx solid #94A3B8;
        }
      }
    }

    .title {
      font-size: 18rpx;
      line-height: 1.5;
    }

    .description {
      font-size: 16rpx;
    }

    .tips {
      font-size: 14rpx;
      color: #555555;
    }

    .input {
      padding: 10rpx 18rpx;
      display: flex;
      align-items: center;
      border: 1rpx solid #CBD5E1;
      border-radius: 8rpx;

      .placeholder {
        font-size: 16rpx;

        span {
          color: red;
        }
      }

      .text-input {
        flex: 1;
        height: 100%;
        font-size: 16rpx;
      }
    }
  }
}

.main-container {
  background: linear-gradient(180deg, #015A92 0%, #56A3E9 15%, #3484BD 74%, #106591 98%);
  padding: 32rpx;
  min-height: 100vh;

  .theme-title {
    //margin-top: 24rpx;
    margin-bottom: 32rpx;
    position: relative;
    height: 130rpx;
    display: flex;
    justify-content: center;
    align-items: center;

    .title {
      color: white;
      font-size: 55rpx;
      font-weight: bold;
    }

    .title-bg {
      position: absolute;
      left: 0;
      top: 0;
      height: 100%;
    }

  }

  .award-index {
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    width: 100%;
    padding: 36rpx 40rpx;

    .award-title {
      flex: 1;
      min-width: 1px;
      font-size: $fontSize1;
    }

    .award-head {
      display: flex;
      align-items: center;

      .award-button {
        line-height: 1;
        background-color: #4085C7;
        padding: 16rpx 32rpx;
        border-radius: 50rpx;
        font-size: 18rpx;
        color: #ffffff;
      }
    }

    .award-body {
      .award-list {
        display: flex;
        flex-direction: column;
        grid-gap: 24rpx;
        margin-top: 32rpx;

        .award-list-item {
          display: flex;
          background: #FAFAFA;
          padding: 30rpx 12rpx;
          align-items: center;
          border-radius: 20rpx;

          image {
            width: 128rpx;
            //height: 128rpx;
          }

          .award-info {
            flex: 1;
            min-width: 1rpx;

            .award-info-title {
              color: #000000;
              font-size: $fontSize2;
            }

            .award-info-desc {
              margin-top: 18rpx;
              color: #555555;
              font-size: $fontSize0;

              text {
                color: #015A92;
              }
            }
          }

          .award-option-btn {
            background: #E57519;
            font-size: 16rpx;
            color: #ffffff;
            width: 128rpx;
            height: 48rpx;
            border-radius: 6rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 1;

            &.disable {
              background: #94A3B8;
            }

            &.cheked {
              background: #015A92;
            }
          }

          .award-option {

          }
        }
      }
    }

    .award-progress {
      margin-top: 30rpx;
      display: flex;
      align-items: center;
      position: relative;
      width: 100%;
      margin-bottom: 90rpx;

      .award-progress-bar {
        display: block;
        width: 90%;
        height: 9rpx;
        border-radius: 100rpx;
        background-color: #D9CC9D;
      }

      .award-progress-value {
        display: block;
        position: absolute;
        height: 9rpx;
        border-radius: 100rpx;
        width: 0%;
        transition: width 1s ease-in-out;
        background-color: #E57519;
      }

      .award-progress-point-list {
        display: flex;
        position: absolute;
        align-items: center;
        width: 100%;

        .award-progress-point-item {
          position: absolute;
          display: flex;
          flex-direction: column;
          align-items: center;
          top: -12rpx;
          transform: translateX(-50%);

          & > text {
            margin-top: 12rpx;
            white-space: nowrap;
            font-size: $fontSize1;
          }

          .point {
            height: 24rpx;
            width: 24rpx;
            border-radius: 50%;
            border: 1rpx solid #E57519;
            background-color: #ffffff;

            &:before {
              content: '\e849';
              font-family: 'iconfont';
              color: #ffffff;
              line-height: 1;
              transition: 1s ease-in-out;
              font-size: 20rpx;
              opacity: 0;
              transform: scale(0);
            }
          }

          &.active {
            .point {
              background-color: #E57519;
              display: flex;
              align-items: center;
              justify-content: center;

              &:before {
                opacity: 1;
                transform: scale(1);
              }
            }
          }
        }
      }
    }

  }

  .award-footer {
    padding: 42rpx 48rpx;
    background-color: #EEEEEE;
    border-radius: 0 0 20rpx 20rpx;

    .award-footer-title {
      font-size: $fontSize3;
    }

    .award-footer-desc {
      padding-left: unset;
      margin-top: 20rpx;
      font-size: $fontSize0;
      line-height: 1.9;
      display: flex;
      flex-direction: column;
      //text-indent: 22rpx;
      list-style: decimal;
      padding-left: 22rpx;

      & > text {
        display: list-item;
      }
    }
  }
}
</style>
