/* eslint-disable import/no-extraneous-dependencies */
import { copyFileSync, readFileSync, writeFileSync } from 'node:fs';
import { Plugin } from 'vite';
import { join } from 'path';

function IBizVitePlugin(): Plugin[] {
  const p: Plugin = {
    name: 'iBizSys:System',
    closeBundle() {
      // 其他第三方依赖包
      const map = {
        'node_modules/qx-util/dist/umd/qx-util.umd.js':
          'dist/extras/js/qx-util.min.js',
      };
      // 模板底包
      const templatePackages = [
        'command',
        'core',
        'model',
        'runtime',
        'service',
        'controller',
        'vue-util',
      ];
      const cwd = process.cwd();
      {
        // 拷贝第三方依赖包
        const keys = Object.keys(map);
        keys.forEach(key => {
          const val = map[key];
          copyFileSync(join(cwd, key), join(cwd, val));
        });
      }
      // eslint-disable-next-line no-lone-blocks
      {
        // 拷贝模板底包并修改文件名称
        templatePackages.forEach(pkg => {
          const cpFile = join(
            cwd,
            `node_modules/@ibiz-template/${pkg}/dist/system/index.system.js`,
          );
          const outFile = join(
            cwd,
            `dist/extras/js/ibiz-template-${pkg}.system.min.js`,
          );
          copyFileSync(cpFile, outFile);
        });
      }
      // 重新改写 index.html 部分代码
      const htmlFilePath = join(cwd, 'dist/index.html');
      let html = readFileSync(htmlFilePath, 'utf-8');
      html = html
        .replace(
          '<script type="module">try{import.meta.url;import("_").catch(()=>1);}catch(e){}window.__vite_is_modern_browser=true;</script>',
          '',
        )
        .replace(
          `<script type="module">!function(){if(window.__vite_is_modern_browser)return;console.warn("vite: loading legacy build because dynamic import or import.meta.url is unsupported, syntax error above should be ignored");var e=document.getElementById("vite-legacy-polyfill"),n=document.createElement("script");n.src=e.src,n.onload=function(){System.import(document.getElementById('vite-legacy-entry').getAttribute('data-src'))},document.body.appendChild(n)}();</script>`,
          '',
        );
      // 标准 vite 编译后脚本
      const rootJsReg =
        /<script type="module" crossorigin src=".\/assets\/index.(.*).js"><\/script>/;
      html = html.replace(rootJsReg, '');
      html = html.replace('<script nomodule', '<script');
      html = html.replace('<script nomodule', '<script');
      html = html.replace('<script nomodule', '<script');
      html = html.replace('<script nomodule', '<script');
      html = html.replace(
        '<script src="./assets/ionicons/ionicons/ionicons.js"></script>',
        '<script nomodule src="./assets/ionicons/ionicons/ionicons.js"></script>',
      );
      writeFileSync(htmlFilePath, html, 'utf-8');
    },
  };

  return [p];
}

export default IBizVitePlugin;
