import { ref } from 'vue'
import { $XXL, isWebEvn } from '@/utils'

export const useLoad = () => {
  const size = ref(0)
  const loadSize = ref(0)
  const loadProgress = ref('0%')
  const loaded = ref(false)
  const loadText = ref('')
  let close = false

  const init = (arr: any, config: { timeout?: number; android?: boolean } = {}) => {
    loadSize.value = 0
    loaded.value = false
    loadProgress.value = '0%'
    close = false
    if (config.android) {
      size.value = arr.c
      $XXL.loadResources({ data: arr }, (res, next) => {
        load(
          {
            src: res.data.url,
          },
          true,
        )
        ok(res.data.url)
        next()
      })
    } else {
      size.value = arr.length
      if (arr.length) {
        arr.forEach((i: string) => {
          load({ src: i })
        })
      } else {
        loadProgress.value = '100%'
        loaded.value = true
      }
    }
  }

  const load = (item: { src: string; numberOfFail?: number }, silence = false) => {
    const img = new Image()
    if (!/^https?:\/\/(.+\/)+.+(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i.test(item.src))
      return ok(item.src)
    img.src = item.src
    if (silence) {
      img.addEventListener('load', () => {})
    } else {
      img.addEventListener('load', () => ok(item.src))
      img.addEventListener('error', () => {
        item.numberOfFail ? item.numberOfFail++ : (item.numberOfFail = 1)
        if (item.numberOfFail && item.numberOfFail > 2) {
          ok(item.src)
          // XMessage.error('加载失败，网络异常，请刷新或稍后重试');
        } else {
          load(item)
        }
      })
    }
  }

  // 加载完成
  const ok = (src?: string) => {
    loadSize.value++
    const progress = Math.round((loadSize.value / size.value) * 100)
    loadProgress.value = progress + '%'
    // loadText.value = src?.split('/').pop() || '';

    if (!isWebEvn && progress > 2 && !close) {
      close = true
      $XXL.closeLoading()
    }

    setTimeout(() => {
      loaded.value = Number(loadProgress.value.replace('%', '')) >= 100
    }, 500)
  }

  return {
    size,
    loadSize,
    loadProgress,
    loaded,
    loadText,
    init,
  }
}
