<script setup lang="ts">
import { debounce } from 'throttle-debounce'
import {appCollectListPost, appCollectCollectPost} from "@/service";
import Collection from "@/components/collection/index.vue";
import {CollectionType} from "@/constant/enums";

const {t} = useI18n()
const emit = defineEmits<{
  (e: 'batch-delete-success'): void
}>()
const props = defineProps({
  currentIndex: {
    type: Number,
    default: 0,
  },
  index: {
    type: Number,
    default: 0,
  },
  batchDeleteMode: {
    type: Boolean,
    default: false,
  },
})

const selectedIds = ref<string[]>([])

watch(() => props.batchDeleteMode, (v) => {
  if (!v) {
    selectedIds.value = []
  }
})

// (1, "菜谱")(2, "菜品")(3, "配菜")(4, "商家")
const typeList = [4,2,1]

watch(()=>props.currentIndex, (newVal, oldVal) => {
  console.log('currentIndex', newVal)
  console.log('props.index', props.index)
  if(newVal === props.index) {
    paging.value?.reload()
  }
})

const {paging, dataList, queryList, loading} = usePage<any>((pageNum: number, pageSize: number) =>
    appCollectListPost({
      params: {
        pageNum,
        pageSize,
      },
      body: {
        targetType: typeList[props.index]
      }
    }),
)


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

function navigateToDishes(item: any) {
  uni.navigateTo({
    url: '/pages-store/pages/store/dishes?id=' + item.id + '&storeId=' + item.merchantId,
  })
}

function getDishInfo(item: any) {
  return item?.merchantDishVo || item || {}
}

function getDishImage(item: any) {
  const dish = getDishInfo(item)
  return dish?.dishImage?.split?.(',')?.[0] || dish?.dishImage || ''
}

/** 当前列表 tab 对应的收藏目标 id（与 appCollectCollectPost 一致） */
function getCollectTargetId(item: any): string {
  const i = props.index
  if (i === 0) {
    return String(item.merchantVo?.id ?? item.merchantId ?? getDishInfo(item).merchantId ?? item.id ?? '')
  }
  if (i === 1) {
    return String(item.merchantDishVo?.id ?? getDishInfo(item).id ?? item.id ?? '')
  }
  if (i === 2) {
    return String(item.merchantRecipeVo?.id ?? item.id ?? '')
  }
  return ''
}

function toggleSelect(item: any) {
  if (!props.batchDeleteMode) return
  const id = getCollectTargetId(item)
  if (!id) return
  const idx = selectedIds.value.indexOf(id)
  if (idx >= 0) {
    selectedIds.value.splice(idx, 1)
  } else {
    selectedIds.value.push(id)
  }
}

function isSelected(item: any) {
  const id = getCollectTargetId(item)
  return id ? selectedIds.value.includes(id) : false
}

function onStoreOrDishRowClick(item: any) {
  if (props.batchDeleteMode) {
    toggleSelect(item)
    return
  }
  navigateToDishes(getDishInfo(item))
}

function onRecipeCardClick(item: any) {
  if (props.batchDeleteMode) {
    toggleSelect(item)
    return
  }
  navigateToRecipeDetail(item.merchantRecipeVo?.id ?? item.id)
}

function runBatchDelete() {
  if (selectedIds.value.length === 0) {
    uni.showToast({
      title: t('pages.mine.collectionSelectFirst'),
      icon: 'none',
    })
    return
  }
  uni.showModal({
    title: t('common.prompt.system-prompt'),
    content: t('pages.mine.collectionBatchDeleteConfirm', { count: selectedIds.value.length }),
    success: (res) => {
      if (!res.confirm) return
      const targetType = typeList[props.index] as number
      const ids = [...selectedIds.value]
      ;(async () => {
        try {
          for (const targetId of ids) {
            await appCollectCollectPost({
              body: {
                targetId,
                targetType,
              },
            })
          }
          selectedIds.value = []
          emit('batch-delete-success')
          paging.value?.reload()
          uni.showToast({
            title: t('toast.deleteSuccess'),
            icon: 'none',
          })
        } catch {
          uni.showToast({
            title: t('common.prompt.request-incorrect'),
            icon: 'none',
          })
        }
      })()
    },
  })
}

// 收藏菜谱
function handleSubmitCollectRecipe(item:any) {
  debouncedEmit(item.merchantRecipeVo?.isCollect, item.merchantRecipeVo?.id, CollectionType.RECIPE, ()=> {
    item.merchantRecipeVo.isCollect = !item.merchantRecipeVo?.isCollect
  })
}

// 防抖处理函数
const debouncedEmit = debounce(1300, (isCollected: boolean, id: string, type: CollectionType, callback: ()=> void) => {
  // 收藏接口
  appCollectCollectPost({
    body: {
      targetId: id,
      targetType: type
    }
  }).then(res=> {
    callback()
  })
}, {
  atBegin: true, // 立即触发
})

function navigateTo(url: string) {
  uni.navigateTo({ url })
}

function reload() {
  paging.value?.reload()
}

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

defineExpose({
  reload,
  refresh,
  runBatchDelete,
})
</script>

