<template>
  <page :nav="false" ref="pageRef">
      <image :src="resource.lottery_bg" mode="aspectFill" class="bg" />
      <view class="mask-page"></view>
      <view class="wrapper flex-column-align" v-if="revealData && revealData.length > 0" :style="{paddingTop: padding + 'px'}">
          <view class="relative">
              <view :class="[revealData.length === 1 ? 'height1' : 'height5']">
                  <view v-for="(pItem, pIndex) in revealData" :key="pIndex" class="overflow-hidden">
                      <view :style="{width: pItem.length * itemWidth + 'px'}" class="flex-align animal-wrapper"
                          :id="`animal-wrapper-${pIndex}`" :animation="animalCreateArray[pIndex]">
                          <view v-for="item in pItem" :key="item.key" :style="{padding: '5px 0'}">
                              <trans-card v-if="num > 1" :item="item" />
                              <trans-card v-else :item="item" :width="90" :height="121" :fill="2" :image-width="74" :image-height="94" />
                          </view>
                      </view>
                  </view>
              </view>
          </view>
          <view class="mask-left" :style="{width: width + 'px'}"></view>
          <view class="mask-right" :style="{width: width + 'px'}"></view>
          <image :src="revealData.length === 1 ? resource.lottery_middle_s : resource.lottery_middle_l" class="lottery_middle translateY"
              mode="widthFix" :style="{marginTop: (padding / 2) + 'px'}" />
      </view>
      <view class="bottom">
          <view class="bottom-btns flex-align-center" @click="skipAnimal">
              跳过动画
          </view>
      </view>
      <result-com ref="result" :num="num" :isDemo="isDemo" :periodQuantity="periodQuantity" />
      <hiddenTask ref="hiddenTaskRef" @refresh="initGoods" />
  </page>
