<script setup lang="ts">
import usePage from "@/hooks/usePage";
import { appMerchantRecommendListPost, type MerchantVo } from "@/service";
import { useUserStore } from "@/store";
import FiltrateTool from "@/components/filtrate-tool/index.vue";
import PriceChoose from "@/components/filtrate-tool/components/price-choose.vue";
import Score from "@/components/filtrate-tool/components/score.vue";

const userStore = useUserStore();
const { t } = useI18n();

const props = defineProps({
  merchantCategoryIds: {
    type: [Number, String],
    default: null,
  },
});

const { paging, dataList, queryList } = usePage<MerchantVo>(getList);
function getList(pageNum: number, pageSize: number) {
  return new Promise((resolve) => {
    appMerchantRecommendListPost({
      params: {
        pageNum: pageNum,
        pageSize: pageSize,
      },
      body: {
        lat: userStore.userLocation.latitude,
        lng: userStore.userLocation.longitude,
        selfPickup: selfPickup.value,
        discount: discount.value,
        scoreRange: scoreRange.value || null,
        priceRange: price.value || null,
        merchantCategoryIds: props.merchantCategoryIds
          ? [props.merchantCategoryIds]
          : [],
      },
    }).then((res) => {
      console.log(res);
      resolve({ rows: res.rows });
    });
  });
}

const selfPickup = ref<number | null>(null);
function togglePickup(value: number) {
  selfPickup.value = value;
  paging.value?.refresh();
}

const discount = ref<number | null>(null);
function toggleDiscount(value: number) {
  discount.value = value;
  paging.value?.refresh();
}

const scoreRef = ref<any>();
const scoreRange = ref<string | null>(null);
const priceChooseRef = ref<any>();
const price = ref<string | null>(null);
function toggleScore() {
  scoreRef.value?.onOpen();
}
function togglePrice() {
  priceChooseRef.value?.onOpen();
}

function applyScore(value: string) {
  scoreRange.value = value;
  nextTick(() => paging.value?.refresh());
}
function applyPrice(value: string) {
  price.value = value;
  nextTick(() => paging.value?.refresh());
}

/** 左侧双图：优先店铺图，不足则用 logo 补齐 */
function merchantImagePair(item: MerchantVo): [string, string] {
  const shop = (item.shopImages || "")
    .split(",")
    .map((s) => s.trim())
    .filter(Boolean);
  const logo = (item.logo || "").trim();
  let a = shop[0] || logo || "";
  let b = shop[1] || shop[0] || logo || "";
  if (!a && !b) return ["", ""];
  if (!b) b = a;
  if (!a) a = b;
  return [a, b];
}

function merchantCategoryLine(item: MerchantVo): string {
  const zh = item.merchantCategoryNamesZh;
  const en = item.merchantCategoryNamesEn;
  if (uni.getLocale() === "zh-Hans" && zh?.length) return zh[0] || "";
  if (en?.length) return en[0] || "";
  if (zh?.length) return zh[0] || "";
  return "";
}

function ratingStars(rating?: number) {
  const n = Math.min(5, Math.max(0, Math.round(Number(rating) || 0)));
  return n;
}

function ratingText(rating?: number) {
  const n = Number(rating);
  if (Number.isFinite(n)) return n.toFixed(1);
  return "0.0";
}

function openMerchant(item: MerchantVo) {
  if (item?.id == null) return;
  uni.navigateTo({
    url: `/pages-store/pages/store/index?id=${item.id}`,
  });
}
</script>

