import { computed, defineComponent, onMounted, onUnmounted } from 'vue';
import { NConfigProvider, zhCN, dateZhCN, NModal } from 'naive-ui';
import { AppProvider } from './components/Application';
import { RouterView } from 'vue-router';
import setting from './settings/designSetting';
import { lighten } from './utils';
// import RouterError from './components/RouterError';
import { useRegisterSW } from 'virtual:pwa-register/vue';
import { useUserStore } from './store/modules/users';
import UpdateTips from './update-tips';

export default defineComponent({
  name: 'App',
  setup() {
    // const { needRefresh, offlineReady, updateServiceWorker } = useRegisterSW({
    //   onRegistered(r: any) {
    //     console.log(r, 'registered');
    //     // if (r) {
    //     //   setInterval(() => {
    //     //     r.update(); // 手动触发更新检查
    //     //   }, 30000); // 每 30 秒检查一次
    //     // }
    //   },
    //   onNeedRefresh() {
    //     console.log('新版本可用！');
    //     alert('新版本可用！');
    //   },
    //   onOfflineReady() {
    //     console.log('离线功能就绪。');
    //   }
    // });
    const { needRefresh, updateServiceWorker } = useRegisterSW({
      onRegistered(r) {
        console.log(r, 'Service Worker 已注册');
        // 你可以在这里使用定时器手动检查更新
        if (r) {
          setInterval(() => {
            r.update(); // 每 30 秒检查一次更新
          }, 30000);
        }
      },
      onNeedRefresh() {
        console.log('onNeedRefresh 事件触发');
        console.log('needRefresh 状态:', needRefresh); // 确认 needRefresh 是否为 true
      },
      onOfflineReady() {
        console.log('离线功能已就绪');
      }
    });

    // const isIOSChrome = ref();
    // const showModalMask = ref(false);
    const getThemeOverrides = computed(() => {
      const appTheme = setting.appTheme;
      const lightenStr = lighten(setting.appTheme, 6);
      return {
        common: {
          primaryColor: appTheme,
          primaryColorHover: lightenStr,
          primaryColorPressed: lightenStr,
          errorColor: '#F51C08',
          errorColorHover: '#F51C08',
          errorColorPressed: '#F51C08'
        },
        LoadingBar: {
          colorLoading: appTheme
        }
      };
    });
    // const showModal = ref(false);
    // const showModalMsg = ref('');
    // // 判断浏览器
    // // 是否是360
    // const check360 = () => {
    //   const result = false;
    //   for (const key in navigator.plugins) {
    //     // np-mswmp.dll只在360浏览器下存在
    //     if (navigator.plugins[key].filename == 'internal-nacl-plugin') {
    //       return !result;
    //     }
    //   }
    //   return result;
    // };
    //

    // const isChrome = () => {
    //   const isChromium = (window as any).chrome,
    //     winNav = window.navigator,
    //     vendorName = winNav.vendor,
    //     isOpera = winNav.userAgent.indexOf('OPR') > -1,
    //     isIEedge = winNav.userAgent.indexOf('Edge') > -1,
    //     isIOSChrome = winNav.userAgent.match('CriOS'),
    //     // QQ
    //     isQQBriwser =
    //       winNav.userAgent.indexOf('QQBrowser') > -1 ||
    //       winNav.userAgent.indexOf('QQ') > -1,
    //     // 搜狗
    //     isSouggou =
    //       winNav.userAgent.indexOf('se 2.x') > -1 ||
    //       winNav.userAgent.indexOf('MetaSr') > -1,
    //     // 360
    //     is360 = check360() && winNav.userAgent.indexOf('Safari') > -1,
    //     // 遨游
    //     isMaxthon = winNav.userAgent.indexOf('Maxthon') > -1,
    //     // 是否为2345浏览器
    //     is2345Explorer = winNav.userAgent.includes('2345Explorer'),
    //     // 世界之窗
    //     isTheWorld = winNav.userAgent.indexOf('TheWorld') > -1,
    //     // 猎豹
    //     isLiebao = winNav.userAgent.indexOf('LBBROWSER') > -1;
    //   // console.log(isQQBriwser, isSouggou, is360, isMaxthon, is2345Explorer, isTheWorld, isLiebao)
    //   if (isIOSChrome) {
    //     return true;
    //   } else if (
    //     isChromium !== null &&
    //     typeof isChromium !== 'undefined' &&
    //     vendorName === 'Google Inc.' &&
    //     isOpera === false &&
    //     isIEedge === false &&
    //     isQQBriwser === false &&
    //     isSouggou === false &&
    //     is360 === false &&
    //     isMaxthon === false &&
    //     is2345Explorer === false &&
    //     isTheWorld === false &&
    //     isLiebao === false
    //   ) {
    //     return true;
    //   } else {
    //     return false;
    //   }
    // };

    // // 获取谷歌版本
    // const getChromeVersion = () => {
    //   const arr = navigator.userAgent.split(' ');
    //   let chromeVersion = '' as any;
    //   for (let i = 0; i < arr.length; i++) {
    //     if (/chrome/i.test(arr[i])) chromeVersion = arr[i];
    //   }
    //   if (chromeVersion) {
    //     return Number(chromeVersion.split('/')[1].split('.')[0]);
    //   } else {
    //     return false;
    //   }
    // };

    // const isChromeFlag = isChrome();
    // // console.log('isChromeFlag', isChromeFlag);
    // if (isChromeFlag) {
    //   const chromeVersion = getChromeVersion();
    //   if (!chromeVersion || (chromeVersion && chromeVersion < 100)) {
    //     showModalMsg.value =
    //       '您当前的chrome版本过低,为了保证您的用户体验请升级后使用';
    //   }
    // } else {
    //   showModalMsg.value = '为了保证您的用户体验,请使用chrome打开,点击确定下载';
    //   // showModal.value = true;
    //   console.log('---');
    // }
    // const submitCallback = () => {
    //   window.open('https://www.google.cn/intl/zh-CN/chrome/');
    // };
    const handleOpen = (e: MessageEvent) => {
      if (e.data?.api === 'onLogin') {
        const userStore = useUserStore();
        // const router = useRouter();
        const documentDom: any = document;
        documentDom.exitFullscreen
          ? documentDom.exitFullscreen()
          : documentDom.mozCancelFullScreen
          ? documentDom.mozCancelFullScreen()
          : documentDom.webkitExitFullscreen
          ? documentDom.webkitExitFullscreen()
          : '';
        userStore.logout();
        history.go(0);
      }
    };

    // const resize = () => {
    //   const params = {
    //     width: document.body.clientWidth,
    //     height: document.body.clientHeight
    //   };
    //   if (params.height >= params.width) {
    //     showModalMask.value = true;
    //   } else {
    //     showModalMask.value = false;
    //   }
    // };

    onMounted(() => {
      window.addEventListener('message', handleOpen);
      // window.addEventListener('resize', resize);

      // 禁用右键菜单
      document.addEventListener('contextmenu', function (event) {
        event.preventDefault();
      });
      // 禁用浏览器快捷键
      document.addEventListener('keydown', function (event) {
        // 屏蔽 F12 和 Ctrl+Shift+I
        if (
          event.key === 'F12' ||
          (event.ctrlKey && event.shiftKey && event.key === 'I') ||
          (event.metaKey && event.altKey && event.key === 'I')
        ) {
          event.preventDefault();
        }
      });

      // console.log('app - onounted - test interval');

      if ('serviceWorker' in navigator) {
        // navigator.serviceWorker.addEventListener('message', event => {
        //   console.log('messageType: ', event.data?.type);
        //   if (event.data?.type === 'NEW_VERSION_AVAILABLE') {
        //     console.log('New version available, refresh the page.');
        //     // 可以提示用户刷新页面
        //   }
        // });
        // navigator.serviceWorker.getRegistrations().then(registrations => {
        //   for (const registration of registrations) {
        //     if (registration.scope.startsWith(`https://${location.host}/`)) {
        //       registration.unregister().then(() => {
        //         console.log(
        //           `Service Worker unregistered for https://${location.host}/`
        //         );
        //       });
        //     }
        //   }
        // });
      }
    });
    onUnmounted(() => {
      // window.removeEventListener('resize', resize);
      window.removeEventListener('message', handleOpen);
    });

    return () => (
      <div>
        <NConfigProvider
          locale={zhCN}
          themeOverrides={getThemeOverrides.value}
          // :theme="getDarkTheme"
          // :theme-overrides="getThemeOverrides"
          dateLocale={dateZhCN}>
          <AppProvider>
            <RouterView />
            {/* <RouterError /> */}
          </AppProvider>
        </NConfigProvider>
        <NModal maskClosable={false} v-model:show={needRefresh.value}>
          <UpdateTips
            onConfirm={() => {
              needRefresh.value = false;
              setTimeout(() => {
                updateServiceWorker(true).then(res => {
                  console.log(res, '------');
                  window.location.reload();
                });
              }, 0);
            }}
          />
        </NModal>

        {/* <NModal
          show={showModal.value}
          closeOnEsc={false}
          closable={false}
          maskClosable={false}
          preset="dialog"
          title="确认"
          content={showModalMsg.value}
          positive-text="确认"
          onPositiveClick={submitCallback}></NModal> */}
      </div>
    );
  }
});
