<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { debounce } from 'throttle-debounce'
import usePage from '@/hooks/usePage'
import { getFeaturedDishList } from '@/pages-store/service'
import { appCollectCollectPost } from '@/service'
import { CollectionType } from '@/constant/enums'
import { formatSalesCount } from '@/utils/utils'
import type { FeaturedDishQueryBody, RouteQueryMap } from '../utils/featured-dish-query'

const props = defineProps<{
  buildQuery: (routeQuery?: RouteQueryMap) => FeaturedDishQueryBody
  routeQuery?: RouteQueryMap
}>()

const { t } = useI18n()

function isSoldOutStock(stockLike: unknown) {
  const n = Number(stockLike)
  return !Number.isNaN(n) && n <= 0
}

function getDishPromoLabel(item: Record<string, unknown>): string {
  const raw = item.marketingLabel ?? item.hotSaleTag ?? item.rankTag ?? item.promotionLabel
  return typeof raw === 'string' && raw.trim() ? raw.trim() : ''
}

function dishImageSrc(item: Record<string, unknown>) {
  const url = item.dishImageUrl ?? item.dishImage
  if (typeof url === 'string' && url) return url.split(',')[0]
  return ''
}

const { paging, dataList, queryList } = usePage((pageNum, pageSize) => {
  const body = props.buildQuery(props.routeQuery)
  return getFeaturedDishList({
    pageNum,
    pageSize,
    ...body,
  }).then((res: { rows?: unknown[]; total?: number }) => ({
    rows: res?.rows ?? [],
    total: res?.total ?? 0,
  }))
})

const featuredDishColumns = computed(() => {
  const list = dataList.value as Record<string, unknown>[]
  return [
    list.filter((_, i) => i % 2 === 0),
    list.filter((_, i) => i % 2 === 1),
  ]
})

function navigateToDishes(item: Record<string, unknown>) {
  uni.navigateTo({
    url: `/pages-store/pages/store/dishes?id=${item.id}&storeId=${item.merchantId}`,
  })
}

const collectDish = debounce(
  1300,
  (item: Record<string, unknown>) => {
    appCollectCollectPost({
      body: {
        targetId: String(item.id),
        targetType: CollectionType.DISH,
      },
    }).then(() => {
      item.isCollect = !item.isCollect
    })
  },
  { atBegin: true },
)

defineExpose({
  refresh: () => paging.value?.refresh(),
})
</script>

<template>
  <z-paging
    ref="paging"
    v-model="dataList"
    :fixed="false"
    :auto="true"
    bg-color="#f2f2f2"
    @query="queryList"
  >
    <view class="featured-dishes-section px-24rpx pb-40rpx pt-16rpx">
      <view class="waterfall-row flex gap-16rpx items-start">
        <view
          v-for="(col, colIndex) in featuredDishColumns"
          :key="colIndex"
          class="waterfall-col flex-1 min-w-0 flex flex-col gap-16rpx"
        >
          <view
            v-for="item in col"
            :key="String(item.id ?? item.merchantId) + '-' + String(item.dishName)"
            class="featured-dish-card w-full"
            @click="navigateToDishes(item)"
          >
            <view class="featured-dish-image">
              <view v-if="item.isNew == 1" class="dish-new-ribbon">
                <text class="dish-new-ribbon__text">NEW</text>
              </view>
              <image
                :src="dishImageSrc(item)"
                mode="aspectFill"
                class="featured-dish-img"
              />
              <view
                v-if="isSoldOutStock(item.stock)"
                class="featured-dish-sold-dim"
              />
              <image
                v-if="isSoldOutStock(item.stock)"
                src="/static/app/images/SoldOut.png"
                mode="aspectFill"
                class="featured-dish-sold-overlay"
              />
              <view
                class="featured-dish-collect w-56rpx h-56rpx absolute z-4 top-12rpx right-12rpx center"
                @click.stop="collectDish(item)"
              >
                <image
                  v-if="!item.isCollect"
                  src="@img-store/1334.png"
                  mode="aspectFill"
                  class="w-44rpx h-44rpx featured-dish-collect-icon"
                />
                <image
                  v-else
                  src="@img-store/1337.png"
                  mode="aspectFill"
                  class="w-44rpx h-44rpx featured-dish-collect-icon"
                />
              </view>
            </view>
            <view class="featured-dish-body">
              <view class="featured-dish-meta flex items-start justify-between gap-12rpx mb-14rpx">
                <view class="min-w-0 flex-1">
                  <text class="featured-dish-price">US${{ item.originalPrice }}</text>
                </view>
                <text class="featured-dish-sales shrink-0">
                  {{ t('pages-store.store.sales') }}: {{ formatSalesCount(item.salesCount) }}
                </text>
              </view>
              <view class="featured-dish-title line-clamp-2 mb-16rpx">
                {{ item.dishName }}
              </view>
              <view class="flex items-center justify-between gap-12rpx">
                <view
                  v-if="Number(item.memberPrice) > 0"
                  class="featured-dish-member shrink min-w-0"
                >
                  <text class="featured-dish-member-inner">
                    {{ t('pages-store.store.members') }}: US${{ item.memberPrice }}
                  </text>
                </view>
                <view v-else class="flex-1 min-w-0"></view>
                <view class="featured-dish-add center shrink-0">
                  <image src="@img/chef/1285.png" class="w-28rpx h-28rpx" />
                </view>
              </view>
              <view
                v-if="getDishPromoLabel(item)"
                class="featured-dish-promo mt-16rpx"
              >
                <text class="featured-dish-promo-text">{{ getDishPromoLabel(item) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </z-paging>
</template>

<style scoped lang="scss">
.featured-dish-collect-icon {
  filter: drop-shadow(0 2rpx 6rpx rgba(0, 0, 0, 0.18));
}

.featured-dish-image {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 100%;
  background: #f0f0f0;
  overflow: hidden;
}

.featured-dish-img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  z-index: 1;
}

.featured-dish-sold-dim {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: 2;
  background: rgba(201, 197, 197, 0.6);
  pointer-events: none;
}

.featured-dish-sold-overlay {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 140rpx;
  height: 140rpx;
  z-index: 3;
  pointer-events: none;
}

.featured-dish-card {
  background: #fff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
}

.featured-dish-body {
  padding: 20rpx 20rpx 22rpx;
}

.featured-dish-price {
  color: #e02e24;
  font-size: 32rpx;
  font-weight: 600;
  line-height: 1.2;
}

.featured-dish-sales {
  color: #999;
  font-size: 24rpx;
  line-height: 1.35;
  max-width: 48%;
  text-align: right;
}

.featured-dish-title {
  color: #1a1a1a;
  font-size: 28rpx;
  font-weight: 500;
  line-height: 1.35;
}

.featured-dish-member-inner {
  font-size: 22rpx;
  color: #ce7138;
}

.featured-dish-member {
  padding: 4rpx 12rpx;
  background: rgba(206, 113, 56, 0.1);
  border-radius: 8rpx;
}

.featured-dish-add {
  width: 52rpx;
  height: 52rpx;
  border-radius: 50%;
  background: #14181b;
}

.featured-dish-promo-text {
  font-size: 22rpx;
  color: #666;
}

.dish-new-ribbon {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 4;
  padding: 6rpx 16rpx;
  background: linear-gradient(135deg, #ff6b35, #e02e24);
  border-radius: 0 0 16rpx 0;
}

.dish-new-ribbon__text {
  font-size: 20rpx;
  font-weight: 700;
  color: #fff;
  letter-spacing: 0.05em;
}
</style>
