<template>
  <z-paging
    ref="pagingRef"
    v-model="myCouponList"
    :paging-style="{'top': '0','background-color': '#f2f3f7'}"
    empty-view-text="您还没有优惠券，赶快去领券吧"
    empty-view-img="/static/empty-img/coupon-empty.png"
    loading-more-no-more-text="没有更多了，看看别的吧"
    class="Mall4j page-my-coupons"
    @query="onQueryMyCouponData"
  >
    <template #top>
      <!-- 未使用 -->
      <view
        v-if="!isUsedStatusPage"
        class="tab unused"
      >
        <view
          :class="['item', navStatus === 0 ? 'active' : '']"
          @tap="onChangeNav(0)"
        >
          全部
          <text
            v-if="couponQuantity.allCount || couponQuantity.allCount === 0"
            class="number"
          >
            {{ '(' + couponQuantity.allCount + ')' }}
          </text>
        </view>
        <view
          :class="['item', navStatus === 1 ? 'active' : '']"
          @tap="onChangeNav(1)"
        >
          平台券
          <text
            v-if="couponQuantity.platformCount || couponQuantity.platformCount === 0"
            class="number"
          >
            {{ '(' + couponQuantity.platformCount + ')' }}
          </text>
        </view>
        <view
          class="item"
          :class="['item', navStatus === 2 ? 'active' : '']"
          @tap="onChangeNav(2)"
        >
          店铺券
          <text
            v-if="couponQuantity.multishopCount || couponQuantity.multishopCount >= 0"
            class="number"
          >
            {{ '(' + couponQuantity.multishopCount + ')' }}
          </text>
        </view>
      </view>
      <!-- 已使用 -->
      <view
        v-if="isUsedStatusPage"
        class="tab used"
      >
        <view
          class="item"
          :class="['item', navStatus === 3 ? 'active' : '']"
          @tap="onChangeNav(3)"
        >
          已使用
          <text
            v-if="couponQuantity.useCount || couponQuantity.useCount === 0"
            class="number"
          >
            {{ '(' + couponQuantity.useCount + ')' }}
          </text>
        </view>
        <view
          class="item"
          :class="['item', navStatus === 4 ? 'active' : '']"
          @tap="onChangeNav(4)"
        >
          已过期
          <text
            v-if="couponQuantity.expiredCount || couponQuantity.expiredCount === 0"
            class="number"
          >
            {{ '(' + couponQuantity.expiredCount + ')' }}
          </text>
        </view>
      </view>
    </template>
    <view class="coupons-box">
      <div>
        <view
          v-if="couponType === 1"
          class="coupon-tit"
        >
          <text class="tit-text">
            平台优惠券
          </text>
          <text class="tit-des">
            （部分特殊商品除外）
          </text>
        </view>
        <view
          v-if="couponType === 2"
          class="coupon-tit"
        >
          <text class="tit-text">
            店铺优惠券
          </text>
          <text class="tit-des">
            （可用于指定店铺商品）
          </text>
        </view>
        <view
          v-for="(item, index) in myCouponList"
          :key="index"
          :class="['coupon-item', item.status === 0 ? 'unavailable' : '', item.shopId === 0 ? 'general':'']"
        >
          <view class="item-box">
            <view class="text-box">
              <view class="c-des">
                <text class="c-style">
                  {{ item.shopId !== 0 ? '店铺' : '平台' }}
                </text>
                <text
                  v-if="item.shopId !== 0"
                  class="text"
                >
                  可用于购买{{ item.shopName }}{{ item.suitableProdType === 0 ? '全部' : '指定' }}商品
                </text>
                <text
                  v-if="item.shopId === 0"
                  class="text"
                >
                  {{ item.suitableProdType === 0 ? '平台全品类商品' : '平台指定商品' }}
                </text>
              </view>
              <view class="c-time">
                {{ item.startTime }} - {{ item.endTime }}
              </view>
              <view
                class="c-det"
                @tap="onPullDownDetails(myCouponList, index)"
              >
                <view class="text">
                  详细信息
                </view>
                <view
                  class="arrow"
                  :class="{'up-arrow' : item.isShowCouponDet}"
                />
              </view>
            </view>
            <view class="c-price">
              <view class="price-box">
                <view
                  v-if="item.couponType === 1"
                  class="price"
                >
                  <view class="symbol">
                    ￥
                  </view>
                  <view>
                    <text class="big">
                      {{ onParsePrice(+item.reduceAmount)[0] }}
                    </text>
                    <text class="small">
                      .{{ onParsePrice(+item.reduceAmount)[1] }}
                    </text>
                  </view>
                </view>
                <view
                  v-if="item.couponType === 2"
                  class="price"
                >
                  <view class="big">
                    {{ item.couponDiscount }}
                  </view>
                  <view class="symbol">
                    折
                  </view>
                </view>
                <view class="c-condition">
                  满{{ item.cashCondition }}元可用
                </view>
                <view
                  v-if="item.status !== 0 && item.status !== 2"
                  class="btn"
                  @tap="onToUseCoupon(item)"
                >
                  立即使用
                </view>
              </view>
            </view>
            <!-- 已过期 -->
            <view
              v-if="item.status === 0"
              class="un-icon"
            >
              <image src="@/package-activities/static/images/coupon-expired.png" />
            </view>
            <!-- 已使用 -->
            <view
              v-if="item.status === 2"
              class="un-icon"
            >
              <image src="@/package-activities/static/images/coupon-used.png" />
            </view>
          </view>
          <view
            class="c-det-box"
            :class="{'active' : item.isShowCouponDet}"
          >
            <!-- <view class="det-item">券数量：{{ item.couponCount }}张</view> -->
            <!-- 店铺 -->
            <view
              v-if="item.shopId !== 0"
              class="det-item"
            >
              限品类：{{ item.shopName }}内{{ item.suitableProdType === 0 ? '全部' : '指定' }}商品可用
            </view>
            <view
              v-if="item.shopId !== 0"
              class="det-item"
            >
              限平台：仅限在{{ item.shopName }}内使用
            </view>
            <!-- 平台 -->
            <view
              v-if="item.shopId === 0"
              class="det-item"
            >
              限品类：可购买{{ item.suitableProdType === 0 ? '平台全品类商品' : '平台指定商品' }}
            </view>
            <view
              v-if="item.shopId === 0"
              class="det-item"
            >
              限平台：{{ item.suitableProdType === 0 ? '全平台通用' : '全平台指定商品可用' }}
            </view>
          </view>
        </view>
      </div>
    </view>
    <!-- 底部 -->
    <view class="coupon-foot">
      <view
        class="coupon-btn"
        @tap="onSwitchPage"
      >
        {{ isUsedStatusPage ? '未使用的优惠券' : '使用记录' }}
      </view>
      <view
        class="coupon-btn"
        @tap="onToCouponCenter"
      >
        领更多好券
      </view>
    </view>
  </z-paging>