<template>
  <view class="h-full">
    <z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" :auto="false">
      <view class="p-30rpx">
        <template v-if="currentIndex == 0 || currentIndex == 1">
          <view class="collection-list">
            <view
              v-for="item in dataList"
              :key="item.id"
              class="collection-item"
              @click="onStoreOrDishRowClick(item)"
            >
              <view
                v-if="batchDeleteMode"
                class="collection-item__check"
                @click.stop="toggleSelect(item)"
              >
                <view class="check-box" :class="{ 'is-on': isSelected(item) }">
                  <text v-if="isSelected(item)" class="check-tick">✓</text>
                </view>
              </view>
              <image
                :src="getDishImage(item)"
                mode="aspectFill"
                class="collection-item__image"
              />
              <view class="collection-item__content">
                <view class="collection-item__name line-clamp-1">{{ getDishInfo(item).dishName }}</view>
                <view class="collection-item__price-row mt-10rpx">
                  <text class="collection-item__price">${{ getDishInfo(item).discountPrice }}</text>
                  <text
                    v-if="Number(getDishInfo(item).originalPrice) > 0"
                    class="collection-item__original ml-10rpx"
                  >
                    ${{ getDishInfo(item).originalPrice }}
                  </text>
                </view>
                <view v-if="Number(getDishInfo(item).memberPrice) > 0" class="collection-item__member mt-12rpx">
                  <image src="@img-store/1339.png" class="w-22rpx h-22rpx mr-6rpx" />
                  {{ t('pages.browse.brandTag') }} {{ t('pages-store.store.members') }}: ${{ getDishInfo(item).memberPrice }}
                </view>
                <view class="collection-item__sales mt-10rpx">
                  {{ t('pages-store.store.sales') }} : {{ getDishInfo(item).salesCount || 0 }}
                </view>
              </view>
              <view v-if="!batchDeleteMode" class="collection-item__add center">
                <text class="text-42rpx text-#333">+</text>
              </view>
            </view>
          </view>
        </template>
        <template v-if="currentIndex == 2">
          <view class="grid grid-cols-2 gap-30rpx">
            <view v-for="item in dataList" :key="item.id" class="recipe-card-wrap">
              <view
                v-if="batchDeleteMode"
                class="recipe-card__check"
                @click.stop="toggleSelect(item)"
              >
                <view class="check-box" :class="{ 'is-on': isSelected(item) }">
                  <text v-if="isSelected(item)" class="check-tick">✓</text>
                </view>
              </view>
              <view @click="onRecipeCardClick(item)" class="w-312rpx">
                <image
                    :src="item.merchantRecipeVo?.recipeImage?.split(',')[0]"
                    class="w-310rpx h-296rpx rounded-24rpx mb-26rpx"
                    mode="aspectFill"
                ></image>
                <view class="flex-center-sb">
                  <text class="text-30rpx lh-30rpx text-#333 line-clamp-1 tracking-[.04em] font-500"
                  >{{ item.merchantRecipeVo?.recipeName }}</text
                  >
                  <view v-if="!batchDeleteMode" class="w-40rpx h-40rpx ml-14rpx shrink-0">
                    <collection
                        :is-collected="item.merchantRecipeVo?.isCollect"
                        @collectionChange="handleSubmitCollectRecipe(item)"
                    />
                  </view>
                </view>
              </view>
            </view>
          </view>
        </template>
      </view>
    </z-paging>
  </view>
</template>

<style scoped lang="scss">
.collection-list {
  .collection-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f1f1f1;
  }

  .collection-item__image {
    width: 168rpx;
    height: 168rpx;
    border-radius: 20rpx;
    background: #f4f4f4;
    flex-shrink: 0;
  }

  .collection-item__content {
    flex: 1;
    margin-left: 20rpx;
    overflow: hidden;
  }

  .collection-item__name {
    font-size: 30rpx;
    line-height: 38rpx;
    color: #222;
    font-weight: 500;
  }

  .collection-item__price-row {
    display: flex;
    align-items: baseline;
  }

  .collection-item__price {
    color: #e7362f;
    font-size: 42rpx;
    line-height: 42rpx;
    font-weight: 600;
  }

  .collection-item__original {
    color: #a5a5a5;
    font-size: 28rpx;
    line-height: 28rpx;
    text-decoration: line-through;
  }

  .collection-item__member {
    display: inline-flex;
    align-items: center;
    color: #c5883f;
    font-size: 26rpx;
    line-height: 26rpx;
  }

  .collection-item__sales {
    width: fit-content;
    height: 42rpx;
    padding: 0 14rpx;
    border-radius: 10rpx;
    background: #f1f2f4;
    color: #9b9b9b;
    font-size: 24rpx;
    line-height: 42rpx;
  }

  .collection-item__add {
    width: 56rpx;
    height: 56rpx;
    border-radius: 50%;
    border: 1rpx solid #e6e6e6;
    margin-left: 14rpx;
    flex-shrink: 0;
  }

  .collection-item__check {
    width: 44rpx;
    margin-right: 12rpx;
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.check-box {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #c8c8c8;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
}

.check-box.is-on {
  border-color: #111;
  background: #111;
}

.check-tick {
  font-size: 24rpx;
  line-height: 24rpx;
  color: #fff;
  font-weight: 700;
}

.recipe-card-wrap {
  position: relative;
}

.recipe-card__check {
  position: absolute;
  z-index: 3;
  left: 8rpx;
  top: 8rpx;
}
</style>