</template>
<script>
import resource from '@/utils/resource'
import { LEVEL_MAP } from '@/utils/config'
import transCard from './trans_card'
import resultCom from './result_com'
import hiddenTask from '../hidden_activity/hidden_task_dialog.vue'
export default {
  components: { transCard, resultCom, hiddenTask },
  data() {
      return {
          LEVEL_MAP,
          resource,
          num: 1,
          nums: [],
          animal: false,
          tableData: null,
          isDemo: false,
          total: 0,
          goods: null,
          revealData: null,
          animalCreateArray: [],
          itemWidth: 0,
          king: null,
          periodQuantity: null,
          magicFireworksList: null,
          spuIds: '',
          resultFlag: false,
		  width: 140.5,
		  padding: 32
      }
  },
  computed: {
      // width() {
      //     if (this.$store.state.systemInfo) {
      //         let screenWidth = this.$store.state.systemInfo.screenWidth
      //         return (screenWidth - (this.num == 1 ? 94 : 72)) / 2
      //     }
      //     return 0
      // },
      // padding() {
      //     if (this.$store.state.systemInfo) {
      //         let screenWidth = this.$store.state.systemInfo.safeArea.height
      //         return screenWidth > 650 ? 32 : 0
      //     }
      //     return 0
      // }
  },
  onLoad(options) {
	  console.log('参数', options);
      this.goods = this.$cache.get(this.$cache.key.AWARD_GOODS)
	  console.log('goods', this.goods);
	  console.log("width", this.width);
	  console.log("padding", this.padding);
      this.num = Number(options.num) || 5
      this.itemWidth = this.num == 1 ? 94 : 71
      this.initNums()
      //试玩
      if (options.tradeNo) {
          this.tradeNo = options.tradeNo
      } else {
          this.isDemo = true
          this.tableData = [this.$cache.get(this.$cache.key.AWARD_DEMO)]
		  console.log('tableData', this.tableData);
      }
      this.initGoods()
      this.innerAudioContext = wx.createInnerAudioContext({
          useWebAudioImplement: false // 是否使用 WebAudio 作为底层音频驱动，默认关闭。对于短音频、播放频繁的音频建议开启此选项，开启后将获得更优的性能表现。由于开启此选项后也会带来一定的内存增长，因此对于长音频建议关闭此选项
      })
      this.innerAudioContext.src = resource.mp3_5
  },
  mounted() {
      setTimeout(
          () => {
              this.startAnimal()
          },
          this.num == 1 ? 500 : 700
      )
      if (this.tradeNo) {
          this.time = new Date().getTime()
          this.initData(0)
      } else {
          this.initDemo()
      }
  },
  onUnload() {
      this.stopPlay()
  },
  methods: {
      stopPlay() {
          try {
              this.innerAudioContext && this.innerAudioContext.stop()
              this.innerAudioContext && this.InnerAudioContext.destroy()
              this.innerAudioContext = null
          } catch (error) {}
      },
      initNums() {
          let array = []
          for (let i = 0; i < this.num; i++) {
              array.push(i)
          }
          this.nums = array
      },
      initGoods() {
          this.screenWidth = this.$store.state.systemInfo.screenWidth
          let array = []
          let animalArray = []
          this.nums.forEach((_) => {
              let tGoods = this.handleGoods(this.goods)
              array.push(tGoods.array)
              animalArray.push({
                  active: tGoods.active,
                  offset: tGoods.offset
              })
          })
          this.revealData = array
          this.animalArray = animalArray
      },
      handleGoods(goods) {
          let lastItem = goods[goods.length - 1]
          let array = goods.concat(goods)
          array = this.$common.shuffle(array)
          array = array.slice(0, Math.floor((array.length / 5) * 4))
          let active = Math.floor(Math.random() * 3 + array.length - 8)
          array[active] = lastItem
          array = array.map((item) => ({ ...item }))
          array.forEach((item, index) => {
              item.key = index
          })
          let offset =
              this.itemWidth * active +
              Math.floor(Math.random() * (this.itemWidth - 4 - 22) + 15) -
              this.screenWidth / 2
          return { array, active, offset }
      },
	  // 主要
      startAnimal() {
          this.resultFlag = false
          let animalCreateArray = []
          this.animalArray.forEach((item, index) => {
              let animation = wx.createAnimation({
                  duration: 7000,
                  timingFunction: 'ease-out'
              })
              animation.translateX(-item.offset).step()
              let animationData = animation.export()
              animalCreateArray.push(animationData)
          })
          this.animalCreateArray = animalCreateArray
          setTimeout(() => {
              if(!this.resultFlag) {
                  this.skipAnimal()
              }
          }, 7200)
          setTimeout(() => {
              this.innerAudioContext.play()
          }, 100)
      },
      skipAnimal() {
          this.stopPlay()
          this.resultFlag = true
          this.showResult()
      },
      async initDemo() {
          this.tableData.forEach((item, index) => {
              item.key = 1000
              this.$set(this.revealData[index], this.animalArray[index].active, item)
          })
      },
      async initData(count) {
          setTimeout(async () => {
              await this.getData()
              if (this.tableData && this.tableData.length > 0) {
                  if (new Date().getTime() - this.time > 4000) {
                      this.fail()
                  } else {
                      this.tableData.forEach((item, index) => {
                          item.key = 10000
                          this.$set(this.revealData[index], this.animalArray[index].active, item)
                      })
                  }
              } else {
                  if (count < 4) {
                      this.initData(count + 1)
                  } else {
                      this.fail()
                  }
              }
          }, 500)
      },
      async getData() {
          const res = await this.$service.award.applyResult(this.tradeNo)
          if (res && res.inventoryList) {
              this.tableData = res.inventoryList
              if (res.kingRealtime && res.kingRealtime.periodQuantity) {
                  this.periodQuantity = res.kingRealtime.periodQuantity
              }
              this.magicFireworksList = res.magicFireworksList
              if (res.richmanTicketRealtime && res.richmanTicketRealtime.changeTicket) {
                  this.changeTicket = res.richmanTicketRealtime.changeTicket
              } else {
                  this.changeTicket = 0
              }
          }
          this.spuIds = res.inventoryList.map(item => item.spu.id)
          return true
      },
      async fail() {
          this.stopPlay()
          this.goods = null
          this.tableData = null
          this.revealData = []
          this.$message.confirm(
              '购买结果请至订单详情查看',
              () => {
                  this.$router.replace('order_award')
              },
              '',
              ['去查看', '返回'],
              () => this.$router.back()
          )
      },
      async skipOther() {
          this.stopPlay()
          this.goods = null
          this.revealData = []
      },
      async showResult() {
          if (this.tableData && this.tableData.length > 0) {
              let array = [...this.tableData]
              if (this.magicFireworksList && this.magicFireworksList.length > 0) {
                  array = [...this.magicFireworksList, ...this.tableData]
              }
              if(!this.isDemo) {
                  const hideRes = await this.$service.award.hideTaskStart(JSON.stringify(this.spuIds))
                  if(hideRes === 1 || hideRes === 2) {
                      this.$refs.hiddenTaskRef.show(hideRes)
                  }
              }
              this.$refs.result.show(array, this.changeTicket)
              this.skipOther()
          } else {
              this.$message.showLoading()
              await this.getData()
              if (this.tableData && this.tableData.length > 0) {
                  let array = [...this.tableData]
                  if (this.magicFireworksList && this.magicFireworksList.length > 0) {
                      array = [...this.magicFireworksList, ...this.tableData]
                  }
                  if(!this.isDemo) {
                     const hideRes = await this.$service.award.hideTaskStart(JSON.stringify(this.spuIds))
                      if(hideRes === 1 || hideRes === 2) {
                          this.$refs.hiddenTaskRef.show(hideRes)
                      }
                  }
                  this.$refs.result.show(array, this.changeTicket)
                  this.skipOther()
              } else {
                  this.fail()
              }
              this.$message.hideLoading()
          }
      }
  }
}
</script>
<style>
page {
  background: #222335;
}
</style>
<style lang="scss" scoped>
.mask-page {
  position: fixed;
  z-index: 0;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba($color: #000000, $alpha: 0.4);
}
.mask-left {
  position: fixed;
  z-index: 0;
  left: 0;
  top: 0;
  bottom: 0;
  background: rgba($color: #000000, $alpha: 0.4);
  backdrop-filter: blur(1px);
}
.mask-right {
  position: fixed;
  z-index: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba($color: #000000, $alpha: 0.4);
  backdrop-filter: blur(1px);
}
.bg {
  position: fixed;
  z-index: -1;
  left: 0;
  right: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
}

.wrapper {
  height: calc(100vh - 115rpx - 40rpx);
  position: relative;
  .lottery_middle {
      position: absolute;
      left: 0;
      width: 100%;
  }
}
.bottom {
  position: fixed;
        left: 0;
        right: 0;
        bottom: 80rpx;
        animation: fade 0.3s;
        text-align: center;
        .bottom-btns {
            height: 162rpx;
            background: rgba(255, 255, 255, 0.3);
            width: 220rpx;
            height: 64rpx;
            font-size: 24rpx;
            line-height: 64rpx;
            text-align: center;
            display: inline-block;
            border-radius: 32rpx;
        }
}
.link {
  text-shadow: 0px 0px 20rpx #a76ef4;
  font-weight: 600;
  color: #a76ef4;
  font-size: 32rpx;
  padding-bottom: 75rpx;
  text-align: center;
}
.demo-btn {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding-bottom: 150rpx;
  image {
      width: 356rpx;
      height: 128rpx;
  }
}

@keyframes fade {
  from {
      opacity: 0.3;
  }
  to {
      opacity: 1;
  }
}

.height1 {
  height: 131px;
}
.height5 {
  height: 500px;
}
</style>