<script setup lang="ts">
import { useSearchStore } from "@/store";
import { decodeRouteQueryValue } from "@/utils/utils";
import SwiperList from "./components/swiper-list/swiper-list.vue";
import Score from "@/components/filtrate-tool/components/score.vue";
import PriceChoose from "@/components/filtrate-tool/components/price-choose.vue";
import SortPopup from "@/pages/search/components/sort-popup.vue";

const _props = defineProps<{
  /** 少数构建下可能由路由注入；实际以 onLoad 的 query 为准 */
  keyword?: string;
}>();

const { t } = useI18n();

const searchStore = useSearchStore();

const keyword = ref(decodeRouteQueryValue(_props.keyword) || '');

/** uni-app：?keyword= 只在 onLoad 的 options 里；部分端会对已编码参数再编一层，需循环 decode */
onLoad((options?: Record<string, string | undefined>) => {
  const q = options?.keyword
  if (q == null || String(q).trim() === '') return
  const plain = decodeRouteQueryValue(q)
  if (plain) keyword.value = plain
})

function handleSearch() {
  nextTick(() => {
    if (keyword.value) {
      searchStore.setHistoryList(keyword.value);
    }
    if (swiperListRef.value) {
      swiperListRef.value[activeTab.value].refresh()
    }
  });
}

const swiperListRef = ref<InstanceType<typeof SwiperList>>()
const activeTab = ref(0);
const tabs = [
  { label: t('pages.search.result.food'), value: "food" },
  { label: t('pages.search.result.recipe'), value: "recipe" },
];
function handleTabChange(index: number) {
  console.log("切换到标签:", index);
}

const scoreRef = ref<InstanceType<typeof Score>>()
const priceChooseRef = ref<InstanceType<typeof PriceChoose>>()
const sortPopupRef = ref<InstanceType<typeof SortPopup>>()
function toggleScore() {
  if (scoreRef.value) {
    scoreRef.value.onOpen()
  }
}
const scoreRange = ref(''); // 星级评分
const price = ref(''); // 价格范围
function applyScore(value: string) {
  console.log('applyScore', value)
  scoreRange.value = value;
  nextTick(()=> {
    if (swiperListRef.value) {
      swiperListRef.value[0].refresh()
    }
  })
}
function togglePrice() {
  if (priceChooseRef.value) {
    priceChooseRef.value.onOpen()
  }
}
function applyPrice(value: string) {
  console.log('applyPrice', value)
  price.value = value;
  nextTick(()=> {
    if (swiperListRef.value) {
      swiperListRef.value[0].refresh()
    }
  })
}
function toggleSort() {
  if (sortPopupRef.value) {
    sortPopupRef.value.onOpen()
  }
}

const currentSort = ref(1); // 默认排序方式
function handleApply(sort: number) {
  console.log('sort', sort)
  currentSort.value = sort;
  nextTick(()=> {
    if (swiperListRef.value) {
      swiperListRef.value[1].refresh()
    }
  })
}

function recipeReset() {
  handleApply(1)
}

onMounted(()=> {
  if (swiperListRef.value) {
    swiperListRef.value[0].refresh()
  }
})
</script>

<template>
  <view class="search-result-page">
    <z-paging-swiper>
      <template #top>
        <header-search
          v-model="keyword"
          trailing-cart
          trailing-surface="white"
          class="search-result-page__header"
          :placeholder="t('components.search.placeholder')"
          @search="handleSearch"
        />
        <!-- <tab-switcher
          v-model="activeTab"
          :tabs="tabs"
          @change="handleTabChange"
        /> -->
      </template>
      <swiper
          class="h-full"
          :current="activeTab"
          disable-touch
        >
          <swiper-item
            class="swiper-item"
            v-for="(item, index) in tabs"
            :key="index"
          >
            <swiper-list ref="swiperListRef"
                         :activeTab="activeTab"
                         :currentIndex="index"
                         :currentSort="currentSort"
                         :keyword="keyword"
                         :scoreRange="scoreRange"
                         :price="price"
                         @toggleScore="toggleScore"
                         @togglePrice="togglePrice"
                         @toggleSort="toggleSort"
                         @reset="recipeReset"
            ></swiper-list>
          </swiper-item>
        </swiper>
    </z-paging-swiper>

    <!-- 星级筛选弹窗 -->
    <score @applyScore="applyScore" ref="scoreRef" />
    <price-choose @applyPrice="applyPrice" ref="priceChooseRef" />
    <!-- 菜谱筛选弹窗 -->
    <sort-popup ref="sortPopupRef" @apply="handleApply" />
  </view>
</template>

<style lang="scss">
page {
  background-color: #fff;
}
</style>

<style scoped lang="scss">
.search-result-page {
  min-height: 100vh;
  background: #fff;
}

.search-result-page__header {
  padding-bottom: 8rpx;
}

:deep(.wd-tabs__nav-item) {
  font-size: 40rpx;
  color: #666666;
}
:deep(.wd-tabs) {
  .wd-tabs__line {
    bottom: 0 !important;
    z-index: 99 !important;
    border-radius: 0 !important;
  }
}
</style>
