"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.initEntry = void 0;
const antd_1 = require("antd");
const lodash_1 = __importDefault(require("lodash"));
const effects_1 = require("redux-saga/effects");
const typesafe_actions_1 = require("typesafe-actions");
const ACTIONS = __importStar(require("@/actions/applications/detail/packages/fast"));
const LIST_ACTIONS = __importStar(require("@/actions/applications/detail/packages/list"));
const API = __importStar(require("@/apis/application"));
const index_1 = require("@/foxI18n/index");
const index_2 = require("@/store/index");
function* handleFetchPackages(action) {
    yield (0, effects_1.put)(ACTIONS.updateLoading(true));
    const params = action.payload;
    const res = yield (0, effects_1.call)(API.fetchRemoteComponents, params);
    if (res.code === 200 && res.data) {
        const { data = [], pageInfo } = res;
        yield (0, effects_1.put)(ACTIONS.pushPackages(data, pageInfo));
    }
    else {
        const { component: { fetchUpdateInfoFailed }, } = (0, index_1.getBusinessI18n)();
        antd_1.message.error(fetchUpdateInfoFailed);
    }
    yield (0, effects_1.put)(ACTIONS.updateLoading(false));
}
const initEntry = (prefix, path) => {
    return { contentId: '', path: prefix + path };
};
exports.initEntry = initEntry;
const initEditorComponent = (name, groupId, contentId) => {
    return {
        name,
        groupId,
        component: {
            content: {
                resource: {
                    entry: {
                        browser: contentId, // ugly design
                    },
                },
                meta: {},
                schema: {},
            },
        },
    };
};
const editorWrapper = (components, savedResources = {}, groupId) => {
    const editors = [];
    components.forEach((item) => {
        var _a, _b, _c, _d, _e;
        const { components } = item;
        if (components[0]) {
            const { resource, component } = components[0];
            const componentName = resource.resourceName;
            const contentId = (_a = savedResources[componentName]) === null || _a === void 0 ? void 0 : _a.umd['editor.js'];
            const value = contentId ? contentId : (_e = (_d = (_c = (_b = component === null || component === void 0 ? void 0 : component.content) === null || _b === void 0 ? void 0 : _b.resource) === null || _c === void 0 ? void 0 : _c.entry) === null || _d === void 0 ? void 0 : _d.editor) === null || _e === void 0 ? void 0 : _e.path;
            if (value) {
                const editor = initEditorComponent(`${resource.name}_editor`, groupId, value);
                editors.push(editor);
            }
        }
    });
    return editors;
};
const componentWrapper = (components = [], changes, editors = {}) => {
    return components.map((item) => {
        const { components = [], lastVersion } = item;
        const savedComponent = lodash_1.default.cloneDeep(components[0]);
        const { component, resource } = savedComponent || {};
        const content = (component === null || component === void 0 ? void 0 : component.content) || {};
        const componentResource = content.resource || {};
        const entry = componentResource.entry;
        const { groupName, version, resourceName, name } = resource || {};
        const prefix = `${groupName}/${resourceName}/${version}/`;
        const values = changes[name] || {};
        if (values.browser) {
            entry.browser = (0, exports.initEntry)(prefix, values.browser);
        }
        if (values.debug) {
            entry.debug = (0, exports.initEntry)(prefix, values.debug);
        }
        if (values.node) {
            entry.node = (0, exports.initEntry)(prefix, values.node);
        }
        if (values.css) {
            entry.css = (0, exports.initEntry)(prefix, values.css);
        }
        delete entry.editor;
        // deal with editor
        const editorName = `${name}_editor`;
        const editor = editors[editorName];
        if (editor) {
            componentResource['editor-entry'] = [{ id: editor.id, name: editorName }];
        }
        // deal with lastVersion
        if (lastVersion) {
            content.meta = lastVersion.content.meta;
            componentResource.dependencies = lastVersion.content.resource.dependencies;
            component.content = Object.assign(Object.assign({}, lastVersion.content), content);
        }
        return savedComponent;
    });
};
function* handleSaveResource(params) {
    const res = yield (0, effects_1.call)(API.saveResourceBatch, params);
    if (res.code === 200) {
        return res.data || {};
    }
    else {
        const { resource: { saveResourceFiled }, } = (0, index_1.getBusinessI18n)();
        antd_1.message.error(saveResourceFiled);
        return null;
    }
}
function* handleSaveEditors(params) {
    const res = yield (0, effects_1.call)(API.saveEditors, params);
    if (res.code === 200) {
        return res.data || {};
    }
    else {
        const { package: { saveComponentFiled }, } = (0, index_1.getBusinessI18n)();
        antd_1.message.error(saveComponentFiled);
        return null;
    }
}
function* handleSaveComponents(params) {
    const res = yield (0, effects_1.call)(API.saveComponentRemote, params);
    const { global: { saveSuccess, saveFailed }, } = (0, index_1.getBusinessI18n)();
    if (res.code === 200) {
        antd_1.message.success(saveSuccess);
    }
    else {
        yield (0, effects_1.put)(ACTIONS.updateSaving(false));
        antd_1.message.error(saveFailed);
    }
}
function* handlePublishEditors(params) {
    const res = yield (0, effects_1.call)(API.batchPublishEditors, params);
    if (res.code === 200) {
    }
    else {
        const { global: { saveFailed }, } = (0, index_1.getBusinessI18n)();
        antd_1.message.error(saveFailed);
    }
}
function* handleSaveChanges(action) {
    yield (0, effects_1.put)(ACTIONS.updateSaving(true));
    const { applicationId, cb } = action.payload;
    const { packages = [], checkedList = [], changes = {}, groupId, } = index_2.store.getState().applications.detail.packages.fast;
    const filters = packages.filter((item) => checkedList.findIndex((key) => item.components[0].resource.name === key) > -1);
    // 1: save resource batch
    const needSaveResources = filters.map((item) => { var _a; return (_a = item.components[0]) === null || _a === void 0 ? void 0 : _a.resource; }).filter((item) => item.isNew);
    let savedResources = {};
    if (needSaveResources.length > 0) {
        savedResources = yield handleSaveResource({ applicationId, id: groupId, resources: needSaveResources });
    }
    if (!savedResources) {
        return null;
    }
    // 2: save editors
    const editors = editorWrapper(filters, savedResources, groupId);
    let savedEditors = {};
    if (editors.length > 0) {
        savedEditors = yield handleSaveEditors({ applicationId, components: editors });
    }
    if (!savedEditors) {
        return null;
    }
    yield handlePublishEditors({
        applicationId,
        idVersions: Object.values(savedEditors).map((item) => ({ id: item.id, version: item.version })),
    });
    // 3: save components
    const data = componentWrapper(filters, changes, savedEditors);
    yield handleSaveComponents({ applicationId, components: data });
    yield (0, effects_1.put)(ACTIONS.updateSaving(false));
    yield (0, effects_1.put)(ACTIONS.updateSelected([]));
    yield (0, effects_1.put)(ACTIONS.clearChanges());
    if (typeof cb === 'function') {
        cb();
    }
    else {
        const { pageInfo, searchName } = index_2.store.getState().applications.detail.packages.fast;
        yield (0, effects_1.put)(ACTIONS.fetchPackages({
            applicationId,
            groupId,
            size: pageInfo.size,
            page: pageInfo.page,
            name: searchName,
        }));
        yield (0, effects_1.put)(LIST_ACTIONS.fetchComponentsAction({ applicationId }));
    }
}
function* watch() {
    yield (0, effects_1.takeLatest)((0, typesafe_actions_1.getType)(ACTIONS.fetchPackages), handleFetchPackages);
    yield (0, effects_1.takeLatest)((0, typesafe_actions_1.getType)(ACTIONS.saveChanges), handleSaveChanges);
}
function* rootSaga() {
    yield (0, effects_1.all)([watch()]);
}
exports.default = rootSaga;
