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

interface Props {
  recordId: string
}

const props = defineProps<Props>()

const emits = defineEmits(['onAddLike', 'onDelLike'])
const isLike = ref(false)
const likeFlag = inject(AiAnswerProvideKey)?.likeFlag

// onAddLike 防抖处理
const onAddLike = useDebounceFn(async () => {
  const res = await fetchSubmitFeedback({
    recordId: props.recordId,
    feedbackStatus: '01',
    content: '',
  })
  if (res) {
    showToast('感谢您的反馈')
    isLike.value = true
    emits('onAddLike')
  }
}, 300)

function toggleFalse() {
  isLike.value = false
}

// onDelLike 防抖处理
const onDelLike = useDebounceFn(async () => {
  const res = await fetchSubmitFeedback({
    recordId: props.recordId,
    feedbackStatus: '00',
    content: '',
  })
  if (res) {
    isLike.value = false
    emits('onDelLike')
    showToast('已取消反馈')
  }
}, 300)

defineExpose({
  toggleFalse,
})

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

<template>
  <div class="like-btn-wrap">
    <SvgIcon v-if="!isLike" size="22px" name="likeG" @click="onAddLike" />
    <SvgIcon v-else size="22px" name="likeL" @click="onDelLike" />
  </div>
</template>
