import { defineConfig } from 'dumi';
import { join } from 'path';
import versionList from './config/version.json';
import { IVersionConfig } from './utils/version';
import { VersionManage } from './utils/version';

export default defineConfig({
  title: 'wakeapp',
  favicon: 'https://s2.loli.net/2021/12/21/XQ367AWSK9kfLoR.png',
  logo: 'https://s2.loli.net/2021/12/21/XQ367AWSK9kfLoR.png',
  outputPath: 'docs-dist',
  mode: 'site',
  base: getBaseHref(),
  publicPath: getBaseHref(),
  exportStatic: {},
  dynamicImport: {},
  resolve: {
    includes: ['desc', './docs', './document'],
  },
  styles: [
    `body { user-select: text!important;}`,
    `.markdown table { display: block;
                    overflow-x: auto;
                    overflow-y: hidden;
                    }
      .__dumi-default-tabs-tab-btn {
        display: inline-flex;
        align-items: center;
      }
      `,
  ],
  define: {
    'process.env.TARO_ENV': 'h5',
  },
  apiParser: {
    propFilter: {
      // 需要忽略的属性名列表，默认为空数组
      skipPropsWithName: [
        '__index',
        '__isLast',
        '__border',
        '__gutter',
        '__square',
        '__active',
        '__activeColor',
        '__inactiveColor',
        '__onClick',
        '__direction',
        '__isActiveStep',
        '__isFinish',
        '__activeIcon',
        '__inactiveIcon',
        '__finishIcon',
        '__isFirst',
        '__stepIndex',
      ],
    },
  },
  theme: {
    '@c-primary': '#f0762b',
  },
  navs: [null, ...[createVersionNav()].filter(Boolean)],
  alias: {
    '@tarojs/components': join(__dirname, '../taro-components-react/index.js'),
    '@wakeapp/tailwind': '@wakeapp/tailwind/tailwind.css',
    '@tarojs/taro': '@tarojs/taro-h5',
    '@wakeapp/components/icons': join(__dirname, '../components/icons/'),
    '@wakeapp/components': join(__dirname, '../components/dist/'),
  },
  extraBabelIncludes: [join(__dirname, '../')],
  extraBabelPlugins: ['@wakeapp/babel-plugin-transform-wkicon'],
  chainWebpack(config) {
    // Taro H5 模块加载
    config.resolve.mainFields.prepend('main:h5').add('browser').add('module').add('main');
    config.entry('umi').prepend(join(__dirname, './docs/theme.ts')).prepend(join(__dirname, './docs/env.ts'));

    // 优先识别 H5 文件
    ['.h5.js', '.h5.jsx', '.h5.ts', '.h5.tsx'].reverse().forEach(ext => {
      config.resolve.extensions.prepend(ext);
    });
  },
  themeConfig: {
    carrier: 'wakeapp',
    hd: {
      rules: [],
      // More rule: https://github.com/umijs/dumi/blob/master/packages/theme-mobile/src/typings/config.d.ts#L7
    },
  },
  // Taro rem 转换脚本
  headScripts: [
    `
  // 只在 iframe 中生效
  if (window.top !== window) {
    // 非根窗口中
    !(function (x) {
      function w() {
        var v,
          u,
          t,
          tes,
          s = x.document,
          r = s.documentElement,
          a = r.getBoundingClientRect().width;
        if (!v && !u) {
          var n = !!x.navigator.appVersion.match(/AppleWebKit.*Mobile.*/);
          v = x.devicePixelRatio;
          tes = x.devicePixelRatio;
          (v = n ? v : 1), (u = 1 / v);
        }
        if (a >= 640) {
          r.style.fontSize = '40px';
        } else {
          if (a <= 320) {
            r.style.fontSize = '20px';
          } else {
            r.style.fontSize = (a / 320) * 20 + 'px';
          }
        }
      }
      x.addEventListener('resize', function () {
        w();
      });
      w();
    })(window);
  }
  `,
  ],
  // more config: https://d.umijs.org/config
});

function createVersionNav(): {
  title: string;
  children: { title: string; path: string }[];
} {
  const children = Object.entries(versionList as IVersionConfig).map(([title, path]) => ({ title, path }));
  if (children.length > 1) {
    return {
      title: '切换版本',
      children,
    };
  }
  return null;
}

function getBaseHref(): string {
  const nodeEnv: 'development' | 'production' = process.env.NODE_ENV as any;
  if (nodeEnv === 'development') return '/';
  const base = '/';
  const version = new VersionManage();
  const path = version.getLastVersion() === 'master' ? 'master' : version.getPackageVersion();
  return base + path + '/';
}
