<template>
  <z-paging
    ref="pagingRef"
    v-model="shopCouponList"
    :paging-style="{'top': '0','background-color': '#f2f3f7', 'bottom': 'calc(100rpx + env(safe-area-inset-bottom))'}"
    empty-view-text="商家还未发布优惠券哦"
    empty-view-img="/static/empty-img/coupon-empty.png"
    loading-more-no-more-text="没有更多了，看看别的吧"
    @query="onGetShopCoupon"
  >
    <view class="Mall4j page-coupon-center">
      <view class="banner">
        <image src="@/package-activities/static/images/coupon-banner.png" />
      </view>
      <view class="con-box">
        <view
          v-if="generalCouponData.length"
          class="c-tit"
        >
          通用神券
        </view>
        <scroll-view
          v-if="generalCouponData.length"
          scroll-x
          class="general-box"
        >
          <view class="general">
            <!-- class received已领取 robbed已抢光 -->
            <view
              v-for="(item,index) in generalCouponData"
              :key="index"
              class="item"
            >
              <view :class="['item-box', item.canGoUse ? 'received' : +item.stocks === 0 ? 'robbed' : '' ]">
                <view class="item-con">
                  <view
                    v-if="item.couponType === 1"
                    class="number"
                  >
                    <view class="symbol">
                      ￥
                    </view>
                    <view class="text">
                      {{ wxs.parsePrice(item.reduceAmount*100)[0] }}
                      <text class="small">
                        .{{ wxs.parsePrice(item.reduceAmount*100)[1] }}
                      </text>
                    </view>
                  </view>
                  <view
                    v-if="item.couponType === 2"
                    class="number"
                  >
                    <view class="text">
                      {{ item.couponDiscount }}
                    </view>
                    <view class="symbol">
                      折
                    </view>
                  </view>
                  <view class="condition">
                    满{{ item.cashCondition }}元可用
                  </view>
                  <view
                    v-if="item.suitableProdType === 0"
                    class="scope"
                  >
                    全品类商品通用
                  </view>
                  <view
                    v-if="item.suitableProdType === 1"
                    class="scope"
                  >
                    平台指定商品可用
                  </view>
                  <view class="progress-box">
                    <view class="text">
                      已抢{{ onHandleCouponProgress(item) }}%
                    </view>
                    <view
                      class="progress"
                      :style="'width: ' + onHandleCouponProgress(item) + '%'"
                    />
                  </view>
                </view>
                <view
                  v-if="!item.canGoUse && item.stocks"
                  class="item-btn"
                  :data-couponid="item.couponId"
                  :data-coupontype="1"
                  :data-couponindex="index"
                  @tap="onReceiveCoupon"
                >
                  立即领取
                </view>
                <view
                  v-if="item.canGoUse"
                  class="item-btn"
                  @tap="onToUseCoupon(item)"
                >
                  去使用
                </view>
                <view
                  v-if="!item.canGoUse && !item.stocks"
                  class="item-btn"
                >
                  已抢光
                </view>
                <view
                  v-if="item.canGoUse"
                  class="icon"
                >
                  <image src="@/package-activities/static/images/coupon-received.png" />
                </view>
                <view
                  v-if="!item.canGoUse && !item.stocks"
                  class="icon"
                >
                  <image src="@/package-activities/static/images/coupon-robbed.png" />
                </view>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="c-tit">
          推荐好券
        </view>
        <view class="special">
          <view
            v-for="(spuCoupon, spuIndex) in shopCouponList"
            :key="spuIndex"
            class="item"
          >
            <!-- 多商品券 -->
            <!-- class received已领取 robbed已抢光 -->
            <view
              v-if="spuCoupon.spus.length > 1"
              :class="['item-box', spuCoupon.canGoUse ? 'received' : +spuCoupon.stocks === 0 ? 'robbed' : '' ]"
            >
              <view class="item-con">
                <view class="shop-msg">
                  <view class="logo">
                    <image
                      v-if="!spuCoupon.shopLogo"
                      src="@/package-activities/static/images/default-shop-logo.png"
                    />
                    <image
                      v-else
                      :src="util.addDomain(spuCoupon.shopLogo)"
                      @error="spuCoupon.shopLogo=''"
                    />
                  </view>
                  <view
                    class="name"
                    @tap="onToShopPage(spuCoupon.shopId)"
                  >
                    {{ spuCoupon.shopName }}
                  </view>
                </view>
                <view class="prod-msg">
                  <view
                    v-for="spuItem in spuCoupon.spus"
                    :key="spuItem.spuId"
                    class="p-item"
                    @tap="onToProdDetailPage(spuItem.spuId)"
                  >
                    <view class="img">
                      <img-show
                        :src="spuItem.mainImgUrl"
                        img-mode="aspectFit"
                      />
                    </view>
                    <view
                      v-if="spuItem.priceFee"
                      class="price"
                    >
                      ￥{{ parseFloat(spuItem.priceFee) / 100 }}
                    </view>
                  </view>
                </view>
              </view>
              <view class="item-btn">
                <view class="btn-box">
                  <!-- 代金券 -->
                  <view
                    v-if="spuCoupon.couponType === 1"
                    class="number"
                  >
                    <view class="symbol">
                      ￥
                    </view>
                    <view class="text">
                      {{ wxs.parsePrice(spuCoupon.reduceAmount*100)[0] }}
                      <text class="small">
                        .{{ wxs.parsePrice(spuCoupon.reduceAmount*100)[1] }}
                      </text>
                    </view>
                  </view>
                  <!-- 折扣券 -->
                  <view
                    v-if="spuCoupon.couponType === 2"
                    class="number"
                  >
                    <view class="text word-style">
                      {{ spuCoupon.couponDiscount }}
                    </view>
                    <view class="symbol">
                      折
                    </view>
                  </view>
                  <view class="condition">
                    满{{ spuCoupon.cashCondition }}元可用
                  </view>
                  <view class="progress-box">
                    <!-- <view v-if="spuCoupon.stocks === 0" class="text">已抢光</view> -->
                    <!-- <view v-if="spuCoupon.stocks !== 0" class="text">已抢{{ parseInt((spuCoupon.totalStock - spuCoupon.stocks) * 100 / spuCoupon.totalStock) }}%</view> -->
                    <view class="text">
                      已抢{{ onHandleCouponProgress(spuCoupon) }}%
                    </view>
                    <view
                      class="progress"
                      :style="'width: ' + onHandleCouponProgress(spuCoupon) + '%'"
                    />
                  </view>
                  <view
                    v-if="!spuCoupon.canGoUse && spuCoupon.stocks"
                    class="btn"
                    :data-couponid="spuCoupon.couponId"
                    :data-coupontype="2"
                    :data-couponindex="spuIndex"
                    @tap="onReceiveCoupon"
                  >
                    立即领取
                  </view>
                  <view
                    v-if="spuCoupon.canGoUse"
                    class="btn"
                    @tap="onToUseCoupon(spuCoupon)"
                  >
                    去使用
                  </view>
                  <view
                    v-if="!spuCoupon.canGoUse && !spuCoupon.stocks"
                    class="btn"
                  >
                    已抢光
                  </view>
                </view>
              </view>
              <!-- 已领取 -->
              <!-- 已领取 -->
              <view
                v-if="spuCoupon.canGoUse"
                class="icon"
              >
                <image src="@/package-activities/static/images/coupon-received.png" />
              </view>
              <!-- 已抢光 -->
              <view
                v-if="!spuCoupon.canGoUse && !spuCoupon.stocks"
                class="icon"
              >
                <image src="@/package-activities/static/images/coupon-robbed.png" />
              </view>
            </view>
            <!-- 多商品券 end -->

            <!-- 单商品券 -->
            <!-- class received已领取 robbed已抢光 -->
            <view
              v-if="spuCoupon.spus.length === 1"
              :class="['item-box', spuCoupon.canGoUse ? 'received' : +spuCoupon.stocks === 0 ? 'robbed' : '' ]"
            >
              <view class="left">
                <view class="img">
                  <img-show :src="spuCoupon.spus[0].mainImgUrl" />
                </view>
                <view class="text-box">
                  <view class="goods-name">
                    {{ spuCoupon.spus[0].spuName }}
                  </view>
                  <view class="coupon-number">
                    <view
                      v-if="spuCoupon.couponType === 1"
                      class="number"
                    >
                      <view class="symbol">
                        ￥
                      </view>
                      <view class="text">
                        {{ spuCoupon.reduceAmount }}
                      </view>
                    </view>
                    <view
                      v-if="spuCoupon.couponType === 2"
                      class="number"
                    >
                      <view class="text">
                        {{ spuCoupon.couponDiscount }}
                      </view>
                      <view class="symbol">
                        折
                      </view>
                    </view>
                    <view class="condition">
                      满{{ spuCoupon.cashCondition }}元可用
                    </view>
                  </view>
                </view>
              </view>
              <view class="right">
                <view class="btn-box">
                  <view class="progress-text">
                    已抢{{ onHandleCouponProgress(spuCoupon) }}%
                  </view>
                  <view class="progress-box">
                    <view
                      class="progress"
                      :style="'width: ' + onHandleCouponProgress(spuCoupon) + '%'"
                    />
                  </view>
                  <view
                    v-if="!spuCoupon.canGoUse && spuCoupon.stocks"
                    class="btn"
                    :data-couponid="spuCoupon.couponId"
                    :data-coupontype="2"
                    :data-couponindex="spuIndex"
                    @tap="onReceiveCoupon"
                  >
                    立即领取
                  </view>
                  <view
                    v-if="spuCoupon.canGoUse"
                    class="btn"
                    @tap="onToUseCoupon(spuCoupon)"
                  >
                    去使用
                  </view>
                  <view
                    v-if="!spuCoupon.canGoUse && !spuCoupon.stocks"
                    class="btn"
                  >
                    已抢光
                  </view>
                </view>
              </view>
              <!-- 已领取 -->
              <view
                v-if="spuCoupon.canGoUse"
                class="icon"
              >
                <image src="@/package-activities/static/images/coupon-received.png" />
              </view>
              <!-- 已抢光 -->
              <view
                v-if="!spuCoupon.canGoUse && !spuCoupon.stocks"
                class="icon"
              >
                <image src="@/package-activities/static/images/coupon-robbed.png" />
              </view>
            </view>
          <!-- 单商品券 end -->
          </view>
        </view>
      </view>
    </view>
    <view class="coupon-foot">
      <view class="item">
        <view class="icon">
          <image src="@/package-activities/static/images/coupon-bar01.png" />
        </view>
        <view class="text">
          领券中心
        </view>
      </view>
      <view
        class="item"
        @tap="onToMyCoupons"
      >
        <view class="icon">
          <image src="@/package-activities/static/images/coupon-bar02.png" />
        </view>
        <view class="text">
          我的优惠券
        </view>
      </view>
    </view>
  </z-paging>
