import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import WindiCSS from 'vite-plugin-windicss';
import { VitePWA } from 'vite-plugin-pwa';
import packageJson from './package.json';
import dayjs from 'dayjs'
import svgr from "vite-plugin-svgr";

const today = new dayjs().format('YYYY-MM-DD HH:mm:ss')

const buildDatePlugin = () => {
  return {
    transformIndexHtml(html) {
      return html.replace(/%BUILD_VERSION%/, `${packageJson.version}(${today})`);
    },
  };
};
// PWA plugin
const manifestForPWAPlugIn = {
  // strategies: 'generateSW',
  registerType: 'prompt',
  devOptions: { enabled: true },
  workbox: {
    // dontCacheBustURLsMatching: /\/maintenance/,
    navigateFallbackDenylist: [/^\/maintenance/],
    globPatterns: ['**/*.{json,css,js,html,ico,png,svg,woff2}'],
    globIgnores: ['**/maintenance.html', '**/maintenance/*'],
    maximumFileSizeToCacheInBytes: 3000000,
    clientsClaim: true,
    // skipWaiting: true,
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/haina-sale-system\.oss-cn-shenzhen\.aliyuncs\.com\/.*/i,
        handler: 'CacheFirst',
        options: {
          cacheName: 'oss-cn-media',
          expiration: {
            maxEntries: 20,
            maxAgeSeconds: 60 * 60 * 24 * 7, // <== 7 days
          },
          cacheableResponse: {
            statuses: [0, 200],
          },
        },
      },
      {
        urlPattern: /^https:\/\/hiana-crm\.oss-ap-southeast-1\.aliyuncs\.com\/.*/i,
        handler: 'CacheFirst',
        options: {
          cacheName: 'oss-ap-media',
          expiration: {
            maxEntries: 20,
            maxAgeSeconds: 60 * 60 * 24 * 7, // <== 7 days
          },
          cacheableResponse: {
            statuses: [0, 200],
          },
        },
      },
      {
        urlPattern: /^https:\/\/hiana-crm\.oss-accelerate\.aliyuncs\.com\/.*/i,
        handler: 'CacheFirst',
        options: {
          cacheName: 'oss-ap-acc-media',
          expiration: {
            maxEntries: 50,
            maxAgeSeconds: 60 * 60 * 24 * 7, // <== 7 days
          },
          cacheableResponse: {
            statuses: [0, 200],
          },
        },
      },
      {
        urlPattern: /^https:\/\/page-spy\.mycht\.cn\/.*/i,
        handler: 'CacheFirst',
        options: {
          cacheName: 'pagespy',
          expiration: {
            maxEntries: 10,
            maxAgeSeconds: 60 * 60 * 24 * 7, // <== 7 days
          },
          cacheableResponse: {
            statuses: [0, 200],
          },
        },
      },
      {
        urlPattern: /^https:\/\/static-legacy\.dingtalk.com\/.*/i,
        handler: 'CacheFirst',
        options: {
          cacheName: 'dingtalk-avatar-media',
          expiration: {
            maxEntries: 10,
            maxAgeSeconds: 60 * 60 * 24 * 7, // <== 7 days
          },
          cacheableResponse: {
            statuses: [0, 200],
          },
        },
      },
    ],
  },
  manifest: {
    name: 'Sales CRM',
    short_name: 'Sales CRM',
    description: 'Haina travel global sales CRM system',
    icons: [
      {
        src: '/favicon.ico',
        sizes: '96x96',
      },
      {
        src: '/pwa-launchericon-192-192.png',
        sizes: '192x192',
        type: 'image/png',
      },
      {
        src: '/pwa-launchericon-144-144.png',
        sizes: '144x144',
        type: 'image/png',
      },
      {
        src: '/pwa-launchericon-512-512.png',
        sizes: '512x512',
        type: 'image/png',
      },
    ],
    screenshots: [
      { src: '/screenshot-pc.png', sizes: '846x458', type: 'image/png', form_factor: 'wide' },
      { src: '/screenshot-m.png', sizes: '375x667', type: 'image/png' },
    ],
    theme_color: '#171717',
    background_color: '#ccd5ae',
    display: 'standalone',
    display_override: ['window-controls-overlay'],
    scope: '/',
    start_url: '/',
    orientation: 'portrait',
  },
};

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    __BUILD_DATE__: JSON.stringify(`${today}`),
    __BUILD_VERSION__: JSON.stringify(`${packageJson.version}`),
  },
  plugins: [ svgr(), react(), WindiCSS(), buildDatePlugin(), VitePWA(manifestForPWAPlugIn), ],
  server: {
    host: '0.0.0.0',
  },
  resolve: {
    alias: {
      '@': '/src',
    },
  },
  build: {
    // outDir: 'distTest',
    emptyOutDir: true,
    sourcemap: true,
    manifest: true,
    chunkSizeWarningLimit: 555,
    rollupOptions: {
      input: {
        main: 'index.html',
        maintenance: './maintenance.html'
      },
      output: {
        entryFileNames: '[name]/build.[hash].js',
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return 'vendor';
            // return id.toString().split('node_modules/')[1].split('/')[0].toString();
          }
        },
    //     chunkFileNames: (chunkInfo) => {
    //       const facadeModuleId = chunkInfo.facadeModuleId ? chunkInfo.facadeModuleId.split('/') : [];
    //       return `assets/[name].[hash].js`;
    //     }
      }
    }
  },
  terserOptions: {
    maxWorkers: 4,
  },
});
