<script setup lang="ts">
import {useConfigStore} from "@/store";
import {receiveCouponApi} from "@/pages-user/service";
const configStore = useConfigStore()

const { t, locale } = useI18n()
const emit = defineEmits(['confirm'])

const props = defineProps({
  couponList: {
    type: Array as unknown as PropType<any[]>,
    default: () => []
  }
})

const show = ref(false)
function init() {
  show.value = true
}

function handleClose() {
  show.value = false
}

function confirmCoupon(item: any) {
  receiveCouponApi(item.id).then(res => {
    if (res.code === 200) {
      uni.showToast({
        title: t('common.prompt.claimCouponSuccessfully'),
        icon: 'none'
      })
      emit('confirm')
    }
  })
}

defineExpose({
  init
});

function daySuffix(value: unknown) {
  const n = Number(value)
  const isEn = String(locale.value || '').toLowerCase().startsWith('en')
  if (isEn) {
    return n === 1 ? ` ${t('pages-store.store.day')}` : ` ${t('pages-store.store.days')}`
  }
  return t('pages-store.store.days')
}

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 couponTitleText(item: any) {
  const type = Number(item?.couponType)
  const discountValue = Number(item?.discountValue)

  // 标题保持原样：折扣券显示百分比，满减券只显示减免金额（不展示门槛）
  if (type === 1) {
    const pct = Number.isFinite(discountValue) ? Number(discountValue * 100).toFixed(0) : '0'
    return `${pct}% ${t('pages-store.store.couponOff')}`
  }

  return `$${formatMoney(discountValue)} ${t('pages-store.store.couponOff')}`
}

function couponBenefitText(item: any) {
  const type = Number(item?.couponType)
  const discountValue = Number(item?.discountValue)
  const minAmount = Number(item?.minAmount)

  if (type === 2) {
    const discountText = `$${formatMoney(discountValue)}`
    const hasMin = Number.isFinite(minAmount) && minAmount > 0
    if (hasMin) {
      const minText = `$${formatMoney(minAmount)}`
      return isEnLocale() ? `Min ${minText} · Off ${discountText}` : `满${minText}减${discountText} 优惠`
    }
    return isEnLocale() ? `Off ${discountText}` : `立减${discountText}`
  }

  const pct = Number.isFinite(discountValue) ? Number(discountValue * 100).toFixed(0) : '0'
  return `${pct}%`
}
</script>

<template>
  <wd-popup v-model="show" custom-style="border-radius:0;" position="bottom" @close="handleClose">
    <view class="bg-#F5F5F5 px-32rpx pt-30rpx">
      <view class="text-40rpx lh-40rpx text-#333 font-bold text-center mb-60rpx">{{ t('pages-store.store.claimCoupon') }}</view>
      <scroll-view scroll-y class="h-1000rpx">
        <template v-for="item in couponList" :key="item.id">
          <view class="coupon-item h-328rpx 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">
<!--                couponType 1-折扣券, 2-满减券-->
                {{ couponTitleText(item) }}
              </view>
              <view class="text-24rpx lh-32rpx text-#999 my-18rpx">
                {{ t('pages-store.store.validDays') }}: {{ item.validDays }}{{ daySuffix(item.validDays) }}
              </view>
              <view class="text-24rpx lh-32rpx text-#999 my-18rpx">
                {{ item.nameZh }}
              </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>
                {{ t('pages-store.store.get') }} {{ couponBenefitText(item) }}
                <template v-if="Number(item?.couponType) === 1"> {{ t('pages-store.store.couponOff') }}</template>
              </view>
            </view>
            <template v-if="item.userCouponVo">
              <view class="h-86rpx bg-#e6e6e6 lh-84rpx text-center text-28rpx text-#fff rounded-br-18rpx rounded-bl-18rpx">
                {{ t('pages-store.store.claimed') }}
              </view>
            </template>
            <template v-else>
              <view @click="confirmCoupon(item)" class="h-84rpx lh-84rpx text-center text-28rpx text-#fff">
                {{ t('pages-store.store.claimNow') }}
              </view>
            </template>
          </view>
        </template>
      </scroll-view>

      <view :style="[configStore.iosSafeBottomPlaceholder]" />
    </view>
  </wd-popup>
</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>