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

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

defineProps({
  showFieldList: {
    type: Array,
    default: () => [],
  },
});


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

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

const { isLoading } = useInfiniteScroll(
  el as any,
  () => {
    loadMore();
  },
  { distance: 10, interval: 1500, canLoadMore: () => 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 result = await taskStore.fetchApprovalList(pagination);
    const { data, pageCount } = result;
    canloadMore.value = pageCount >= pagination.pageNo;
    return data || [];
  } catch (error) {
    canloadMore.value = false;
    return [];
  }
}

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

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

  taskStore.reset();
}

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() {
  search("");
}

defineExpose({
  search,
});
</script>

<template>
  <n-spin :show="isLoading">
    <div ref="el" class="list">
      <ListItem
        :showFieldList="showFieldList"
        v-for="(item, index) in data"
        :key="item.id"
        :selected="activeId === item.id"
        :list-item="item"
        @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>
