const path = require('path');
const { CIPluginFn } = require('../ci/upload');

import AutoImport from 'unplugin-auto-import/webpack';
import ComponentsPlugin from 'unplugin-vue-components/webpack';
import NutUIResolver from '@nutui/nutui-taro/dist/resolver';

const config = {
  projectName: 'vue-mini',
  date: '2022-11-29',
  designWidth(input) {
    // 配置 NutUI 375 尺寸
    if (input?.file?.replace(/\\+/g, '/').indexOf('@nutui') > -1) {
      return 375;
    }
    // 全局使用 Taro 默认的 750 尺寸
    return 750;
  },
  deviceRatio: {
    375: 2 / 1,
    640: 2.34 / 2,
    750: 1,
    828: 1.81 / 2,
  },
  alias: {
    '@': path.resolve(__dirname, '..', 'src'),
    '@components/assets': path.resolve(__dirname, '..', 'node_modules', '@12333/components/assets'),
  },
  sourceRoot: 'src',
  outputRoot: 'dist',
  plugins: [
    ['@tarojs/plugin-mini-ci', CIPluginFn],
    [
      '@tarojs/plugin-vue-devtools',
      {
        port: 9999,
      },
    ],
    '@tarojs/plugin-html',
    [
      '@tarojs/plugin-http',
      {
        enableCookie: true,
      },
    ],
    'taro-plugin-pinia',
    [
      '@tarojs/plugin-framework-vue3',
      {
        vueLoaderOption: {
          compilerOptions: {
            isCustomElement: (tag) => tag.includes('ec-canvas'),
          },
          reactivityTransform: true, // 开启vue3响应性语法糖
        },
      },
    ],
  ],

  defineConstants: {
    // CLIENT_ID: JSON.stringify('frontend-admin-app-client'),
    // START_YEAR: '2022',
  },
  copy: {
    patterns: [],
    options: {},
  },
  framework: 'vue3',
  compiler: {
    type: 'webpack5',
    prebundle: { enable: false },
  },
  cache: {
    enable: false, // Webpack 持久化缓存配置,建议开启。默认配置请参考:https://docs.taro.zone/docs/config-detail#cache
  },
  sass: {
    resource: [path.resolve(__dirname, '..', 'src/styles/custom_theme.scss')],
    data: `@import "@nutui/nutui-taro/dist/styles/variables.scss";`,
  },

  mini: {
    hot: true,
    miniCssExtractPluginOption: {
      ignoreOrder: true,
    },
    postcss: {
      pxtransform: {
        enable: true,
        config: {
          selectorBlackList: ['nut-'],
        },
      },
      url: {
        enable: true,
        config: {
          limit: 1024, // 设定转换尺寸上限
        },
      },
      cssModules: {
        enable: true, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]',
        },
      },
    },
    webpackChain(chain, webpack) {
      if (process.env.NODE_ENV === 'development') {
        chain.plugin('analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin, []);
      }

      chain.plugin('unplugin-auto-import').use(
        AutoImport({
          imports: ['vue', 'pinia', 'vue-router', { '@/constants': ['RouterPath'] }],
          eslintrc: {
            enabled: true, // Default `false`
            filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
            globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
          },
        })
      );

      chain.plugin('unplugin-vue-components').use(
        ComponentsPlugin({
          include: [/\.[tj]sx?$/, /\.vue$/, /\.vue\?vue/],
          resolvers: [NutUIResolver({ taro: true })],
          dts: true,
        })
      );

      chain.merge({
        plugin: {
          install: {
            plugin: require('terser-webpack-plugin'),
            args: [
              {
                terserOptions: {
                  compress: true, // 默认使用terser压缩
                  keep_classnames: true, // 不改变class名称
                  keep_fnames: true, // 不改变函数名称
                },
              },
            ],
          },
        },
      });

      chain.merge({
        optimization: {
          splitChunks: {
            cacheGroups: {
              nutui: {
                name: 'nutui',
                minChunks: 2,
                test: (module) => {
                  return /[\\/]node_modules[\\/]@nutui[\\/]/.test(module.resource);
                },
                priority: 20,
              },
              lodash: {
                name: 'lodash',
                minChunks: 2,
                test: (module) => {
                  return /[\\/]node_modules[\\/]lodash[\\/]/.test(module.resource);
                },
                priority: 20,
              },
              // senin: {
              //   name: 'senin',
              //   minChunks: 2,
              //   test: (module) => {
              //     return /[\\/]node_modules[\\/]senin-mini[\\/]/.test(module.resource);
              //   },
              //   priority: 30,
              // },
            },
          },
        },
      });
    },
    commonChunks(commonChunks) {
      commonChunks.push('nutui');
      commonChunks.push('lodash');
      // commonChunks.push('senin');
      return commonChunks;
    },
  },
  h5: {
    publicPath: '/',
    staticDirectory: 'static',
    postcss: {
      autoprefixer: {
        enable: true,
        config: {},
      },
      cssModules: {
        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
        config: {
          namingPattern: 'module', // 转换模式,取值为 global/module
          generateScopedName: '[name]__[local]___[hash:base64:5]',
        },
      },
    },
  },
  rn: {
    appName: 'taroDemo',
    postcss: {
      cssModules: {
        enable: false, // 默认为 false,如需使用 css modules 功能,则设为 true
      },
    },
  },
};

module.exports = function (merge) {
  if (process.env.NODE_ENV === 'development') {
    return merge(
      {},
      config,
      require('./dev'),
      process.env.APP_ENV === 'staging' ? require('./staging') : {}
    );
  }

  return merge(
    {},
    config,
    require('./prod'),
    process.env.APP_ENV === 'staging' ? require('./staging') : {}
  );
};