<script lang="ts" setup>
import { useDebounceFn } from '@vueuse/core'
import { showToast } from 'vant'
import { fetchCancelCollection, fetchSubmitCollection } from '@/api/answer'
import { AiAnswerProvideKey } from '@/components/AiAnswer/type'

const props = withDefaults(defineProps<Props>(), {
  recordId: '',
})

interface Props {
  recordId: string
}

const isCollectionned = ref(false)
const collectionFlag = inject(AiAnswerProvideKey)?.collectionFlag

const onAddCollection = useDebounceFn(async () => {
  const res = await fetchSubmitCollection(props.recordId)
  if (res) {
    isCollectionned.value = true
    showToast('收藏成功')
  }
}, 300)

const onDelCollection = useDebounceFn(async () => {
  const res = await fetchCancelCollection(props.recordId)
  if (res) {
    isCollectionned.value = false
    showToast('取消收藏成功')
  }
}, 300)

watch(() => collectionFlag?.value, (val) => {
  isCollectionned.value = val as boolean
}, {
  immediate: true,
  deep: true,
})
</script>

<template>
  <div class="collection-btn-wrap">
    <SvgIcon v-if="!isCollectionned" size="22px" name="collectionD" @click="onAddCollection" />
    <SvgIcon v-else size="22px" name="collection" @click="onDelCollection" />
  </div>
</template>
