/* 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',
    apply: 'build',
    closeBundle() {
      // 其他第三方依赖包
      const map = {
        'node_modules/qx-util/dist/qx-util.umd.js':
          'dist/extras/js/qx-util.min.js',
        'node_modules/@ibiz/dynamic-model-api/dist/ibiz-dynamic-model-api.system.min.js':
          'dist/extras/js/ibiz-dynamic-model-api.system.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');
      // 重新修改 system-import.json 补充时间戳
      {
        const systemImportPath = join(
          cwd,
          'dist/extras/json/system-import.json',
        );
        const content = readFileSync(systemImportPath, 'utf-8');
        if (content) {
          const json = JSON.parse(content);
          const items = json.imports;
          const date = new Date();
          // eslint-disable-next-line no-restricted-syntax, guard-for-in
          for (const key in items) {
            const val = items[key];
            items[key] = `${val}?time=${date.getTime()}`;
          }
          writeFileSync(
            systemImportPath,
            JSON.stringify(json, null, 2),
            'utf-8',
          );
        }
      }
      // 修改 dist/environments/environment.js 把 dev 模式改为 false
      {
        const envPath = join(cwd, 'dist/environments/environment.js');
        let env = readFileSync(envPath, 'utf-8');
        if (env) {
          env = env.replace(/dev:(.*)true/, 'dev: false');
          writeFileSync(envPath, env, 'utf-8');
        }
      }
    },
  };

  return [p];
}

export default IBizVitePlugin;