</template>

<script setup>
onLoad(() => {
  onQueryMyCouponQuantity() // 请求用户优惠券数量
})

/**
 * 请求用户优惠券数量
 */
const couponQuantity = ref({}) // 优惠券数量
const onQueryMyCouponQuantity = () => {
  http.request({
    url: '/mall4cloud_marketing/my_coupon/get_my_coupons_status_or_type_count',
    method: 'GET'
  }).then(res => {
    couponQuantity.value = res
  })
}

/**
 * 请求我的优惠券列表
 */
const pagingRef = ref(null)
const myCouponList = ref([]) // 我的优惠券列表
const couponStatus = ref(1) // 优惠券状态 0:过期 1:未过期 2:使用过
const couponType = ref(0) // 0：所有 1：平台优惠券 2：店铺优惠券
const onQueryMyCouponData = (pageNum, pageSize) => {
  http.request({
    url: '/mall4cloud_marketing/my_coupon/get_page',
    method: 'GET',
    data: {
      pageNum, // 每页大小
      pageSize, // 当前页
      status: couponStatus.value,
      type: couponType.value
    }
  }).then(res => {
    res.list.forEach(couponItem => {
      const newStartTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(couponItem.startTime)
      const newEndTime = /\d{4}-\d{1,2}-\d{1,2}/g.exec(couponItem.endTime)
      couponItem.startTime = newStartTime[0]
      couponItem.endTime = newEndTime[0]
      couponItem.reduceAmount = util.accuracyCount(couponItem.reduceAmount, 100, 3)
      couponItem.cashCondition = util.accuracyCount(couponItem.cashCondition, 100, 3)
    })
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    pagingRef.value.complete(res.list)
  })
}

/**
 * 切换使用状态页面
 */
const isUsedStatusPage = ref(false) // 是否已使用状态页面
const navStatus = ref(0) // 切换导航nav
const onSwitchPage = () => {
  isUsedStatusPage.value = !isUsedStatusPage.value
  let sts
  if (isUsedStatusPage.value) { // 已使用状态
    sts = navStatus.value && navStatus.value > 2 ? navStatus.value : 3
    onChangeNav(sts)
  } else {
    sts = navStatus.value && navStatus.value <= 2 ? navStatus.value : 0
    onChangeNav(sts)
  }
}

/**
 * 切换nav
 * couponType 0全部 1平台券 2店铺券
 * couponStatus 优惠券状态 0:过期 1:未过期 2:使用过
 */
const onChangeNav = (sts) => {
  navStatus.value = sts
  if (sts <= 2) { // 0全部 1平台券 2店铺券
    couponType.value = sts
    couponStatus.value = 1
  } else if (sts === 3) { // 已使用
    couponType.value = 0
    couponStatus.value = 2
  } else if (sts === 4) { // 已过期
    couponType.value = 0
    couponStatus.value = 0
  }
  pagingRef.value.reload() // 刷新列表
}

// 展示券详情
const onPullDownDetails = (list, index) => {
  list.forEach((coupon, idx) => {
    if (idx === index) {
      coupon.isShowCouponDet = !coupon.isShowCouponDet
    } else {
      coupon.isShowCouponDet = false
    }
  })
}

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

// 跳转领券中心
const onToCouponCenter = () => {
  uni.navigateTo({
    url: '/package-activities/pages/coupon-center/coupon-center'
  })
}

const onParsePrice = (val) => {
  if (!val) {
    val = 0
  }
  return val.toFixed(2).split('.')
}

</script>
<style lang="scss" scoped>
@use "./my-coupons.scss";
</style>
