"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleSubApps = exports.handleMixMode = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importStar(require("fs-extra"));
const mp_1 = require("../util/mp");
const generateFiles_1 = require("../util/generateFiles");
// 将 BUILD 目录往混合模式移动
async function handleMixMode({ buildContext, apps = [], miniprogramRoot, wedaRoot, }) {
    await handleSubApps({ buildContext, apps, miniprogramRoot, wedaRoot });
}
exports.handleMixMode = handleMixMode;
async function handleSubApps({ buildContext, apps = [], miniprogramRoot, wedaRoot, }) {
    let modifiedAppJson = false;
    const rootAppJosnPath = path_1.default.join(miniprogramRoot, 'app.json');
    let rootAppJosn = await fs_extra_1.default.readJSON(rootAppJosnPath);
    let modifiedPackageJosn = false;
    const rootPackageJosnPath = path_1.default.join(wedaRoot, 'package.json');
    let rootPackageJson = fs_extra_1.default.existsSync(rootPackageJosnPath)
        ? await fs_extra_1.default.readJson(rootPackageJosnPath)
        : {
            name: 'WeDa-app',
            version: '1.0.0',
        };
    let mergeDependencies = {};
    await Promise.all(apps
        .filter((app) => app.rootPath)
        .map(async (app) => {
        const subAppPath = path_1.default.join(wedaRoot, ...(app.rootPath ? ['packages', app.rootPath] : ['']));
        // 复制整个子包
        // 新模式下已经生成，感觉无需进行复制 @royhyang
        // const distDir = path.join(generateMpPath, app.rootPath || '')
        // await fs.copy(subAppPath, distDir, { overwrite: true })
        const appJsonPath = path_1.default.join(subAppPath, 'app.json');
        if (fs_extra_1.default.existsSync(appJsonPath)) {
            let appJson = await fs_extra_1.default.readJson(appJsonPath);
            if (appJson) {
                let { subpackages = [] } = rootAppJosn;
                const subRoot = path_1.default.join('./', buildContext.wedaRoot || '', `packages/${app.rootPath}`);
                const find = subpackages.find((item) => item.root === subRoot);
                if (find) {
                    find.pages = appJson.pages;
                }
                else {
                    if (!rootAppJosn.subpackages) {
                        rootAppJosn.subpackages = [];
                    }
                    rootAppJosn.subpackages.push({
                        root: subRoot,
                        pages: appJson.pages,
                    });
                }
                modifiedAppJson = true;
            }
        }
        const packageJosnPath = path_1.default.join(subAppPath, 'package.json');
        if (fs_extra_1.default.existsSync(packageJosnPath)) {
            mergeDependencies = {
                ...mergeDependencies,
                ...(await (0, mp_1.mergePackageDependencies)(mergeDependencies, await fs_extra_1.default.readJson(packageJosnPath))),
            };
            modifiedPackageJosn = true;
        }
        await Promise.all([
            'app.json',
            'app.js',
            'app.wxss',
            'project.config.json',
            'package.json',
            'node_modules',
            'miniprograme_npm',
        ].map((name) => {
            let clearPath = path_1.default.join(subAppPath, name);
            return name.includes('.') ? (0, generateFiles_1.removeFile)(clearPath) : (0, generateFiles_1.cleanDir)(clearPath, []);
        }));
    }));
    if (modifiedAppJson) {
        await (0, fs_extra_1.writeFile)(rootAppJosnPath, JSON.stringify(rootAppJosn, undefined, 2));
    }
    if (modifiedPackageJosn) {
        await (0, fs_extra_1.writeFile)(rootPackageJosnPath, JSON.stringify({
            ...rootPackageJson,
            ...(0, mp_1.mergePackageDependencies)(mergeDependencies, rootPackageJson), // 主包优先
        }, undefined, 2));
    }
}
exports.handleSubApps = handleSubApps;
