import { Button, Notification } from '@arco-design/web-vue'
import axios from 'axios'

let timer: any
/**
 * 版本更新监听器，当有新版本，右上角弹出消息通知
 * @param time 检查间隔，单位秒，默认5分钟
 */
export const useVersionUpdateListener = (time = 5 * 60) => {
  if (timer !== undefined) {
    return
  }
  if (import.meta.env.PROD) {
    let indexJs: string
    timer = setInterval(() => {
      axios
        .request({
          baseURL: '',
          url: `/manifest.json?t=${Date.now()}`
        })
        .then((res) => {
          let file
          try {
            file = res.data['index.html'].file
          } catch (_) {
            return
          }
          if (!indexJs) {
            indexJs = file
          }
          if (indexJs !== file) {
            clearInterval(timer)
            Notification.info({
              duration: 0,
              content: '发现新版本，点击获取最新版本。',
              footer: () =>
                h(
                  Button,
                  {
                    size: 'small',
                    text: true,
                    type: 'primary',
                    onClick: () => {
                      window.location.reload()
                    }
                  },
                  { default: () => h('span', '刷新') }
                )
            })
          }
        })
        .catch(() => {})
    }, time * 1000)
  }
}