<template>
  <view class="home-store-page">
  <z-paging
    ref="paging"
    v-model="dataList"
    bg-color="#F2F3F5"
    @query="queryList"
  >
    <template #top>
      <view class="home-store-header">
        <navbar
          :title="t('pages.home.featured-on')"
          circle-back
          custom-class="!bg-white"
        />
      </view>
      <view class="home-store-filter-strip">
        <filtrate-tool
          class="home-store-filters"
          @togglePickup="togglePickup"
          @toggleDiscount="toggleDiscount"
          @toggleScore="toggleScore"
          @togglePrice="togglePrice"
        />
      </view>
    </template>

    <view class="home-store-list">
      <view
        v-for="(item, index) in dataList"
        :key="item.id ?? index"
        class="merchant-card"
        @click="openMerchant(item)"
      >
        <view class="merchant-card__imgs">
          <view
            v-for="(src, ii) in merchantImagePair(item)"
            :key="ii"
            class="merchant-card__img-slot"
            :class="
              ii === 0
                ? 'merchant-card__img-slot--first'
                : 'merchant-card__img-slot--last'
            "
          >
            <image
              v-if="src"
              class="merchant-card__img"
              :src="src"
              mode="aspectFill"
            />
            <view v-else class="merchant-card__img merchant-card__img--empty" />
          </view>
        </view>
        <view class="merchant-card__body">
          <text class="merchant-card__name">{{ item.merchantName }}</text>
          <text
            v-if="merchantCategoryLine(item)"
            class="merchant-card__cate"
            >{{ merchantCategoryLine(item) }}</text
          >
          <view class="merchant-card__rating">
            <text
              v-for="si in [1, 2, 3, 4, 5]"
              :key="si"
              class="merchant-card__star"
              :class="{
                'merchant-card__star--on': si <= ratingStars(item.rating),
              }"
              >★</text
            >
            <text class="merchant-card__score">{{
              ratingText(item.rating)
            }}</text>
          </view>
          <text class="merchant-card__tag">{{ t("pages.home.brandTag") }}</text>
        </view>
        <view class="merchant-card__go" @click.stop="openMerchant(item)">
          <view class="i-carbon:chevron-right merchant-card__go-icon"></view>
        </view>
      </view>
    </view>
  </z-paging>

  <score @applyScore="applyScore" ref="scoreRef" />
  <price-choose @applyPrice="applyPrice" ref="priceChooseRef" />
  </view>
</template>

<style scoped lang="scss">
.home-store-page {
  min-height: 100vh;
}

.home-store-header {
  background: #fff;
}

.home-store-filter-strip {
  background: #f2f3f5;
  padding-bottom: 8rpx;
}

.home-store-filters {
  display: block;
  padding: 16rpx 0 20rpx;
}

.home-store-list {
  padding: 16rpx 24rpx 40rpx;
  box-sizing: border-box;
}

.merchant-card {
  display: flex;
  flex-direction: row;
  align-items: center;
  background: #fff;
  border-radius: 24rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.06);
}

.merchant-card__imgs {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  width: 152rpx;
  flex-shrink: 0;
}

.merchant-card__img-slot {
  width: 152rpx;
  height: 96rpx;
  flex-shrink: 0;
  overflow: hidden;
  background: #e8eaed;
}

/* 仅外侧圆角；靠两张图之间的分割一侧为直角 */
.merchant-card__img-slot--first {
  border-radius: 12rpx 12rpx 0 0;
}

.merchant-card__img-slot--last {
  border-radius: 0 0 12rpx 12rpx;
}

.merchant-card__img {
  width: 100%;
  height: 100%;
  display: block;
  background: #e8eaed;
}

.merchant-card__img--empty {
  flex-shrink: 0;
  width: 100%;
  height: 100%;
}

.merchant-card__body {
  flex: 1;
  min-width: 0;
  padding: 0 20rpx 0 8rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.merchant-card__name {
  font-size: 30rpx;
  font-weight: 600;
  color: #14181b;
  line-height: 1.35;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.merchant-card__cate {
  margin-top: 8rpx;
  font-size: 26rpx;
  color: #333;
  line-height: 1.3;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.merchant-card__rating {
  margin-top: 12rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
  gap: 4rpx;
}

.merchant-card__star {
  font-size: 22rpx;
  line-height: 1;
  color: #e0e0e0;
  letter-spacing: -2rpx;
}

.merchant-card__star--on {
  color: #14181b;
}

.merchant-card__score {
  margin-left: 10rpx;
  font-size: 26rpx;
  font-weight: 600;
  color: #14181b;
}

.merchant-card__tag {
  margin-top: 10rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: #b8860b;
  line-height: 1.3;
}

.merchant-card__go {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  background: #14181b;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.merchant-card__go-icon {
  font-size: 28rpx;
  color: #fff;
  margin-left: 2rpx;
}
</style>

<style>
page {
  background-color: #f2f3f5;
}
</style>
