"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.mergeSubPackages = exports.generateMpConfig = void 0;
const path = __importStar(require("path"));
const lodash_1 = require("lodash");
const mp_1 = require("@cloudbase/lowcode-generator/lib/generator/config/mp");
const weapps_core_1 = require("@cloudbase/lowcode-generator/lib/weapps-core");
const config_1 = require("../config");
const net_1 = require("../util/net");
const chalk_1 = __importDefault(require("chalk"));
/**
 * generate app.json & page.json for mp
 *
 * @param kboneConfig https://wechat-miniprogram.github.io/kbone/docs/config/
 * @param appConfigs app config from prop edit panel
 */
function generateMpConfig(weapps, ctx, options) {
    var _a;
    const appConfig = {
        useExtendedLib: { weui: true },
    };
    const { miniprogramPlugins = [] } = ctx;
    const projConfig = (0, lodash_1.merge)({}, mp_1.defaultProjConfig, {
        projectname: (ctx.mainAppData && ctx.mainAppData.label) || `WeDa-${ctx.appId}`,
        appid: (options === null || options === void 0 ? void 0 : options.mpAppId) || mp_1.defaultProjConfig.appid,
    });
    const pageConfigs = weapps.map((app) => {
        var _a;
        const pageConfig = {};
        // #1 Get page config from mp config
        const kbConfig = (_a = app.lowCodes) === null || _a === void 0 ? void 0 : _a.find((m) => m.name === config_1.MP_CONFIG_MODULE_NAME);
        if (kbConfig) {
            const { pagesConfigJson = {} } = eval(`(${kbConfig.code.replace(/export\s+default/, '')})`);
            (0, lodash_1.merge)(pageConfig, pagesConfigJson);
        }
        // #2 Get page config from page page.data editor UI
        (0, lodash_1.merge)(pageConfig, getAppPagesConfig((app === null || app === void 0 ? void 0 : app.pageInstanceList) || []));
        return pageConfig;
    });
    const kbConfig = (_a = weapps[0].lowCodes) === null || _a === void 0 ? void 0 : _a.find((m) => m.name === config_1.MP_CONFIG_MODULE_NAME);
    if (kbConfig) {
        const { projectConfigJson = {}, appJson = {} } = eval(`(${kbConfig.code.replace(/export\s+default/, '')})`);
        // # project.config.json, https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html
        (0, lodash_1.merge)(projConfig, projectConfigJson);
        // # app.json, https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html
        if (appJson.tabBar) {
            parseTabConfig(appJson.tabBar, ctx.projDir);
        }
        (0, lodash_1.merge)(appConfig, appJson);
        // # page.json
        // merge(pageConfigs, pagesConfigJson)
    }
    const matertialMetaIgnores = ctx.materialLibs
        .filter((lib) => !lib.isComposite)
        .reduce((arr, lib) => {
        arr.push({ type: 'file', value: `materials/${lib.name}/meta.json` });
        return arr;
    }, []);
    projConfig.packOptions.ignore.push(...matertialMetaIgnores);
    const { tradingCapability, ...mainAppConfig } = weapps[0].appConfig || {};
    // keep main app config only, ignore subapp config
    const { subpackages, ...extra } = extractPages(weapps, pageConfigs);
    (0, lodash_1.merge)(appConfig, mainAppConfig, extra);
    appConfig.subpackages = mergeSubPackages(appConfig.subpackages, subpackages);
    if (tradingCapability) {
        const tradePluginKey = `weda-mini-shop-plugin`;
        const pluginMeta = {
            version: 'latest',
            provider: 'wx34345ae5855f892d',
        };
        let { plugins = {} } = appConfig;
        let find = false;
        for (let key in plugins) {
            let value = plugins[key];
            if (key === tradePluginKey || value.provider === pluginMeta.provider) {
                find = true;
                break;
            }
        }
        if (!find) {
            plugins[tradePluginKey] = pluginMeta;
        }
        appConfig.plugins = plugins;
    }
    miniprogramPlugins.forEach((plugin) => {
        var _a;
        if (!((_a = appConfig === null || appConfig === void 0 ? void 0 : appConfig.plugins) === null || _a === void 0 ? void 0 : _a[plugin.name])) {
            (0, lodash_1.set)(appConfig, `plugins.${plugin.name}`, {
                version: plugin.version,
                provider: plugin.pluginAppId,
            });
        }
    });
    if (options.mpAppId) {
        projConfig.appId = options.mpAppId;
    }
    // merge(pageConfigs, extractAllPagesConfig())
    return { appConfig, projConfig, pageConfigs };
}
exports.generateMpConfig = generateMpConfig;
function extractPages(weapps, pageConfigs) {
    const pages = [];
    const subpackages = [];
    let homePage = '';
    let homePageId = '';
    weapps.forEach((weapp, index) => {
        const { rootPath } = weapp;
        const subPackage = { root: rootPath, pages: [] };
        if (rootPath) {
            subpackages.push(subPackage);
        }
        (0, weapps_core_1.loopDealWithFn)(weapp.pageInstanceList || [], (page) => {
            const pageConfig = pageConfigs[index];
            const pageFileName = (0, lodash_1.get)(pageConfig, `${page.id}.pageFileName`, 'index');
            if (rootPath) {
                subPackage.pages.push(`pages/${page.id}/${pageFileName}`);
            }
            else if (!page.isHome) {
                pages.push(`pages/${page.id}/${pageFileName}`);
            }
            else {
                homePage = `pages/${page.id}/${pageFileName}`;
                homePageId = page.id;
            }
        });
    });
    if (homePage) {
        pages.unshift(homePage);
    }
    return { pages, subpackages, homePageId };
}
function getAppPagesConfig(pages) {
    const pagesConfig = {};
    pages.map((page) => {
        const pageConfig = transformDynamicData(page.data);
        delete pageConfig['title'];
        pagesConfig[page.id] = pageConfig;
    });
    return pagesConfig;
}
function transformDynamicData(originData) {
    const temp = {};
    for (const key in originData) {
        const target = originData[key];
        if (target === null || target === void 0 ? void 0 : target.value) {
            temp[key] = target.value;
        }
    }
    return temp;
}
function parseTabConfig(tabBar, projDir) {
    tabBar.list.map((tab, index) => {
        const { iconPath, selectedIconPath } = tab;
        if (iconPath) {
            tab.iconPath = parseTabIcon(iconPath, index, 'icon');
        }
        if (selectedIconPath) {
            tab.selectedIconPath = parseTabIcon(selectedIconPath, index, 'selectedIcon');
        }
    });
    function parseTabIcon(iconUrl, index, filename) {
        if (typeof iconUrl !== 'string') {
            console.error(chalk_1.default.red('App.json invalid tabbar icon path'), iconUrl);
            return;
        }
        const iconPath = `assets/tab${index}/${filename}${path.extname(iconUrl)}`;
        (0, net_1.downloadFile)(iconUrl, `${projDir}/${iconPath}`).catch((e) => {
            console.error(chalk_1.default.red(`Fail to download tabBar icon from ${iconUrl}`), e);
        });
        return iconPath;
    }
}
function mergeSubPackages(base = [], extra = []) {
    const baseMap = base.reduce((map, item) => {
        map[item.root] = item;
        return map;
    }, {});
    for (const subpackage of extra) {
        if (!baseMap[subpackage.root]) {
            base.push(subpackage);
            continue;
        }
        const current = baseMap[subpackage.root];
        current.pages = Array.from(new Set([...(current.pages || []), ...(subpackage.pages || [])]));
        if (current.plugins || subpackage.plugins) {
            current.plugins = (0, lodash_1.merge)(current.plugins, subpackage.plugins);
        }
    }
    return base;
}
exports.mergeSubPackages = mergeSubPackages;