</template>

<script setup>
import util from '@/utils/util.js'

const wxs = number()

onLoad(() => {
  onQueryGeneralCoupon() // 平台券
})

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

// 处理优惠券领取进度
const onHandleCouponProgress = (item) => {
  const { totalStock, stocks } = item
  const progress = parseInt((totalStock - stocks) * 100 / totalStock)
  if (progress < 1 && totalStock - stocks !== 0) {
    return 1
  }
  return progress
}

// 获取（平台）通用券列表
const generalCouponData = ref([])
const onQueryGeneralCoupon = () => {
  http.request({
    url: '/mall4cloud_marketing/ma/coupon/general_coupon_list',
    method: 'GET'
  }).then(res => {
    res.forEach((item) => {
      item.reduceAmount = util.accuracyCount(item.reduceAmount, 100, 3)
      item.cashCondition = util.accuracyCount(item.cashCondition, 100, 3)
      item.canGoUse = item.hasReceive >= item.limitNum // 优惠券可以去使用的标记
    })
    generalCouponData.value = res
  })
}

// 获取（店铺）商品券列表(指定商品可用优惠券)
const pagingRef = ref(null)
const shopCouponList = ref([])
const onGetShopCoupon = (pageNum, pageSize) => {
  http.request({
    url: '/mall4cloud_marketing/ma/coupon/get_coupon_page',
    method: 'GET',
    data: {
      pageNum,
      pageSize
    }
  }).then(res => {
    const couponList = res.list.filter(el => {
      el.reduceAmount = util.accuracyCount(el.reduceAmount, 100, 3)
      el.cashCondition = util.accuracyCount(el.cashCondition, 100, 3)
      el.canGoUse = el.hasReceive >= el.limitNum // 优惠券可以去使用的标记
      return el.spus && el.spus.length > 0
    })
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    pagingRef.value.complete(couponList)
  })
}

