<script setup lang="ts">
import { computed, ref } from 'vue'
import { SlidingVertical } from '@icon-park/vue-next'
import { throttle } from 'lodash-es'
import { useI18n } from 'vue-i18n'
import HitKnowledgeItem from '@/views/personal-space/personal-app-setting/components/agent-config/agent-preview/components/hit-knowledge-item.vue'

interface Props {
  drawerToRef: string
  maxHeight: number
  knowledgeContentResult: KnowledgeContentResultItem[]
}

const props = defineProps<Props>()

const { t } = useI18n()

const isShowDrawer = defineModel<boolean>('isShow', { required: true })

const drawerHeight = ref(300)
const isResizing = ref(false) // 是否允许拖拽
const startY = ref(0) // 鼠标按下时的Y坐标
const startHeight = ref(0) // 初始高度

const MIN_HEIGHT = 80 // 最低高度

const maxHeight = computed(() => {
  return props.maxHeight - 80 || 80
})
function handleStartResize(event: MouseEvent) {
  isResizing.value = true
  startY.value = event.clientY
  startHeight.value = drawerHeight.value

  window.addEventListener('mousemove', onMouseMove)
  window.addEventListener('mouseup', stopResize)
}

const onMouseMove = throttle((event) => {
  if (isResizing.value) {
    const deltaY = event.clientY - startY.value
    let newHeight = startHeight.value - deltaY

    if (newHeight < MIN_HEIGHT) {
      newHeight = MIN_HEIGHT
    } else if (newHeight > maxHeight.value) {
      newHeight = maxHeight.value
    }

    drawerHeight.value = newHeight
  }
}, 16)

const stopResize = () => {
  isResizing.value = false
  window.removeEventListener('mousemove', onMouseMove)
  window.removeEventListener('mouseup', stopResize)
}
</script>

<template>
  <n-drawer
    v-model:show="isShowDrawer"
    placement="bottom"
    :height="drawerHeight"
    :show-mask="false"
    :trap-focus="false"
    :block-scroll="false"
    class="shadow-[0_0_20px_rgba(0,4,65,0.07)]! mx-[25px]! rounded-[10px]! relative"
    :to="drawerToRef"
  >
    <SlidingVertical
      theme="outline"
      size="18"
      fill="#333"
      :stroke-width="3"
      class="absolute left-1/2 top-0 -translate-x-1/2 -translate-y-1/2 cursor-ns-resize"
      @mousedown="handleStartResize"
    />

    <n-drawer-content
      :title="t('personal_space_module.agent_module.agent_setting_module.agent_config_module.back_chunk_content')"
      header-class="border-b-0! p-5! pt-6! text-[16px]! font-family-medium!"
      body-content-class="px-5! py-0!"
      footer-class="border-t-0! py-2!"
      :native-scrollbar="false"
      closable
    >
      <div class="flex flex-col gap-[18px]">
        <HitKnowledgeItem
          v-for="(knowledgeContentResultItem, index) in knowledgeContentResult"
          :key="index"
          :content-result-item="knowledgeContentResultItem"
        />
      </div>
      <template #footer> </template>
    </n-drawer-content>
  </n-drawer>
</template>
