<template>
  <div class="list flash-sale">
    <div class="content">
      <div class="list-banner">
        <img src="~/assets/images/flash-banner.jpg" alt />
      </div>
      <div class="goods-list">
        <div class="list-con">
          <div
            class="item sell-out"
            v-for="(item, index) in dataList"
            :key="index"
            @click="toSeckillDet(item.seckillSearchVO.seckillId)"
          >
            <div class="sellout-text" v-if="!item.seckillSearchVO.seckillTotalStocks">
              {{$t('spike.alreadyFinished')}}
            </div>
            <div class="goods-img">
              <img v-if="item.pic" :src="item.pic" alt @error="handlePicError"/>
              <img v-else src="~/assets/img/def.png" alt />
            </div>
            <div class="time-box" v-if="countdownList.length">
              <div class="text" style="textAlign:center">
                {{
                  countdownList[index].obj.signs !== 0 ? $t('spike.stillToGoBeforeTheEnd') : $t('spike.stillToGoBeforeTheStart')
                }}
              </div>
              <div class="time">
                <template v-if="countdownList[index].obj.day">
                  <span class="time-item">{{
                    countdownList[index].obj.day
                  }}</span>
                  <span class="time-text">{{$t('day')}}</span>
                </template>
                <span class="time-item">{{
                  countdownList[index].obj.hou
                }}</span>
                <span class="time-text">:</span>
                <span class="time-item">{{
                  countdownList[index].obj.min
                }}</span>
                <span class="time-text">:</span>
                <span class="time-item">{{
                  countdownList[index].obj.sec
                }}</span>
              </div>
            </div>
            <div class="goods-name">{{ item.prodName }}</div>
            <div class="rest-number">
              <div class="number-box">
                <div
                  class="percent"
                  :style="'width:' + item.salesRatio + '%'"
                ></div>
              </div>
              <div class="number-text">
                {{$t('spike.sold')}}
                <span class="number">{{ item.salesRatio }}%</span>
              </div>
            </div>
            <div class="goods-price">
              <div class="price">
                ￥
                <span class="big">{{ parsePrice(item.activityPrice)[0] }}</span>
                .{{ parsePrice(item.activityPrice)[1] }}
              </div>
              <div class="old-price">￥{{ toPrice(item.activityOriginalPrice) }}</div>
            </div>
          </div>
        </div>
        <!-- 页码 -->
        <pagination
          v-model="current"
          :pages="pages"
          @changePage="getSearchProdPage"
        ></pagination>
        <!-- /页码 -->

        <!-- 商品列表为空 -->
        <div class="empty" v-if="!dataList.length">
          <div class="img">
            <img src="~/assets/images/emptyPic/not-found.png" alt />
          </div>
          <div class="action">
            <div class="text">{{$t('sorryNoRelatedProducts')}}</div>
            <nuxt-link to="/list" class="btn">{{$t('lookAtOther')}}</nuxt-link>
          </div>
        </div>
        <!-- 商品列表为空 -->
      </div>
    </div>
  </div>
</template>

<script src='~/assets/js/load-transition'></script>
<script>
import util from '~/plugins/util'
import Pagination from '~/components/pagination'