// 立即领取
let isReceiving = false // 领券中
const onReceiveCoupon = (e) => {
  const couponIndex = e.currentTarget.dataset.couponindex
  const couponType = e.currentTarget.dataset.coupontype
  const couponId = e.currentTarget.dataset.couponid
  if (isReceiving) {
    return
  }
  isReceiving = true
  http.request({
    url: '/mall4cloud_marketing/my_coupon/receive',
    method: 'POST',
    data: String(couponId)
  }).then(res => {
    isReceiving = false
    uni.showToast({
      title: res,
      icon: 'none',
      duration: 1000
    })
    onSetCouponCanGoUseFlag(couponIndex, couponType)
  })
}

// 去使用
const onToUseCoupon = (item) => {
  uni.removeStorageSync('cloudCouponMsg')
  uni.setStorageSync('cloudCouponMsg', item)
  if (item.shopId) {
    // 店铺券 指定商品可用  对应店铺商品列表
    uni.navigateTo({
      url: '/package-shop/shop-page/shop-prods/shop-prods?shopId=' + item.shopId + '&couponId=' + item.couponId
    })
  } else {
    // 平台券 跳转到商品列表页
    uni.navigateTo({
      url: '/pages/coupon-products/coupon-products?couponId=' + item.couponId
    })
  }
}

