importScripts(
  './sw-utils.js',
  './sw-domain.js',
  './sw-page.js',
);
// ç›‘å¬ install äº‹ä»¶
self.addEventListener('message', (event) => {
  console.log("ðŸš€ Self_message", event);
});
// ç›‘å¬ install äº‹ä»¶
self.addEventListener('install', (event) => {
  console.log("ðŸš€ SW å®‰è£…æˆåŠŸï¼");
  // è·³è¿‡ç­‰å¾…ï¼Œç›´æŽ¥è¿›å…¥ active çŠ¶æ€
  self.skipWaiting();
});
// ç›‘å¬ activate äº‹ä»¶ (æ¿€æ´» SW)
self.addEventListener('activate', (event) => {
  console.log("ðŸš€ SW æ¿€æ´»æˆåŠŸï¼");
});

// ç›‘å¬ fetch äº‹ä»¶
self.addEventListener('fetch', (event) => {
  // é¿å…å¤„ç†éžåŒæºè¯·æ±‚
  const url = new URL(event.request.url);
  // åªå¤„ç† GET è¯·æ±‚å’ŒåŒæºè¯·æ±‚
  if (event.request.method !== 'GET' || url.origin !== self.location.origin) return;
  // å¿½ç•¥ API è¯·æ±‚å’Œé™æ€èµ„æºè¯·æ±‚
  if (url.pathname.includes('/api')||url.pathname.includes('/web') || url.pathname.includes('.')) {
    return;
  }
  event.respondWith((
    async () => {
      try {
        const networkResponse = await fetch(event.request);
        if (networkResponse.ok) {
          return networkResponse;
        }
        throw new Error('network error when fetching request');
      } catch (error) {
        // å¦‚æžœç½‘ç»œè¯·æ±‚å¤±è´¥ï¼Œè¿”å›žç¦»çº¿é¡µé¢
        if (!navigator.onLine) {
          return new Response(
            '<h1>navigator is offLine,Please check the device network</h1>',
            {
              status: 503,
              headers: { 'Content-Type': 'text/html' },
            }
          );
        } else {
          const htmlContent = createDynamicOnlinePage(buildStringMap());
          console.log("ðŸš€ htmlContent", buildStringMap());
          // å¼‚æ­¥ç¼“å­˜å“åº”
          try {
            const cache = await caches.open('online-page');
            await cache.put('sw-page.html', htmlContent.clone());
          } catch (cacheError) {
            console.error('ç¼“å­˜å¤±è´¥:', cacheError);
          }

          // ä¼˜å…ˆè¿”å›žæ–°ç”Ÿæˆçš„å“åº”ï¼Œæˆ–ä»Žç¼“å­˜ä¸­èŽ·å–
          const cachedResponse = await caches.match('sw-page.html');
          console.log(cachedResponse, 'cachedResponse')
          return cachedResponse || htmlContent;
        }
      }
    }
  )()
  );
});