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

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

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 getList(pageNum: number, pageSize: number) {
  return appCouponUserCouponListPost({
    params: {
      pageNum,
      pageSize,
    }
  }) as any
}

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


const keyword = ref<string>("");
// 输入框是否聚焦
const isSearch = ref<boolean>(false);
// 是否禁用兑换按钮
const isDisabled = computed(() => {
  return !keyword.value;
});

function handleClearSearch() {
  isSearch.value = false;
}
function search(event: any) {
  if (!event.value) {
    isSearch.value = false;
  } else {
  }
}
const handleSearch = throttle(Config.throttleShortTime, search, {
  noLeading: true,
  noTrailing: false,
});

// 兑换
function handleSubmit() {
  console.log("兑换");
  appCouponExchangeCouponPost({
    body: {
      couponCode: keyword.value,
    }
  }).then(res=> {
    paging.value?.refresh()
    uni.showToast({
      title: t('toast.redemptionSuccessful'),
      icon: 'none'
    })
  })
}
</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
          class="flex items-center h-88rpx px-30rpx bg-#F2F3F6 rounded-88rpx box-border"
        >
          <image
            class="w-28rpx h-28rpx shrink-0"
            src="@img/chef/105.png"
          ></image>
          <wd-input
            no-border
            focus-when-clear
            type="text"
            v-model="keyword"
            :maxlength="120"
            :placeholder="t('pages-user.coupon.search-placeholder')"
            placeholderStyle="font-size: 30rpx;line-height: 42rpx;color: #4A4A4A;"
            custom-class="flex-1 ml-16rpx !bg-transparent"
            @clear="handleClearSearch"
            @input="handleSearch"
            @focus="isSearch = true"
            @blur="isSearch = false"
          />
        </view>
      </view>
    </template>

    <view class="px-30rpx my-38rpx" v-if="isSearch">
      <wd-button
        block
        custom-class="!h-108rpx !text-36rpx !rounded-16rpx"
        :disabled="isDisabled"
        @click="handleSubmit"
      >
        {{ t("pages-user.coupon.redeem-now") }}
      </wd-button>
    </view>

    <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">
              {{ dayjs(Number(item.snapshotValidEnd)).format('YYYY-MM-DD HH:mm') }}{{ isEnLocale() ? ' expires' : '到期' }}
            </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 class="h-84rpx lh-84rpx text-center text-28rpx text-#fff">
            {{ t('common.confirm') }}
        </view>
      </view>
    </template>

<!--    <view-->
<!--      v-if="dataList.length === 0 && !isSearch"-->
<!--      class="flex flex-col items-center mt-88rpx"-->
<!--    >-->
<!--      <image class="w-552rpx h-552rpx" src="@img/chef/104.png"></image>-->
<!--      <text class="text-28rpx text-#9E9E9E mt&#45;&#45;100rpx"-->
<!--        >{{ t('pages-user.coupon.no-coupons') }}</text-->
<!--      >-->
<!--    </view>-->
  </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>
