<script lang="ts" setup>
import { useInfiniteScroll } from '@vueuse/core'
import { reactive, ref, unref, watch } from 'vue'
import ApprovalModal from '../modal/ApprovalModal.vue'
import ListItem from './ListItem.vue'
import type { PackageListItem } from '/#/workorder'
import { isEmpty } from '@/utils'
import { useWorkOrder } from '@/store/modules/workOrder'

defineProps({
  showFieldList: {
    type: Array,
    default: () => [],
  },
})
const workStore = useWorkOrder()
const data = ref<PackageListItem[]>([])
const activeId = ref('')
const el = ref<HTMLDivElement | null>(null)
const keyword = ref('')
const canloadMore = ref(true)
const isLoading = ref(false)

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

const approvalModalRef = ref(null)

function showModal(modalRef: any, id) {
  const modal = unref(modalRef)! as any
  modal.showModal(id)
}

function selectHandler(id: string, index: number) {
  console.log(id)
  console.log(777)
  workStore.setActive(index)
  showModal(approvalModalRef, id)
}

useInfiniteScroll(
  el as any,
  () => {
    loadMore()
  },
  {
    distance: 10,
    interval: 1500,
    canLoadMore: () => canloadMore.value,
  },
)

async function loadMore() {
  if (isLoading.value || el.value == null)
    return
  isLoading.value = true
  try {
    const more = await fetchList()
    data.value.push(...more)
  }
  finally {
    isLoading.value = false
  }
}

async function fetchList() {
  try {
    pagination.pageNo += 1
    const result = await workStore.fetchOrderList(pagination, keyword.value)
    const { data, pageCount } = result
    if (pageCount !== 0)
      canloadMore.value = pageCount >= pagination.pageNo
    else
      canloadMore.value = false

    return data || []
  }
  catch (error) {
    canloadMore.value = false
    return []
  }
}

watch(
  () => workStore.activeId,
  (newVal) => {
    if (isEmpty(newVal))
      return

    activeId.value = newVal
  },
)

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

  workStore.reset()
}

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

defineExpose({
  search,
})
</script>

<template>
  <ApprovalModal ref="approvalModalRef" />

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

<style lang="less" scoped>
.list {
  height: calc(100vh - 146px);
  overflow-y: scroll;
  overflow-x: hidden;

  scrollbar-width: none;
  /* firefox */
  -ms-overflow-style: none;
  /* IE 10+ */

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>
