<template>
  <z-paging
    ref="pagingRef"
    v-model="seckillProdList"
    :auto="false"
    :paging-style="{'top': '0','background-color': '#f2f3f7'}"
    empty-view-text="很抱歉，没有相关商品"
    loading-more-no-more-text="没有更多了，看看别的吧"
    @query="onGetSeckillProdList"
  >
    <view class="Mall4j page-seckill-prods">
      <!-- 分类 -->
      <view
        v-if="primaryCategoryList.length"
        class="seckill-category"
      >
        <scroll-view
          scroll-x
          class="category-box"
        >
          <view
            v-for="(categoryItem, categoryIndex) in primaryCategoryList"
            :key="categoryIndex"
            class="item"
            :class="{'active':selectedItem===categoryIndex}"
            @click="onSwitchCategory(categoryItem.categoryId, categoryIndex)"
          >
            {{ categoryItem.name }}
          </view>
        </scroll-view>
      </view>

      <!-- 轮播图 -->
      <view class="banner">
        <swiper
          v-if="banners.length"
          class="img"
          indicator-dots
          indicator-color="rgba(255,252,255, .3)"
          indicator-active-color="rgba(255,252,255, .6)"
          autoplay
          circular
        >
          <swiper-item
            v-for="(imgItem, imgIdx) in banners"
            :key="imgIdx"
            class="item"
          >
            <img-show :src="imgItem" />
          </swiper-item>
        </swiper>
        <view
          v-else
          class="default-banner"
        >
          <image src="@/package-activities/static/images/flash-banner.jpg" />
        </view>
      </view>

      <!-- 时间场次 -->
      <view
        v-if="listSeckillTimes.length"
        class="sessions"
      >
        <view class="img">
          <image src="@/package-activities/static/images/seckill-img.png" />
        </view>
        <scroll-view
          scroll-x
          class="time-box"
        >
          <view
            v-for="(timeItem, timeIndex) in listSeckillTimes"
            :key="timeIndex"
            class="item"
            :class="{'active': selectedValue === timeIndex}"
            @tap="onSwitchTimeRange(timeItem, timeIndex)"
          >
            <view class="number">
              {{ timeItem.time + ':00' }}
            </view>
            <view class="state">
              {{ timeItem.dayType===0 ? currentHour >= timeItem.time ? '正在进行' : '即将开始': '明日开抢' }}
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 产品列表 -->
      <view
        v-if="seckillProdList.length"
        class="line-prods"
      >
        <view
          v-for="(prodItem, prodIndex) in seckillProdList"
          :key="prodIndex"
          class="item"
          @tap="onToProdDetailPage(prodItem.spuId, prodItem.spuActivity.sekillActivitySpuVO.seckillId)"
        >
          <view class="img">
            <img-show
              :src="prodItem.mainImgUrl"
              img-mode="aspectFit"
            />
          </view>
          <view class="text-box">
            <view class="name">
              {{ prodItem.spuName }}
            </view>
            <view class="price-btn">
              <view class="left">
                <view class="price">
                  <view class="symbol">
                    ￥
                  </view>
                  <view class="big">
                    {{ wxs.parsePrice(prodItem.spuActivity.sekillActivitySpuVO.seckillPrice)[0] + '.' + wxs.parsePrice(prodItem.spuActivity.sekillActivitySpuVO.seckillPrice)[1] }}
                  </view>
                </view>
                <view
                  v-if="prodItem.spuActivity.sekillActivitySpuVO.priceFee - prodItem.spuActivity.sekillActivitySpuVO.seckillPrice > 0"
                  class="sold"
                >
                  立减{{ (prodItem.spuActivity.sekillActivitySpuVO.priceFee - prodItem.spuActivity.sekillActivitySpuVO.seckillPrice) / 100 + `元,仅剩${prodItem.spuActivity.sekillActivitySpuVO.seckillTotalStocks}件` }}
                </view>
              </view>
              <view :class="['btn-box', currentHour < selectedLot ? 'gray-btn' : '']">
                <view class="text">
                  {{ currentHour < selectedLot ? '即将开始': '去抢购' }}
                </view>
                <view class="percent">
                  <view class="progress-bar">
                    <view
                      class="bg"
                      :style="{width: `${(prodItem.spuActivity.sekillActivitySpuVO.seckillOriginStocks - prodItem.spuActivity.sekillActivitySpuVO.seckillTotalStocks) / prodItem.spuActivity.sekillActivitySpuVO.seckillOriginStocks*100}%`}"
                    />
                  </view>
                  <view class="number">
                    {{ ((prodItem.spuActivity.sekillActivitySpuVO.seckillOriginStocks - prodItem.spuActivity.sekillActivitySpuVO.seckillTotalStocks) / prodItem.spuActivity.sekillActivitySpuVO.seckillOriginStocks*100).toFixed(0) }}%
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </z-paging>
</template>

