import { NButton, NModal, NSpace, useDialog } from 'naive-ui';
import { defineComponent, onBeforeUnmount, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import downBg from './images/downBg.png';
import rocketIcon from './images/rocketIcon.png';
import styles from './index.module.less';
import axios from 'axios';
let refreshing = false;
let isError = false;
const reloadPage = async () => {
  if ('serviceWorker' in navigator) {
    // let refreshing = false
    const flag = (await caches.keys()).length > 0;
    // console.log(caches.keys(), `0904路由更新有缓存${flag}`);
    caches.keys().then(function (cacheNames) {
      cacheNames.forEach(function (cacheName) {
        caches.delete(cacheName);
      });
    });
    // 尝试监听install
  }
  console.log('route index');
  window.location.reload();
};

const isChromeError = (error: any) => {
  console.log(error, 'error===>isChromeError', refreshing);
  isError = true;
  const tagName = error.target.tagName;
  const notIncoudle = ['IMG'];
  setTimeout(() => {
    if (!refreshing && !error.message && !notIncoudle.includes(tagName)) {
      refreshing = true;
      sessionStorage.setItem('isRouter', 'true');
      // reloadPage();
    }
  }, 500);
};
window.addEventListener('error', isChromeError, true);
export default defineComponent({
  name: 'router-error',
  setup() {
    const router = useRouter();
    const dialog = useDialog();

    const showModalMask = ref(false);
    const route = useRoute();

    router.onError((error, to) => {
      const str = error.message + '';
      const isChunkLoadFailed = str.indexOf('imported');
      console.log(error, to);
      const targetPath = router.currentRoute.value.fullPath;
      if (isChunkLoadFailed != -1 && !refreshing) {
        refreshing = true;
        // console.log('onError刷新');
        // sessionStorage.setItem('isRouter', 'true');
        // showModalMask.value = true;
        // router.push(to.path)
        location.hash = targetPath;
        window.location.reload();
      }
    });
    router.beforeEach(async (to, from, next) => {
      // const flag = await versionCheck();
      // console.log('路由之前弹窗', `refreshing${refreshing},flag:${flag}`);
      // if (flag && !refreshing) {
      //   refreshing = true;
      //   // console.log('修改刷新',refreshing)
      //   sessionStorage.setItem('isRouter', 'true');
      //   // reloadPage();
      //   //   showModalMask.value = true
      //   // setTimeout(()=>{
      //   //   const dom = document.getElementById('updateModel')
      //   //   if(isError&&!dom){
      //   //     reloadPage()
      //   //   }
      //   // },1000)

      //   //   setTimeout(()=>{
      //   //    sessionStorage.removeItem('isRouter')
      //   //  },60000)
      // }
      next();
    });
    const checkNewVersion = async () => {
      if ('serviceWorker' in navigator) {
        // let refreshing = false
        const flag = (await caches.keys()).length > 0;
        // console.log(caches.keys(), `0904路由更新有缓存${flag}`);
        caches.keys().then(function (cacheNames) {
          cacheNames.forEach(function (cacheName) {
            caches.delete(cacheName);
          });
          if (flag) {
            // window.location.reload();
            // dialog.warning({
            //   title: '更新提示',
            //   content: '网站有更新请点击确定刷新页面?',
            //   positiveText: '确定',
            //   negativeText: '取消',
            //   onPositiveClick: () => {
            //   }
            // });
          }
        });

        // 尝试监听install

        // navigator.serviceWorker.addEventListener(
        //   'controllerchange',
        //   async () => {
        //     console.log('controllerchange刷新', route.path, 'path');
        //     const flag = await versionCheck();
        //     if (refreshing || route.path == '/attend-class' || !flag) {
        //       return;
        //     }
        //     const isRouter = sessionStorage.getItem('isRouter');
        //     if (!isRouter) {
        //       // showModalMask.value = true
        //       // reloadPage();
        //     }
        //     refreshing = true;
        //   }
        // );
      }
    };

    console.log(route.path, 'route.path');
    // checkNewVersion();
    onBeforeUnmount(() => {
      sessionStorage.removeItem('isRouter');
      window.removeEventListener('error', isChromeError);
    });

    // 版本监控
    const versionCheck = async () => {
      // console.log(import.meta.env.MODE, 'import.meta.env', __APP_VERSION__);
      if (import.meta.env.MODE === 'development') return;
      const response = await axios.get('version.json');
      // eslint-disable-next-line no-undef
      // console.log(__APP_VERSION__, response.data.version);
      if (__APP_VERSION__ !== response.data.version) {
        // eslint-disable-next-line no-undef
        return true;
      } else {
        return false;
      }
    };

    return () => (
      <div>
        <NModal v-model:show={showModalMask.value} mask-closable={false}>
          <div class={styles.downMove} id="updateModel">
            <img src={rocketIcon} class={styles.dingPng} alt="" />
            <img src={downBg} class={styles.downMoveBg} alt="" />
            <h2>发现新版本</h2>
            <p>为提升您的用户体验，请刷新页面后使用</p>
            {/* <NButton>确定</NButton> */}
            <NSpace style={{ padding: '25px 0 0 0' }} justify="center">
              <NButton
                class={styles.submitAppBtn}
                round
                type="primary"
                onClick={reloadPage}>
                立即刷新
              </NButton>
            </NSpace>
          </div>
        </NModal>
      </div>
    );
  }
});
