<script setup lang="ts">
import {
  appCouponExchangeCouponPost,
  appCouponUserCouponListPost,
  appMerchantOrderCanUseCouponListMerchantIdGet
} from "@/service";

const { t, locale } = useI18n();
import { throttle } from "throttle-debounce";
import Config from "@/config";
import {dayjs} from "@/plugin";
import {useConfigStore} from "@/store";

const {proxy} = getCurrentInstance() as any

const eventChannel = proxy.getOpenerEventChannel();

const props = defineProps<{
  id?: string
}>()

function getList(pageNum: number, pageSize: number) {
  return new Promise(resolve => {
    appMerchantOrderCanUseCouponListMerchantIdGet({
      params: {
        merchantId: props.id || '',
      }
    }).then(res => {
      resolve({ rows: res.data } as any)
    })
  }) as any
}

const {paging, loading, firstLoaded, dataList, queryList} = usePage<any>(getList)

function isEnLocale() {
  return String(locale.value || '').toLowerCase().startsWith('en')
}

function formatMoney(value: unknown) {
  const n = Number(value)
  if (!Number.isFinite(n)) return '0.00'
  return n.toFixed(2)
}

function formatCouponDetail(item: any) {
  const type = Number(item?.snapshotType)
  const discount = Number(item?.snapshotDiscount)
  const minAmount = Number(item?.snapshotMinAmount)

  // 1-折扣券(percentage), 2-满减券(amount off with minimum spend)
  if (type === 2) {
    const hasMin = Number.isFinite(minAmount) && minAmount > 0
    const discountText = `$${formatMoney(discount)}`
    if (hasMin) {
      const minText = `$${formatMoney(minAmount)}`
      return isEnLocale()
        ? `Min ${minText} · Off ${discountText}`
        : `满${minText}减${discountText}`
    }
    return isEnLocale() ? `Off ${discountText}` : `立减${discountText}`
  }

  if (type === 1) {
    const pct = Number.isFinite(discount) ? Number(discount * 100).toFixed(0) : '0'
    return `${pct}% ${t('pages-store.store.discount')}`
  }

  return t('pages-store.store.discount')
}

function confirmCoupon(item: any) {
  eventChannel.emit('selectedCoupon', item);
  uni.navigateBack()
}
</script>
<template>
  <z-paging
      ref="paging"
      :default-page-size="10"
      v-model="dataList"
      @query="queryList"
      bg-color="#fff"
  >
    <template #top>
      <navbar />
      <view class="px-30rpx pb-42rpx">
        <view class="text-46rpx text-#333 font-bold lh-46rpx mb-36rpx mt-10rpx">
          {{ t("pages-user.coupon.title") }}</view
        >
      </view>
    </template>
    <template v-for="item in dataList" :key="item.id">
      <view class="coupon-item h-328rpx mx-36rpx flex flex-col mb-30rpx last:mb-0">
        <view class="flex-1 pt-40rpx px-58rpx">
          <view class="line-clamp-1 text-34rpx lh-34rpx text-#333 font-bold">
            {{ item.snapshotNameZh }}
          </view>
          <view class="text-24rpx lh-32rpx text-#999 my-18rpx">
            {{ item.snapshotMerchantId ? t('pages-user.coupon.merchant-specific') : t('pages-user.coupon.all-merchants') }}
          </view>
          <view class="text-24rpx lh-32rpx text-#999 my-18rpx">
            {{ t('pages-user.coupon.expiry-date') }}{{ dayjs(Number(item.snapshotValidEnd))
              .format('MM:DD HH:mm:ss') }}
          </view>
          <view class="text-28rpx lh-28rpx text-#333 flex items-center">
            <image
                class="w-36rpx h-36rpx shrink-0 mr-10rpx"
                src="@img/chef/106.png"
            ></image>
            {{ formatCouponDetail(item) }}
          </view>
        </view>
        <view @click="confirmCoupon(item)" class="h-84rpx lh-84rpx text-center text-28rpx text-#fff">
          {{ t('common.confirm') }}
        </view>
      </view>
    </template>
  </z-paging>
</template>
<style scoped lang="scss">
.coupon-item {
  background-image: url('@img/chef/103.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
}
</style>
