"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const lowcode_code_generator_1 = require("@alilc/lowcode-code-generator");
const lodash_1 = tslib_1.__importDefault(require("lodash"));
const const_1 = require("./const");
const pluginFactory = (config) => {
    const cfg = Object.assign({ fileType: 'vue' }, config);
    const plugin = (pre) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
        const next = Object.assign({}, pre);
        const ir = next.ir;
        if (!ir.lifeCycles) {
            return next;
        }
        const createLifeCyclesContent = () => {
            let pieces = [];
            lodash_1.default.forIn(ir.lifeCycles, (item, methodName) => {
                if (item.type === 'JSFunction') {
                    const functionBody = item.value.match(/\{([\s\S]*)\}/)[1].trim();
                    const paramsMatch = item.value.match(/^function\s*\(([^)]*)\)/);
                    const params = paramsMatch ? paramsMatch[1] : '';
                    const arrowFunctionString = `${methodName}(${functionBody.startsWith('(') ? '' : `(${params}) => `}{${functionBody}})`;
                    pieces.push(arrowFunctionString);
                }
            });
            return pieces.join('\n');
        };
        const createVueImport = () => {
            const lifeCycles = [];
            lodash_1.default.forIn(ir.lifeCycles, (item, methodName) => {
                if (item.type === 'JSFunction') {
                    lifeCycles.push(methodName);
                }
            });
            return `import { ref,${lifeCycles.join(',')} } from 'vue'`;
        };
        next.chunks.push({
            type: lowcode_code_generator_1.ChunkType.STRING,
            fileType: cfg.fileType,
            name: const_1.VUE_CHUNK_NAME.ScriptVueImp,
            content: createVueImport(),
            linkAfter: [const_1.VUE_CHUNK_NAME.ScriptStart],
        });
        next.chunks.push({
            type: lowcode_code_generator_1.ChunkType.STRING,
            fileType: cfg.fileType,
            name: const_1.VUE_CHUNK_NAME.ScriptLifeCycles,
            content: createLifeCyclesContent(),
            linkAfter: [const_1.VUE_CHUNK_NAME.ScriptVueImp, const_1.VUE_CHUNK_NAME.ScriptInitState],
        });
        return next;
    });
    return plugin;
};
exports.default = pluginFactory;
//# sourceMappingURL=lifeCycles.js.map