"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateThemeVarsFile = exports.handleAssets = exports.generateHTML = exports.generateProjectFiles = void 0;
const lowcode_generator_1 = require("@cloudbase/lowcode-generator");
const generateFiles_1 = require("../util/generateFiles");
const path_1 = __importDefault(require("path"));
const cals_1 = require("@cloudbase/cals");
const util_1 = require("../util");
const common_1 = require("../util/common");
const webpack_1 = require("../service/webpack");
const config_1 = require("../config");
const lodash_1 = require("lodash");
const fs_extra_1 = __importDefault(require("fs-extra"));
const common_2 = require("../types/common");
/**
 * 该函数从 @govcloud/generate 取到需要的模版文件
 */
async function generateProjectFiles(buildData) {
    const fileCodeMap = await (0, lowcode_generator_1.generateCode)(buildData);
    Promise.all(Object.keys(fileCodeMap).map(async (filePath) => {
        await (0, generateFiles_1.writeFile)(path_1.default.join(buildData.appBuildDir || '', filePath), fileCodeMap[filePath].code).catch((e) => console.error(e));
    }));
}
exports.generateProjectFiles = generateProjectFiles;
async function generateHTML({ appId, appBuildDir, externalResources = [], mode, devTool, isBuildApp, buildTypeList, cdnEndpoints, }) {
    const templatePath = path_1.default.join(config_1.appTemplateDir, 'html', 'index.html.ejs');
    const dstFilePath = path_1.default.join(appBuildDir, 'index.html');
    const packageTpl = await fs_extra_1.default.readFile(templatePath, { encoding: 'utf8' });
    const jsApis = [];
    const cssStyles = [];
    for (let externalResource of externalResources) {
        switch (externalResource.type) {
            case cals_1.EExternalResourceType.JSUrl: {
                jsApis.push(externalResource.url || '');
                break;
            }
            case cals_1.EExternalResourceType.CSSUrl: {
                cssStyles.push(externalResource.url || '');
                break;
            }
        }
    }
    await fs_extra_1.default.writeFile(dstFilePath, (0, lodash_1.template)(packageTpl)({
        appId,
        title: '',
        desc: 'WeDa构建的应用',
        canUseVite: (0, util_1.canUseVite)(mode, devTool),
        jsApis: Array.from(new Set(jsApis.filter((item) => !!item))),
        cssStyles: Array.from(new Set(cssStyles.filter((item) => !!item))),
        mode,
        isBuildApp,
        isAdminPortal: (0, common_2.buildAsAdminPortalByBuildType)(buildTypeList),
        cdnEndpoints: (0, config_1.generateCdnEndpoints)(cdnEndpoints),
    }));
}
exports.generateHTML = generateHTML;
async function handleAssets({ appBuildDir, buildTypeList, assets, }) {
    const assetsArr = assets
        .split(',')
        .filter((str) => !!str)
        .map((str) => str.trim())
        .filter((str) => !!str);
    let jsApis = [];
    fs_extra_1.default.ensureDir(path_1.default.resolve(appBuildDir, 'assets'));
    if (buildTypeList.includes('qywxH5')) {
        jsApis = ['//res.wx.qq.com/open/js/jweixin-1.2.0.js'];
    }
    else if (buildTypeList.includes('wxH5')) {
        jsApis = ['//res.wx.qq.com/open/js/jweixin-1.6.0.js'];
    }
    if (assetsArr && assetsArr.length > 0) {
        if (buildTypeList.includes('app')) {
            const targetDir = path_1.default.resolve(appBuildDir, './assets');
            assetsArr.forEach(async (assetUrl) => {
                console.log('============>>>>>> getWebpackWebBuildParams assetUrl', assetUrl);
                if (assetUrl) {
                    const fileName = (0, common_1.getFileNameByUrl)(assetUrl);
                    jsApis.push(`./${fileName}`);
                    await (0, webpack_1.downloadAssets)(targetDir, assetUrl);
                }
            });
        }
        else {
            jsApis = jsApis.concat(assetsArr);
        }
    }
    return jsApis;
}
exports.handleAssets = handleAssets;
async function generateThemeVarsFile(themeVars = {}, appBuildDir) {
    const themeVarsPath = path_1.default.resolve(appBuildDir, './webpack/themeVars.js');
    // 清除没有的变量
    for (const key in themeVars) {
        if (!themeVars[key]) {
            delete themeVars[key];
        }
    }
    await (0, generateFiles_1.writeFile)(themeVarsPath, `module.exports = ${JSON.stringify(themeVars, null, 2)}`);
}
exports.generateThemeVarsFile = generateThemeVarsFile;
