import { NModal } from 'naive-ui';
import { defineComponent, ref } from 'vue';
import { useRouter } from 'vue-router';
import styles from './index.module.less';
import commentBg from './images/tip-bg.png';
import commentTop from './images/tip-dang.png';

let refreshing = false;
export default defineComponent({
  name: 'router-error',
  setup() {
    const router = useRouter();

    const showModalMask = ref(false);

    router.onError((error, to) => {
      const str = error.message + '';
      const isChunkLoadFailed = str.indexOf('imported');
      console.log(error, to, str);
      const targetPath = router.currentRoute.value.fullPath;
      if (isChunkLoadFailed != -1 && !refreshing) {
        refreshing = true;
        location.hash = targetPath;
        // window.location.reload();
        showModalMask.value = true;
      }
    });
    return () => (
      <NModal v-model:show={showModalMask.value} mask-closable={false}>
        <div class={styles.commonWork}>
          <img src={commentTop} class={styles.dingPng} alt="" />
          <img src={commentBg} class={styles.downMoveBg} alt="" />
          <h2>发现新版本</h2>

          <div class={styles.header}>系统已更新版本，请刷新界面后继续使用</div>

          <div
            class={styles.btn}
            onClick={() => {
              showModalMask.value = false;
              window.location.reload();
            }}>
            立即刷新
          </div>
        </div>
      </NModal>
    );
  }
});
