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

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

const { t } = useI18n()
const configStore = useConfigStore()

const paging = ref<ZPagingInstance | null>(null)
const dataList = ref<Record<string, unknown>[]>([])

async function onQuery(pageNum: number, pageSize: number) {
  try {
    const filterBody = props.buildQuery(props.routeQuery)
    const res = await getFeaturedDishList({
      pageNum,
      pageSize,
      ...filterBody,
    })
    const { rows, total } = parseFeaturedDishListRes(res)
    await paging.value?.completeByTotal(rows, total)
  } catch {
    await paging.value?.complete(false)
  }
}

const featuredDishColumns = computed(() => {
  const list = dataList.value
  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"
    bg-color="#f2f2f2"
    :auto="true"
    @query="onQuery"
  >
    <template #top>
      <navbar :title="pageTitle || ''" />
    </template>

    <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="getFeaturedDishImage(item)"
                mode="aspectFill"
                class="featured-dish-img"
              />
              <view
                v-if="isFeaturedDishSoldOut(item.stock)"
                class="featured-dish-sold-dim"
              />
              <image
                v-if="isFeaturedDishSoldOut(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="getFeaturedDishPromoLabel(item)"
                class="featured-dish-promo mt-16rpx"
              >
                <text class="featured-dish-promo-text">{{ getFeaturedDishPromoLabel(item) }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <template #bottom>
      <view class="h-24rpx"></view>
      <view :style="[configStore.iosSafeBottomPlaceholder]"></view>
    </template>
  </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.45;
}

.featured-dish-member {
  display: inline-flex;
  align-items: center;
  max-width: calc(100% - 88rpx);
}

.featured-dish-member-inner {
  display: inline-block;
  padding: 6rpx 18rpx;
  border-radius: 999rpx;
  background: linear-gradient(180deg, #fff5eb 0%, #ffe8d6 100%);
  color: #c45c1a;
  font-size: 24rpx;
  font-weight: 500;
  line-height: 1.35;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.featured-dish-add {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: #14181b;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.12);
}

.featured-dish-promo {
  padding: 12rpx 16rpx;
  border-radius: 12rpx;
  background: #fff0f0;
}

.featured-dish-promo-text {
  color: #e02e24;
  font-size: 22rpx;
  font-weight: 500;
  line-height: 1.4;
}

.dish-new-ribbon {
  position: absolute;
  top: 0;
  left: 0;
  width: 184rpx;
  height: 184rpx;
  overflow: hidden;
  z-index: 5;
  pointer-events: none;

  &__text {
    position: absolute;
    top: 26rpx;
    left: -66rpx;
    width: 240rpx;
    text-align: center;
    font-size: 22rpx;
    font-weight: 700;
    color: #fff;
    letter-spacing: 2rpx;
    line-height: 44rpx;
    background: #e23636;
    transform: rotate(-45deg);
  }
}
</style>
