import { ref, onActivated, nextTick } from 'vue'
import listRefreshInfoStore from '@/stores/listRefreshInfo'
const listRefreshInfo = listRefreshInfoStore()

export function scrollList(pageContent: any, scrollPosition: any, refresh: any) {
  const refreshFlag = ref(true)
  function setScrollTop() {
    console.log(1)
    onActivated(() => {
      nextTick(() => {
        if (listRefreshInfo.refreshId) {
          refresh('refresh', listRefreshInfo.refreshId)
          listRefreshInfo.refreshId = ''
        } else if (listRefreshInfo.deleteId) {
          refresh('delete', listRefreshInfo.deleteId)
          listRefreshInfo.deleteId = ''
        } else if (listRefreshInfo.addId) {
          listRefreshInfo.addId = ''
          refresh()
        } else {
          if (scrollPosition.value && pageContent.value) {
            pageContent.value.scrollTop = scrollPosition.value
          }
          if (refreshFlag.value === true) {
            refresh()
          }
        }
      })
    })
  }

  function setScrollPositionAndRefreshFlag(to: any, page: string) {
    if (pageContent.value) {
      scrollPosition.value = pageContent.value.scrollTop
    }
    if (page.includes(',')) {
      const pages = page.split(',')
      const index = pages.findIndex((ele: any) => {
        return to.name === ele
      })
      if (index > -1) {
        refreshFlag.value = false
      } else {
        refreshFlag.value = true
      }
    } else {
      if (to.name === page) {
        refreshFlag.value = false
      } else {
        refreshFlag.value = true
      }
    }
  }

  return {
    setScrollTop,
    setScrollPositionAndRefreshFlag
  }
}
