import { defineConfig, type UserConfigExport } from "@tarojs/cli";
import TsconfigPathsPlugin from "tsconfig-paths-webpack-plugin";
import { GitRevisionPlugin } from "git-revision-webpack-plugin";
import { UnifiedWebpackPluginV5 } from 'weapp-tailwindcss/webpack'
import * as path from "path";
import devConfig from "./dev";
import prodConfig from "./prod";

const gitRevision = new GitRevisionPlugin();

const CIPluginFn = async () => {
  // 可以在这里做一些异步事情， 比如请求接口获取配置
  /**
   * @typedef { import("@tarojs/plugin-mini-ci").CIOptions } CIOptions
   * @type {CIOptions}
   */
  return {
    weapp: {
      appid: "wxa080848726642f73",
      privateKeyPath: "key/private.wxa080848726642f73.key",
    },
    tt: {
      email: "字节小程序邮箱",
      password: "字节小程序密码",
    },
    alipay: {
      appid: "支付宝小程序appid",
      toolId: "工具id",
      privateKeyPath:
        "密钥文件相对项目根目录的相对路径，例如 key/pkcs8-private-pem",
    },
    dd: {
      appid: "钉钉小程序appid,即钉钉开放平台后台应用管理的 MiniAppId 选项",
      token: "令牌，从钉钉后台获取",
    },
    swan: {
      token: "鉴权需要的token令牌",
    },
    // 版本号
    version: "1.0.0",
    // 版本发布描述
    desc: "版本描述",
  };
};

// https://taro-docs.jd.com/docs/next/config#defineconfig-辅助函数
export default defineConfig<"webpack5">(async (merge, {}) => {
  const baseConfig: UserConfigExport<"webpack5"> = {
    alias: {
      "@/components": path.resolve(__dirname, "..", "src/components"),
      "@/store": path.resolve(__dirname, "..", "src/store"),
      "@/constants": path.resolve(__dirname, "..", "src/constants"),
      "@/service": path.resolve(__dirname, "..", "src/service"),
      "@/utils": path.resolve(__dirname, "..", "src/utils"),
      "@/config": path.resolve(__dirname, "..", "src/config"),
    },
    projectName: "app-client",
    date: "2023-9-18",
    plugins: [
      "@tarojs/plugin-html",
      "@tarojs/plugin-http",
      ["@tarojs/plugin-mini-ci", CIPluginFn],
      ['@tarojs/plugin-inject', {
        components: {
          View: {
            "aria-label": "",
            "aria-role": ""
          },
        },
      }]
    ],
    designWidth(input) {
      // 配置 NutUI 375 尺寸
      // @ts-ignore
      if (input?.file?.replace(/\\+/g, "/").indexOf("@nutui") > -1) {
        return 375;
      }
      // 全局使用 Taro 默认的 750 尺寸
      return 750;
    },
    deviceRatio: {
      640: 2.34 / 2,
      750: 1,
      375: 2,
      828: 1.81 / 2,
    },
    sourceRoot: "src",
    outputRoot: `dist/${process.env.TARO_ENV}`,
    defineConstants: {},
    copy: {
      patterns: [
        {
          from: "src/ext.json",
          to: "dist/weapp/ext.json",
        },
      ],
      options: {},
    },
    framework: "react",
    compiler: {
      type: "webpack5",
      prebundle: {
        enable: false,
        force: true,
        exclude: ["@nutui/nutui-react-taro", "@nutui/icons-react-taro"],
      },
    },
    cache: {
      enable: false, // Webpack 持久化缓存配置，建议开启。默认配置请参考：https://docs.taro.zone/docs/config-detail#cache
    },
    mini: {
      compile: { include: [path.resolve(__dirname, "../node_modules")] },
      debugReact: true,
      optimizeMainPackage: {
        enable: true,
      },
      commonChunks: ["runtime", "vendors", "taro", "common"],
      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) {
        chain
          .merge({
            plugin: {
              install: {
                plugin: UnifiedWebpackPluginV5,
                args: [
                  {
                    appType: "taro",
                    injectAdditionalCssVarScope: true,
                    rem2rpx: true,
                    cssEntries: [
                      // 你 @import "weapp-tailwindcss"; 那个文件绝对路径
                      path.resolve(__dirname, '../src/app.css')
                    ]
                  },
                ],
              },
            },
          })
          .resolve.plugin("tsconfig-paths")
          .use(TsconfigPathsPlugin);
      },
    },
    h5: {
      compile: { include: [path.resolve(__dirname, "../node_modules")] },
      publicPath: "/",
      staticDirectory: "static",
      router: {
        mode: "browser",
      },
      output: {
        filename: "pages/js/[name].[hash:8].js",
        chunkFilename: "pages/js/[name].[chunkhash:8].js",
      },
      miniCssExtractPluginOption: {
        ignoreOrder: true,
        filename: "pages/css/[name].[hash].css",
        chunkFilename: "pages/css/[name].[chunkhash].css",
      },
      postcss: {
        pxtransform: {
          enable: true,
          config: {
            baseFontSize: 16,
            minRootSize: 16,
            maxRootSize: 40,
          },
        },
        autoprefixer: {
          enable: true,
          config: {},
        },
        cssModules: {
          enable: true, // 默认为 false，如需使用 css modules 功能，则设为 true
          config: {
            namingPattern: "module", // 转换模式，取值为 global/module
            generateScopedName: "[name]__[local]___[hash:base64:5]",
          },
        },
      },
      webpackChain(chain) {
        chain.resolve.plugin("tsconfig-paths").use(TsconfigPathsPlugin);
        chain.merge({
          plugins: [gitRevision],
        });
        chain.plugin("htmlWebpackPlugin").tap((args) => {
          return [{ ...args[0], gitCommitId: gitRevision.commithash() }];
        });
      },
    },
    rn: {
      appName: "taroDemo",
      postcss: {
        cssModules: {
          enable: false, // 默认为 false，如需使用 css modules 功能，则设为 true
        },
      },
    },
  };
  if (process.env.NODE_ENV === "development") {
    // 本地开发构建配置（不混淆压缩）
    return merge({}, baseConfig, devConfig);
  }
  // 生产构建配置（默认开启压缩混淆等）
  return merge({}, baseConfig, prodConfig);
});
