import { XMessage } from '@/hooks'

export default function useLoad() {
  const size = ref(0)
  const loadSize = ref(0)
  const loadProgress = ref('0%')
  const loaded = ref(false)
  const arrTool = ref<string[]>([])
  const showAgainLoad = ref(false) // 重新加载按钮

  function init(arr: string[]) {
    showAgainLoad.value = false
    arrTool.value = arr
    size.value = arr.length
    loadSize.value = 0
    loaded.value = false
    loadProgress.value = '0%'
    getLoadTime()
    if (arr.length) {
      arr.forEach(i => {
        load({ src: i })
      })
    } else {
      loadProgress.value = '100%'
      loaded.value = true
    }
  }
  function getLoadTime() {
    // 加载时长超过8秒   显示重新加载
    setTimeout(() => {
      showAgainLoad.value = true
    }, 8000)
  }

  function loadAgain() {
    init(arrTool.value)
  }

  function loadTool() {
    if (loaded.value) return
    loadSize.value++
    loadProgress.value = Math.round((loadSize.value / size.value) * 100) + '%'
    setTimeout(() => {
      loaded.value = Number(loadProgress.value.replace('%', '')) >= 100
    }, 500)
  }

  function load(item: { src: string; numberOfFail?: number }) {
    const img = new Image()
    img.src = item.src
    img.addEventListener('load', () => {
      loadTool()
    })
    img.addEventListener('error', () => {
      item.numberOfFail ? item.numberOfFail++ : (item.numberOfFail = 1)
      if (item.numberOfFail && item.numberOfFail > 1) {
        XMessage.error('加载失败，网络异常')

        loadTool()
      } else {
        load(item)
      }
    })
  }

  return {
    size,
    loadSize,
    loadProgress,
    showAgainLoad,
    loaded,
    loadAgain,
    init,
  }
}