export default {
  components: {
    Pagination
  },
  data () {
    return {
      // seckillList: [],  //秒杀列表
      countdownList: [], // 秒杀倒计时列表
      countdownStamplList: [], // 秒杀倒计时时间戳列表
      // salesRatio: 0,  //已售百分比
      dataList: [], //秒杀列表
      pages: 1, // 总页数
      current: this.$route.query.current || 1, // 当前页数
      timer: null
    }
  },
  mounted () {
    // 设置网页标题
    document.title = this.$t('commonHead.spikeSpecial')
    this.current = parseInt(this.$route.query.c) || 1
    this.getSearchProdPage(this.current)
  },
  methods: {
    /**
     * 加载默认图片
     */
    handlePicError(e){
       e.target.src=require('@/assets/img/def.png')
    },

    /**
     * 请求商品列表
     */
    getSearchProdPage (current) {
      var param = {
        current: current,
        size: 20, // 每页显示多少条
        prodType: 2,
        isActive: 1 // 过滤掉活动商品
      }
      // this.$axios.get('/seckill/pageProd', {
      this.$axios.get('/search/page', {
        params: param
      }).then(({ data }) => {
        this.pages = data.pages
        var countdownList = []
        var startTimee = []
        data.records[0].products = data.records[0].products.filter(el=> el.seckillSearchVO)
        this.dataList = data.records[0].products
        // 计算秒杀时间
        // let newTime = new Date().getTime()
        data.records[0].products.forEach((el, index) => {
          //已售百分比
          el.salesRatio = el.seckillSearchVO.seckillOriginStocks <= 0 ? 100 : parseInt(((el.seckillSearchVO.seckillOriginStocks - el.seckillSearchVO.seckillTotalStocks) / el.seckillSearchVO.seckillOriginStocks) * 100)
          let betweenTimestamp = util.betweenTimestamp(util.dateToTimestamp(el.seckillSearchVO.startTime), util.dateToTimestamp(el.seckillSearchVO.endTime))

          // 开始时间存入数组
          startTimee.push({
            startTime: util.dateToTimestamp(el.seckillSearchVO.startTime)
          })

          countdownList.push({
            obj: util.betweenTime(betweenTimestamp),
            stamp: betweenTimestamp
          });

          // 现在距离秒杀开始的时间判断
          // if(newTime<util.dateToTimestamp(el.startTime)){
          //     countdownList[index].obj.signs = 0
          // }

          // console.log(countdownList[index].obj.signs)

        })

        this.countdownList = countdownList
        this.countdown(startTimee)
      })
    },
    // 倒计时
    countdown (startTimee) {
      // signs = 0 是距离开始  signs = 1 是距离结束
      let newTime = new Date().getTime()
      this.countdownList.forEach((countdown, index) => {
        countdown.stamp = countdown.stamp > 0 ? countdown.stamp - 1000 :  countdown.stamp + 1000
        countdown.obj = util.betweenTime(countdown.stamp)
        // 现在距离秒杀开始的时间判断
        if (newTime < startTimee[index].startTime) {
          countdown.obj.signs = 0
        }

        if (countdown.stamp < 1000) {
          countdown.obj.signs = 0
        }

      })

      let countdownFlag =  this.countdownList.some((item,index) => {
        if (item.obj.day === '00' && item.obj.hou === '00' && item.obj.min === '00' && item.obj.sec === '00') {
          clearTimeout(this.timer)
          this.getSearchProdPage(this.current)
           return true
        }
        return false
      })

      if (!countdownFlag) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.countdown(startTimee)
        }, 1000)
      }

    },

    /**
     * 跳转秒杀详情
     */
    toSeckillDet (seckillId) {
      // const newPage = this.$router.resolve({ path: '/secdetail/' + seckillId })
      // window.open(newPage.href, '_blank')
      this.$router.push({ path: '/secdetail/' + seckillId })
    },

    //   startCountdown () {
    //   this.countdown = {
    //     stamp: this.countdown.stamp -= 1000,
    //     obj: util.betweenTime(this.countdown.stamp)
    //   }
    //   if (this.countdown.stamp < 1000) {
    //     clearTimeout(this.timer)
    //     this.isKilling = -1
    //     return
    //   } else {
    //     this.timer = setTimeout(() => {
    //       this.startCountdown()
    //     }, 1000);
    //   }
    // }

    /**
     * 处理价格样式
     */
    toPrice (val) {
      var val = Number(val)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，没有则自动补0
      return (val.toFixed(2))
    },
    parsePrice (val) {
      var val = Number(val)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    }
  },
  beforeDestroy () {
    clearTimeout(this.timer)
    // this.timer = ''
  },
}
</script>

<style scoped src='~/assets/css/list.css'>
</style>