<script setup>
const wxs = number()

onLoad(() => {
  onGetPlatformCategoryList()
})

/**
 * 用户点击右上角分享(勿删)
 */
onShareAppMessage(() => {})

// 获取平台一级分类列表
const primaryCategoryList = ref([]) // 一级分类列表
let selectedCategoryId = '' // 选中的分类
const onGetPlatformCategoryList = () => {
  http.request({
    url: '/tmerclub_seckill/ua/seckill_category/list',
    method: 'GET'
  }).then(res => {
    primaryCategoryList.value = res
    if (res.length) {
      selectedCategoryId = res[0].categoryId
    }
    onGetListSeckillTimes()
  })
}

/**
 * 获取时间段批次
 */
const currentHour = ref(new Date().getHours()) // 当前小时
const selectedLot = ref('')
const listSeckillTimes = ref([])
const banners = ref([]) // 轮播图
const onGetListSeckillTimes = () => {
  http.request({
    url: '/tmerclub_seckill/ua/seckill/list_seckill_times',
    method: 'GET'
  }).then(res => {
    if (res) {
      banners.value = res.imgUrls ? res.imgUrls.split(',') : []
      let list = []
      for (let i = 0; i < res.seckillTimeList.length; i++) {
        const hourItem = res.seckillTimeList[i]
        if (hourItem >= currentHour.value - 1) {
          list.push({ time: hourItem, dayType: 0 })
        }
      }
      const count = list.length - 5
      if (count < 0) {
        const tomorrowSeckillTimeList = []
        for (let i = 0; i < Math.abs(count); i++) {
          if (res.seckillTimeList[i] || res.seckillTimeList[i] === 0) {
            tomorrowSeckillTimeList.push({ time: res.seckillTimeList[i], dayType: 1 })
          }
        }
        list = list.concat(tomorrowSeckillTimeList)
      }
      listSeckillTimes.value = list
      selectedLot.value = list[0].time
      pagingRef.value?.reload()
    }
  })
}

/**
 * 获取秒杀商品列表
 */
const seckillProdList = ref([]) // 秒杀商品列表
const pagingRef = ref(null)
const onGetSeckillProdList = (pageNum, pageSize) => {
  const todayTs = new Date(new Date().toLocaleDateString()).getTime()
  const nextDayTs = new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000
  http.request({
    url: '/tmerclub_search/ua/search/search_page',
    method: 'GET',
    data: {
      pageNum,
      pageSize,
      spuType: 2,
      seckillCategoryId: selectedCategoryId,
      selectedLot: selectedLot.value,
      needActivity: 1,
      activityTime: isNextDay ? nextDayTs : todayTs
    }
  }).then(res => {
    if (res.list) {
      const spusList = res.list[0].spus.filter(x => x.spuActivity.sekillActivitySpuVO)
      // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
      pagingRef.value.complete(spusList)
    }
  })
}

// 切换分类
const selectedItem = ref(0) // 默认选中第一项分类
const onSwitchCategory = (categoryId, index) => {
  if (selectedItem.value === index) {
    return
  }
  selectedCategoryId = categoryId
  selectedItem.value = index
  pagingRef.value?.reload()
}

/**
 * 切换时间段
 */
// 1代表0点-0点 2代表2点-4点 以此类推，每加一为2个小时间隔，即有12个时间段
// 默认选中第一个时间
let isNextDay = false // 选择的时间段是否为第二天的
const selectedValue = ref(0)
const onSwitchTimeRange = (timeItem, timeIndex) => {
  if (selectedValue.value === timeIndex) {
    return
  }
  selectedLot.value = timeItem.time
  selectedValue.value = timeIndex
  isNextDay = Boolean(timeItem.dayType)
  pagingRef.value?.reload()
}

/**
 * 跳转到商品详情页
 */
const onToProdDetailPage = (spuId, seckillId) => {
  uni.navigateTo({
    url: `/pages/detail/detail?spuId=${spuId}&seckillId=${seckillId}`
  })
}
</script>

<style lang="scss" scoped>
@use "./seckill-prods.scss";
</style>
