import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  ref
} 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, eventGlobal } from './utils';
import { useRegisterSW } from 'virtual:pwa-register/vue';
import { useUserStore } from './store/modules/users';
import UpdateTips from './update-tips';
import VipPurchaseModal from './components/VipPurchaseModal';

export default defineComponent({
  name: 'App',
  setup() {
    // VIP购买弹窗状态
    const showVipModal = ref(false);
    const hasClose = ref(false); // 是否允许关闭弹窗

    // 监听VIP购买弹窗事件（必须在setup开头同步注册，否则路由守卫emit时监听还未准备好）
    eventGlobal.on('show-vip-purchase', (val?: boolean) => {
      showVipModal.value = true;
      if (val) {
        hasClose.value = true;
      }
    });

    // 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 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);
      }
    };

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

      // 主动检测会员状态（仅登录用户）
      const userStore = useUserStore();
      if (userStore.getToken) {
        const membershipEndTime = userStore.getUserInfo?.membershipEndTime;
        const isExpired =
          !membershipEndTime || new Date(membershipEndTime) < new Date();
        if (isExpired) {
          nextTick(() => {
            showVipModal.value = true;
          });
        }
      }

      // 禁用右键菜单
      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();
        }
      });
    });
    onUnmounted(() => {
      // window.removeEventListener('resize', resize);
      window.removeEventListener('message', handleOpen);
      eventGlobal.off('show-vip-purchase');
    });

    return () => (
      <div>
        <NConfigProvider
          locale={zhCN}
          themeOverrides={getThemeOverrides.value}
          dateLocale={dateZhCN}
        >
          <AppProvider>
            <RouterView />
          </AppProvider>

          {/* VIP购买弹窗 - 放在NConfigProvider内部 */}
          <NModal
            maskClosable={false}
            closeOnEsc={false}
            closable={hasClose.value || false}
            displayDirective="show"
            preset="card"
            title="VIP会员续费"
            class="modalTitle background"
            style={{ width: '860px' }}
            v-model:show={showVipModal.value}
          >
            <VipPurchaseModal
              hasCancel={hasClose.value}
              onClose={() => (showVipModal.value = false)}
              onSuccess={() => (showVipModal.value = false)}
            />
          </NModal>
        </NConfigProvider>

        <NModal maskClosable={false} v-model:show={needRefresh.value}>
          <UpdateTips
            onConfirm={() => {
              needRefresh.value = false;
              updateServiceWorker(true)
                .then(() => {
                  console.log('Service Worker updated');
                  if (navigator.serviceWorker.controller) {
                    navigator.serviceWorker.controller.postMessage({
                      type: 'SKIP_WAITING'
                    });
                  }
                  setTimeout(() => {
                    window.location.reload();
                  }, 200);
                })
                .catch((err: any) => {
                  console.error('Update failed:', err);
                });
            }}
          />
        </NModal>
      </div>
    );
  }
});
