<script setup lang="ts">
import FiltrateTool from "@/components/filtrate-tool/index.vue";
import SearchDishResultItem from "@/pages/search/components/search-dish-result-item.vue";
import TabsType from "@/pages/home/components/tabbar-home/components/tabs-type.vue";
import AnimatedButton from "../animated-button/animated-button.vue";
import Collection from "@/components/collection/index.vue";
import FoodSkeleton from "@/pages/search/components/food-skeleton.vue";
import RecipeSkeleton from "@/pages/search/components/recipe-skeleton.vue";
import {getDishListByCategoryId,appRecipeCategoryListGet, appSearchMerchantByDishPost, appSearchSearchRecipePost, appCollectCollectPost} from "@/service";
import {formatTimestamp} from "@/utils/utils";
import {useUserStore} from "@/store";
import { debounce } from 'throttle-debounce'
import {CollectionType} from "@/constant/enums";
const props = defineProps<{
  activeTab: number;
  currentIndex: number;
  keyword?: string;
  currentSort: number;
  scoreRange?: string;
  price?: string;
}>();
const emit = defineEmits(["toggleScore", "togglePrice", "toggleSort", "reset"]);
const { t } = useI18n();
const userStore = useUserStore();

// 菜谱数据总条数
const recipeTotal = ref(0);
// 美食数据总条数
const foodTotal = ref(0);
// 是否自提
const selfPickup = ref<number | null>(null)
function togglePickup(value: number) {
  selfPickup.value = value;
  refresh()
}
// 是否有折扣
const discount = ref<number | null>(null)
function toggleDiscount(value: number) {
  discount.value = value;
  refresh()
}
const { paging, dataList, loading, queryList, firstLoaded } = usePage((pageNum, pageSize) => {
  if(props.activeTab === 0) {
    // 搜索美食
    return new Promise(resolve => {
      getDishListByCategoryId({
        body: {
          keyword: props.keyword || '', // 搜索关键词
          pageNum: pageNum,
          pageSize: pageSize,
          selfPickup: selfPickup.value || undefined, // 是否自提
          discount: discount.value || undefined, // 是否有折扣 1是 2 否
          scoreRange: props.scoreRange || undefined, // 评分范围 比如 3-4
          priceRange: props.price || undefined, // 价格范围 比如 10-30
          sortType: 1, // 1系统推荐(按照喜好) 2 距离排序 3 评分排序
          lat: userStore.userLocation.latitude || undefined,
          lng: userStore.userLocation.longitude || undefined,
        },
      }).then(res => {
        foodTotal.value = res.total||res.data?.total||0; // 更新美食数据总条数
        resolve({rows: res.rows||res.data.rows})
      })
    })
  } else {
    // 搜索菜谱
    return new Promise(resolve => {
      appSearchSearchRecipePost({
        body: {
          keyword: props.keyword || '', // 搜索关键词
          pageNum: pageNum,
          pageSize: pageSize,
          recipeCategoryId: recipeCategoryId.value, // 菜谱分类ID
          sortType: props.currentSort // 排序方式
        }
      }).then(res => {
        recipeTotal.value = res.total; // 更新菜谱数据总条数
        resolve({rows: res.rows})
      })
    })
  }
});

// 食物加载状态
const loadingFoodState = ref(true)
// 菜谱加载状态
const loadingRecipeState = ref(true)
watch(() => props.activeTab, (val) => {
  if(val === props.currentIndex && props.activeTab === 0) {
    if(paging.value) {
      paging.value.refresh()
    }
  }
  if (+val === 0) {
    setTimeout(() => {
      loadingFoodState.value = true
    }, 100)
    setTimeout(() => {
      loadingFoodState.value = false
    }, 400)
  } else {
    setTimeout(() => {
      loadingRecipeState.value = true
    }, 100)
    setTimeout(() => {
      loadingRecipeState.value = false
    }, 400)
    if(val === props.currentIndex) {
      getRecipeCategory()
    }
  }
}, { immediate: true })

// 获取菜谱分类数据
const allRecipeCategoryList = ref([])
const recipeCategoryId = 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()
}

// 重置按钮旋转状态
const rotationCount = ref(0)

// 处理重置按钮点击
function handleReset() {
  rotationCount.value++
  emit('reset')
}

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

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

defineExpose({
  refresh,
})
</script>

<template>
  <z-paging
    ref="paging"
    v-model="dataList"
    @query="queryList"
    :fixed="false"
    :auto="false"
    bg-color="#ffffff"
  >
    <template v-if="activeTab === 0">
      <!-- <view
          class="animate-in fade-in animate-ease-out animate-duration-300"
          v-show="loadingFoodState"
      >
        <food-skeleton />
      </view> -->
      <view
          class="animate-in fade-in animate-ease-in animate-duration-300"
          v-show="!loadingFoodState"
      >
        <!-- 筛选工具 -->
        <!-- <filtrate-tool class="my-36rpx" @togglePickup="togglePickup" @toggleDiscount="toggleDiscount"  @toggleScore="emit('toggleScore')" @togglePrice="emit('togglePrice')" /> -->
        <view class="search-food-toolbar">
          <text class="search-food-toolbar__count">{{ foodTotal }} {{ t('pages.search.result.result') }}</text>
        </view>
        <view class="search-food-list">
          <search-dish-result-item v-for="item in dataList" :key="String(item.id)" :item="item" />
        </view>
      </view>
    </template>
    <template v-if="activeTab === 1">
      <view
          class="animate-in fade-in animate-ease-out animate-duration-300"
          v-show="loadingRecipeState"
      >
        <recipe-skeleton />
      </view>
      <view
          class="animate-in fade-in animate-ease-in animate-duration-300"
          v-show="!loadingRecipeState"
      >

        <!-- 分类滚动区域 -->
        <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="emit('toggleSort')"
                class="bg-#F2F2F2 h-64rpx rounded-64rpx px-24rpx center text-26rpx text-#333 lh-26rpx font-500"
            >
              <text v-if="+props.currentSort === 1">{{ t('components.searchSort.time') }}</text>
              <text v-if="+props.currentSort === 2">{{ t('components.searchSort.comment') }}</text>
              <text v-if="+props.currentSort === 3">{{ t('components.searchSort.thumbsUp') }}</text>
              <text v-if="+props.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 v-for="(item,index) in dataList">
          <view :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>
      </view>
    </template>
  </z-paging>
</template>

<style scoped lang="scss">
.search-food-toolbar {
  padding: 20rpx 24rpx 8rpx;
  background: #fff;
}
.search-food-toolbar__count {
  font-size: 26rpx;
  line-height: 34rpx;
  color: #999;
  font-weight: 400;
}
.search-food-list {
  background: #fff;
}
.search-food-list :deep(.search-dish-item:last-child) {
  border-bottom: none;
}
// 确保过渡动画平滑
.transition-transform {
  transition: transform 0.6s ease-in-out;
}
</style>
