<script lang="ts" setup>
import { onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useInfiniteScroll } from '@vueuse/core'
import ListItem from './ListItem.vue'
import { useTaskStore } from '@/store/modules/task'
import { useUser } from '@/store/modules/user'
import emitter from '@/utils/mitt'

defineOptions({ name: 'WorkSheetList' })

const taskStore = useTaskStore()
const data = ref<any[]>([])
const activeId = ref('')
const el = ref<HTMLDivElement | null>(null)
const keyword = ref('')
const canloadMore = ref(true)
const userStore = useUser()

const pagination = reactive({
  pageNo: 0,
  pageSize: 10,
})

function selectHandler(id: string, index: number) {
  taskStore.setActive(index)
}

const { isLoading } = useInfiniteScroll(
  el as any,
  () => {
    loadMore()
  },
  { distance: 10, interval: 300, canLoadMore: () => {
    // console.log('canloadmore excuted!')
    return canloadMore.value
  } },
)

async function loadMore() {
  if (isLoading.value || el.value == null)
    return

  const more = await fetchList()
  data.value.push(...more)
}

async function fetchList() {
  try {
    pagination.pageNo += 1
    const id = userStore.getUserInfo.id
    const result = await taskStore.fetchApprovalList(pagination, id)
    const { data, pageCount } = result
    canloadMore.value = pageCount >= pagination.pageNo && pageCount !== 0
    return data || []
  }
  catch (error) {
    canloadMore.value = false
    return []
  }
}

watch(() => taskStore.activeId, (newVal) => {
  activeId.value = newVal
})

function reset() {
  pagination.pageNo = 0
  pagination.pageSize = 10
  canloadMore.value = true
  data.value.length = 0
}

async function search(word: string) {
  keyword.value = word
  reset()
  useInfiniteScroll(
    el as any,
    () => {
      loadMore()
    },
    { distance: 10, canLoadMore: () => canloadMore.value },
  )
}

onMounted(() => {
  emitter.on('refresh', refreshHandler)
})

onUnmounted(() => {
  emitter.off('refresh', refreshHandler)
})

async function refreshHandler() {
  reset()
  search('')
}

defineExpose({
  search,
})
</script>

<template>
  <n-scrollbar>
    <n-spin :show="isLoading">
      <div ref="el">
        <ListItem
          v-for="(item, index) in data" :key="item.id" :selected="activeId === item.formid" :list-item="item"
          @click="selectHandler(item.id, index)"
        />
      </div>
    </n-spin>
  </n-scrollbar>
</template>

<style lang="less" scoped>
</style>