// 设置优惠券可以去使用的标记 couponType 1:通用券 2:商品券
const onSetCouponCanGoUseFlag = (index, couponType) => {
  const idx = Number(index)
  const tempCouponList = couponType === 1 ? generalCouponData.value : couponType === 2 ? shopCouponList.value : []
  if (tempCouponList.length) {
    tempCouponList[idx].canGoUse = true
    tempCouponList[idx].stocks = tempCouponList[idx].stocks - 1
  }
}

// 跳转我的优惠券
const onToMyCoupons = () => {
  uni.navigateTo({
    url: '/package-activities/pages/my-coupons/my-coupons'
  })
}
// 跳转到店铺页
const onToShopPage = (shopId) => {
  http.request({
    url: '/mall4cloud_admin/ua/shop_detail/head_info',
    method: 'GET',
    data: {
      shopId,
      imgType: 0 // 图片类型：0.app(h5) 1.pc
    }
  }).then(res => {
    let url
    if (res.renovationId) {
      url = '/package-shop/shop-page/feature-index/feature-index?shopId=' + shopId + '&renovationId=' + res.renovationId
    } else {
      url = '/package-shop/shop-page/shop-index/shop-index?shopId=' + shopId
    }
    uni.navigateTo({
      url
    })
  })
}

// 跳转到商品详情页
const onToProdDetailPage = (spuId) => {
  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + spuId
  })
}
</script>
<style lang="scss" scoped>
@use "./coupon-center.scss";
</style>
