<script setup lang="ts">
import {appSearchSearchRecipePost, appRecipeCategoryListGet, appCollectCollectPost} from "@/service";
import {formatTimestamp} from "@/utils/utils";
import TabsType from "@/pages/home/components/tabbar-home/components/tabs-type.vue";
import Collection from "@/components/collection/index.vue";
import AnimatedButton from "@/pages/search/components/animated-button/animated-button.vue";
import SortPopup from "@/pages/search/components/sort-popup.vue";
import {CollectionType} from "@/constant/enums";
import {debounce} from "throttle-debounce";
const { t } = useI18n();
const recipeCategoryId = ref('')
const currentSort = ref(1)
const recipeTotal = ref('')
const { paging, dataList, loading, queryList, firstLoaded } = usePage((pageNum, pageSize) => {
  // 搜索菜谱
  return new Promise(resolve => {
    appSearchSearchRecipePost({
      body: {
        pageNum: pageNum,
        pageSize: pageSize,
        recipeCategoryId: recipeCategoryId.value, // 菜谱分类ID
        sortType: currentSort.value // 排序方式
      }
    }).then(res => {
      recipeTotal.value = res.total; // 更新菜谱数据总条数
      resolve({rows: res.rows})
    })
  })
})

const allRecipeCategoryList = ref([]) // 所有菜谱分类列表
function getRecipeCategory() {
  appRecipeCategoryListGet({}).then(res => {
    console.log('菜谱分类数据', res)
    allRecipeCategoryList.value = res.data;
    if (res.data.length > 0) {
      recipeCategoryId.value = res.data[0].id; // 默认选中第一个分类
      refresh()
    } else {
      recipeCategoryId.value = ''; // 没有分类时清空
    }
  })
}
function tabsTypeChange(data){
  console.log('选中的菜谱分类ID', data)
  recipeCategoryId.value = data;
  refresh()
}

function refresh() {
  if(paging.value) {
    paging.value.refresh()
  }
}

const sortPopupRef = ref(null)
function toggleSort() {
  if (sortPopupRef.value) {
    sortPopupRef.value.onOpen()
  }
}

const rotationCount = ref(0)
function handleReset() {
  currentSort.value = 1;
  rotationCount.value ++
  refresh()
}

function handleApply(sort: number) {
  currentSort.value = sort;
  refresh()
}

onLoad(()=> {
  // 获取菜谱分类数据
  getRecipeCategory()
})


// 收藏菜品
function handleSubmitCollectRecipe(item: any) {
  collectRecipe(item)
}
// 防抖处理函数
const collectRecipe = debounce(1000, (item: any) => {
  appCollectCollectPost({
    body: {
      targetId: item.id,
      targetType: CollectionType.RECIPE
    }
  }).then(res=> {
    item.isCollect = !item.isCollect;
  })
}, {
  atBegin: true, // 立即触发
});

function navigateToRecipeDetail(id: string | number) {
  navigateTo(`/pages-user/pages/recipe/index?id=${id}`)
}

function navigateTo(url: string) {
  uni.navigateTo({ url })
}
</script>

<template>
  <z-paging ref="paging" v-model="dataList" @query="queryList" :auto="false" bg-color="#fff">
    <template #top>
      <navbar/>
      <!-- 分类滚动区域 -->
      <tabs-type @changeType="tabsTypeChange" :currentId="recipeCategoryId" :list="allRecipeCategoryList" labelKey="categoryName" imgKey="categoryImage" class="my-36rpx" />
      <!-- 筛选结果 -->
      <view class="flex-center-sb px-30rpx mb-36rpx">
        <view class="text-36rpx lh-36rpx text-#333 font-500 tracking-[.04em]"
        >{{ recipeTotal }} {{ t('pages.search.result.result') }}</view
        >
        <view class="flex items-center gap-20rpx">
          <view
              @click="toggleSort"
              class="bg-#F2F2F2 h-64rpx rounded-64rpx px-24rpx center text-26rpx text-#333 lh-26rpx font-500"
          >
            <text v-if="+currentSort === 1">{{ t('components.searchSort.time') }}</text>
            <text v-if="+currentSort === 2">{{ t('components.searchSort.comment') }}</text>
            <text v-if="+currentSort === 3">{{ t('components.searchSort.thumbsUp') }}</text>
            <text v-if="+currentSort === 4">{{ t('components.searchSort.view') }}</text>
            <image
                src="@img/chef/101.png"
                class="w-24rpx h-24rpx ml-10rpx"
            ></image
            >
          </view>

          <animated-button
              button-class="bg-#F2F2F2 h-64rpx rounded-64rpx px-24rpx center text-26rpx text-#333 lh-26rpx font-500"
              @click="handleReset"
          >
            {{ t('common.reset') }}
            <image
                src="@img/chef/131.png"
                class="w-24rpx h-24rpx ml-10rpx transition-transform duration-600"
                :style="{ transform: `rotate(${rotationCount * 360}deg)` }"
            ></image>
          </animated-button>
        </view>
      </view>
    </template>
    <template v-for="(item,index) in dataList">
      <view @click="navigateToRecipeDetail(item.id)" :class="[index === 0 ? '' : 'mt-52rpx']" class="flex-center-sb px-30rpx">
        <image
            :src="item?.recipeImage?.split(',')[0]"
            mode="aspectFill"
            class="w-210rpx h-200rpx mr-28rpx shrink-0 rounded-24rpx"
        ></image>
        <view class="flex-1 h-200rpx">
          <view class="text-36rpx lh-40rpx text-#333 font-500 mb-40rpx line-clamp-1 tracking-[.04em]">{{ item.recipeName }}</view>
          <view class="text-30rpx lh-30rpx text-#333 tracking-[.04em]">
            {{ formatTimestamp(item?.createTime) }}
          </view>
          <view class="mt-42rpx flex items-center gap-30rpx text-#999 text-30rpx">
            <view class="flex items-center gap-10rpx">
              <collection :is-collected="item.isCollect"
                          @collectionChange="handleSubmitCollectRecipe(item)" />
              {{ item.collectCount }}
            </view>
            <view class="flex items-center gap-10rpx">
              <image
                  src="@img/chef/132.png"
                  class="w-40rpx h-40rpx"
              ></image>
              {{ item.commentCount }}
            </view>
          </view>
        </view>
      </view>
    </template>
  </z-paging>

  <!-- 菜谱筛选弹窗 -->
  <sort-popup ref="sortPopupRef" @apply="handleApply" />
</template>

<style scoped lang="scss">

</style>