"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;
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const antd_1 = require("antd");
const ACTIONS = __importStar(require("@/actions/applications/detail/packages/detail"));
const application_1 = require("@/apis/application");
const index_1 = require("@/components/index");
const store_1 = require("@/constants/store");
const system_1 = require("@/pages/system");
const index_2 = require("./components/index");
const mapStateToProps = (store) => {
    var _a, _b, _c, _d, _e;
    return ({
        applicationId: store.applications.detail.settings.app.applicationId,
        contentId: (_a = store.applications.detail.packages.detail.componentInfo) === null || _a === void 0 ? void 0 : _a.id,
        open: (_b = store.applications.detail.packages.detail.versionDrawer) === null || _b === void 0 ? void 0 : _b.open,
        type: (_c = store.applications.detail.packages.detail.versionDrawer) === null || _c === void 0 ? void 0 : _c.type,
        data: (_d = store.applications.detail.packages.detail.versionDrawer) === null || _d === void 0 ? void 0 : _d.data,
        packageType: (_e = store.applications.detail.packages.detail.componentInfo) === null || _e === void 0 ? void 0 : _e.type,
        fileDetail: store.applications.detail.packages.detail.fileDetail,
    });
};
const mapDispatchToProps = {
    closeDrawer: ACTIONS.resetVersionDrawerState,
    addVersion: ACTIONS.addComponentVersionAction,
    editVersion: ACTIONS.editComponentVersionAction,
};
const VersionEditDrawer = (props) => {
    var _a;
    const { applicationId, contentId, open, type, data, closeDrawer, addVersion, editVersion, fileDetail, } = props;
    const initialValuesRef = (0, react_1.useRef)();
    const versionDetailRef = (0, react_1.useRef)();
    const isComponent = (fileDetail === null || fileDetail === void 0 ? void 0 : fileDetail.type) === 'component';
    const isRefer = !!((_a = fileDetail === null || fileDetail === void 0 ? void 0 : fileDetail.tags) === null || _a === void 0 ? void 0 : _a.find((item) => item.type === store_1.StoreGoodsPurchaseType.reference));
    // i18n
    const { locale } = (0, react_1.useContext)(system_1.GlobalContext);
    const { global, version } = locale.business;
    const [form] = antd_1.Form.useForm();
    (0, react_1.useMemo)(() => {
        if (type === 'add') {
            initialValuesRef.current = undefined;
        }
        else {
            const { versionId = '' } = data || {};
            if (applicationId && versionId) {
                initialValuesRef.current = (0, application_1.getComponentsEditVersions)({
                    applicationId,
                    id: versionId,
                }).then((rs) => {
                    const { code, msg, data } = rs;
                    if (code !== 200) {
                        antd_1.message.error(msg);
                        return;
                    }
                    else {
                        return data;
                    }
                });
            }
        }
    }, [type, data]);
    const disableState = (0, react_1.useMemo)(() => {
        return type === 'view';
    }, [type]);
    const afterVisibleChange = (0, react_1.useCallback)((visiable) => {
        var _a;
        if (visiable) {
            (_a = initialValuesRef.current) === null || _a === void 0 ? void 0 : _a.then((data) => {
                if (data) {
                    versionDetailRef.current = data;
                    const { content, version } = data;
                    const { meta = {}, schema, resource, useStyleEditor, enableChildren, changelog = '' } = content || {};
                    const { entry, 'editor-entry': editorEntry, dependencies = [] } = resource || {};
                    const { browser, node, debug, css } = entry || {};
                    const initForm = {
                        version,
                        meta,
                        schema,
                        browser: parseValueForTreeSelect(browser),
                        node: parseValueForTreeSelect(node),
                        debug: parseValueForTreeSelect(debug),
                        css: parseValueForTreeSelect(css),
                        editor: transformPackageToFormData(editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry[0]),
                        dependencies: dependencies.map(transformPackageToFormData).filter(Boolean),
                        useStyleEditor,
                        enableChildren,
                        changelog,
                    };
                    form.setFieldsValue(initForm);
                }
            });
        }
        else {
            initialValuesRef.current = undefined;
            form.resetFields();
        }
    }, []);
    const onSave = () => {
        if (isRefer) {
            return;
        }
        form
            .validateFields()
            .then((values) => {
            const params = transformFormToParams(values);
            if (type === 'add') {
                addVersion(Object.assign(Object.assign({}, params), { applicationId,
                    contentId }), {
                    onSuccess: () => closeDrawer(),
                });
            }
            else {
                const { versionId = '' } = data || {};
                editVersion(Object.assign(Object.assign({}, params), { applicationId, id: versionId }), {
                    onSuccess: () => closeDrawer(),
                });
            }
        })
            .catch((info) => {
            console.warn('Validate Failed:', info);
        });
    };
    const parseValueForTreeSelect = (data) => {
        const { contentId, path } = data || {};
        if (!data || !contentId || !path) {
            return undefined;
        }
        return {
            value: contentId,
            label: path,
            path,
        };
    };
    const transformFormToParams = (formValues) => {
        const { version, browser, node, debug, css, editor, dependencies = [], useStyleEditor, enableChildren, meta = {}, schema = {}, changelog = '', } = formValues || {};
        const editorEntry = [editor]
            .map((item) => {
            if (item === null || item === void 0 ? void 0 : item.value) {
                return {
                    id: item.value,
                };
            }
            return undefined;
        })
            .filter(Boolean);
        const dep = dependencies
            .map((item) => {
            if (item === null || item === void 0 ? void 0 : item.value) {
                return {
                    id: item.value,
                };
            }
            return undefined;
        })
            .filter(Boolean);
        return {
            version,
            content: {
                resource: {
                    entry: {
                        browser: (browser === null || browser === void 0 ? void 0 : browser.value) || '',
                        node: (node === null || node === void 0 ? void 0 : node.value) || '',
                        debug: (debug === null || debug === void 0 ? void 0 : debug.value) || '',
                        css: (css === null || css === void 0 ? void 0 : css.value) || '',
                    },
                    'editor-entry': editorEntry,
                    dependencies: dep,
                },
                meta,
                schema,
                useStyleEditor,
                enableChildren,
                changelog,
            },
        };
    };
    const transformPackageToFormData = (pkg) => {
        const { id, name } = pkg || {};
        if (id && name) {
            return {
                value: id,
                label: name,
            };
        }
        return undefined;
    };
    if (!contentId)
        return null;
    return (react_1.default.createElement(index_1.OperationDrawer, { destroyOnClose: true, canExpend: true, width: 700, title: type === 'edit' ? version.edit : version.add, actions: react_1.default.createElement(antd_1.Button, { type: "primary", onClick: onSave, disabled: isRefer }, global.apply), open: open, onClose: closeDrawer, afterVisibleChange: afterVisibleChange },
        react_1.default.createElement(antd_1.Form, { layout: "vertical", form: form },
            react_1.default.createElement(index_1.Group, null,
                react_1.default.createElement(antd_1.Form.Item, { name: "version", label: react_1.default.createElement(index_1.Title, null, version.name), required: true, rules: [
                        {
                            required: true,
                            validator: (_rule, value = '') => {
                                const arr = value.split('.');
                                if (arr.length !== 3 ||
                                    arr.find((item) => {
                                        return !item || item !== String(Number(item));
                                    }) !== undefined) {
                                    return Promise.reject(version.versionError);
                                }
                                return Promise.resolve('');
                            },
                        },
                    ] },
                    react_1.default.createElement(antd_1.Input, { placeholder: "Version", disabled: disableState, style: { width: '200px' } }))),
            react_1.default.createElement(index_1.Group, null,
                react_1.default.createElement(index_1.Title, null, version.source),
                react_1.default.createElement(antd_1.Form.Item, { name: "browser", label: "Browser", rules: [{ required: true }] },
                    react_1.default.createElement(index_2.ResPathTreeSelect, { applicationId: applicationId || '', disabled: disableState })),
                isComponent && applicationId && (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement(antd_1.Form.Item, { name: "node", label: "Node" },
                        react_1.default.createElement(index_2.ResPathTreeSelect, { applicationId: applicationId, disabled: disableState })),
                    react_1.default.createElement(antd_1.Form.Item, { name: "debug", label: "Debug" },
                        react_1.default.createElement(index_2.ResPathTreeSelect, { applicationId: applicationId, disabled: disableState })),
                    react_1.default.createElement(antd_1.Form.Item, { name: "css", label: "Css" },
                        react_1.default.createElement(index_2.ResPathTreeSelect, { applicationId: applicationId, disabled: disableState }))))),
            isComponent && applicationId && (react_1.default.createElement(index_1.Group, null,
                react_1.default.createElement(antd_1.Form.Item, { name: "editor", label: "Editor" },
                    react_1.default.createElement(index_2.PackageSelect, { applicationId: applicationId, packageType: "editor", ignoreContentIds: [contentId], disabled: isRefer })),
                react_1.default.createElement(antd_1.Form.Item, { name: "useStyleEditor", label: version.useStyleEditor, valuePropName: "checked" },
                    react_1.default.createElement(antd_1.Switch, { disabled: isRefer })))),
            isComponent && applicationId && (react_1.default.createElement(index_1.Group, null,
                react_1.default.createElement(index_1.Title, null, version.dependency),
                react_1.default.createElement(antd_1.Form.Item, { name: "dependencies", label: "" },
                    react_1.default.createElement(index_2.PackageSelect, { applicationId: applicationId, packageType: "component,library", mode: "multiple", disabled: disableState, ignoreContentIds: [contentId] })))),
            react_1.default.createElement(index_1.Group, null,
                react_1.default.createElement(index_1.Title, null, version.config),
                isComponent && (react_1.default.createElement(antd_1.Form.Item, { name: "enableChildren", label: version.enableChildren, valuePropName: "checked" },
                    react_1.default.createElement(antd_1.Switch, { disabled: isRefer }))),
                react_1.default.createElement(antd_1.Form.Item, { name: "meta", label: "Meta" },
                    react_1.default.createElement(index_2.JSONEditorFormItem, { disabled: isRefer })),
                react_1.default.createElement(antd_1.Form.Item, { name: "schema", label: "Schema" },
                    react_1.default.createElement(index_2.JSONEditorFormItem, { disabled: isRefer })),
                react_1.default.createElement(antd_1.Form.Item, { name: "changelog", label: version.changelog },
                    react_1.default.createElement(antd_1.Input.TextArea, { disabled: isRefer }))))));
};
exports.default = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(VersionEditDrawer);
