<template>
  <view class="collection-component" @click.stop="handleCollectionClick">
    <view class="icon-container">
      <!-- 未收藏图标 -->
      <image
          v-show="!isCollected"
          :class="['collection-icon', 'collected-icon', { 'slide-in': isAnimating && !isCollected }]"
          :src="uncollectedIcon"
          mode="aspectFit"
      />
      <!-- 已收藏图标 -->
      <image
          v-show="isCollected"
          :class="['collection-icon', 'uncollected-icon', { 'slide-out': isAnimating && isCollected }]"
          :src="collectedIcon"
          mode="aspectFit"
      />
    </view>
  </view>
</template>

<script lang="ts" setup>
import {debounce, throttle} from 'throttle-debounce'

// 定义组件属性
interface Props {
  /** 是否已收藏 */
  isCollected: boolean
  /** 节流延迟时间（毫秒） */
  throttleDelay?: number
  /** 防抖延迟时间（毫秒） */
  debounceDelay?: number
  /** 是否禁用点击 */
  disabled?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isCollected: false,
  throttleDelay: 300,
  debounceDelay: 500,
  disabled: false
})

// 定义事件
const emit = defineEmits<{
  /** 收藏状态改变事件 */
  'collection-change': [isCollected: boolean]
  /** 点击事件 */
  'click': [event: any]
}>()

// 图标路径
const uncollectedIcon = '/static/images/chef/196.png'
const collectedIcon = '/static/images/chef/197.png'

// 动画状态
const isAnimating = ref(false)

// 节流处理函数
const throttledEmit = throttle(props.throttleDelay, (isCollected: boolean) => {
  emit('collection-change', isCollected)
})

// 防抖处理函数
const debouncedEmit = debounce(props.debounceDelay, (isCollected: boolean) => {
  emit('collection-change', isCollected)
})

// 点击处理函数
const handleCollectionClick = (event: any) => {
  if (props.disabled) {
    return
  }

  // 触发点击事件
  emit('click', event)

  // 开始动画
  isAnimating.value = true

  // 立即触发状态变化
  throttledEmit(!props.isCollected)
  debouncedEmit(!props.isCollected)

  // 动画结束后重置状态
  setTimeout(() => {
    isAnimating.value = false
  }, 300)
}
</script>

<style lang="scss" scoped>
.collection-component {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;

  &:active {
    transform: scale(0.95);
  }

  .icon-container {
    position: relative;
    width: 40rpx;
    height: 40rpx;
    overflow: hidden;
  }

  .collection-icon {
    position: absolute;
    top: 0;
    left: 0;
    width: 40rpx;
    height: 40rpx;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    &.uncollected-icon {
      transform: translateY(0);
      opacity: 1;

      &.slide-out {
        transform: translateY(-100%);
        opacity: 0;
      }
    }

    &.collected-icon {
      transform: translateY(0);
      opacity: 1;

      &.slide-in {
        animation: slide-in-from-bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }
    }
  }
}

@keyframes slide-in-from-bottom {
  0% {
    transform: translateY(100%);
    opacity: 0;
  }
  100% {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
