"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 });
const react_1 = __importStar(require("react"));
const react_redux_1 = require("react-redux");
const icons_1 = require("@ant-design/icons");
const antd_1 = require("antd");
const ACTIONS = __importStar(require("@/actions/applications/detail/file/variables"));
const index_1 = require("@/components/index");
const index_2 = require("@/constants/index");
const system_1 = require("@/pages/system");
const utils_1 = require("@/sagas/builder/utils");
const name_check_1 = require("@/utils/name-check");
const FunctionSelect_1 = __importDefault(require("./FunctionSelect"));
const { Option } = antd_1.Select;
const mapStateToProps = (store) => ({
    editorDrawerOpen: store.applications.detail.file.variables.drawerVisible,
    editVariable: store.applications.detail.file.variables.editVariable,
    pageInfo: store.applications.detail.file.variables.pageInfo,
});
const mapDispatchToProps = {
    closeDrawer: ACTIONS.openEditDrawer,
    fetchList: ACTIONS.fetchList,
    saveVariable: ACTIONS.saveVariable,
    update: ACTIONS.updateEditVariableValue,
    updateContent: ACTIONS.updateVariableContentValue,
    updateRelation: ACTIONS.updateVariableContentRelation,
    updateVariableContentProps: ACTIONS.updateVariableContentProps,
    updateVariableRelations: ACTIONS.updateVariableRelations,
};
const EditDrawer = (props) => {
    var _a, _b, _c;
    const { applicationId, folderId, editorDrawerOpen, editVariable, pageInfo, closeDrawer, fetchList, saveVariable, update, updateContent, updateRelation, updateVariableContentProps, updateVariableRelations, } = props;
    const [funcDrawerVisible, setFuncDrawerVisible] = (0, react_1.useState)(false);
    const [func, setFunc] = (0, react_1.useState)(undefined);
    const [isEditType, setIsEditType] = (0, react_1.useState)(false);
    // i18n
    const { locale } = (0, react_1.useContext)(system_1.GlobalContext);
    const { global, function: functionI18n, variable } = locale.business;
    (0, react_1.useEffect)(() => {
        var _a, _b;
        setFunc(undefined);
        const relation = (_a = editVariable === null || editVariable === void 0 ? void 0 : editVariable.content) === null || _a === void 0 ? void 0 : _a.relation;
        const relations = editVariable === null || editVariable === void 0 ? void 0 : editVariable.relations;
        if (relation) {
            for (const key in relation) {
                if (relation[key].type === index_2.FileType.function) {
                    const funcContent = (_b = relations === null || relations === void 0 ? void 0 : relations.functions) === null || _b === void 0 ? void 0 : _b.find((item) => item.id === relation[key].id);
                    if (funcContent) {
                        setFunc(funcContent);
                    }
                }
            }
        }
    }, [editVariable]);
    const handleVariableFunctionChange = (selectedFunc) => {
        if (!selectedFunc) {
            return;
        }
        const props = editVariable.content.schemas[0].props;
        const relationKey = `${(0, utils_1.getFunctionRelationKey)(selectedFunc.contentId)}`;
        updateRelation('relation', {
            [relationKey]: {
                id: selectedFunc.contentId,
                type: 'function',
            },
        });
        updateVariableRelations({ functions: [selectedFunc.content] });
        updateContent('props', {
            function: `{{${relationKey}}}`,
            args: props.args,
        });
    };
    const columns = [
        {
            title: global.nameLabel,
            dataIndex: 'name',
            key: 'name',
            render: (_text, record) => record.schemas[0].name,
        },
        {
            title: global.type,
            dataIndex: 'type',
            key: 'type',
            width: 100,
            render: (_text, record) => record.schemas[0].props.async ? 'async' : 'sync',
        },
    ];
    const type = (0, react_1.useMemo)(() => {
        var _a, _b;
        const schemas = ((_a = editVariable === null || editVariable === void 0 ? void 0 : editVariable.content) === null || _a === void 0 ? void 0 : _a.schemas) || [];
        if (schemas.length > 0) {
            return (_b = schemas[0]) === null || _b === void 0 ? void 0 : _b.type;
        }
        return '';
    }, [editVariable]);
    const handleUpdateName = (name) => {
        if (!!folderId) {
            if (name.startsWith('_')) {
                update('name', name);
            }
            else {
                update('name', '');
            }
        }
        else {
            if (!name.startsWith('_')) {
                update('name', name);
            }
            else {
                update('name', '');
            }
        }
    };
    const handleSave = () => {
        if ((0, name_check_1.nameErrorCheck)(editVariable === null || editVariable === void 0 ? void 0 : editVariable.name)) {
            return;
        }
        saveVariable({
            applicationId,
            folderId,
        }, () => {
            handleClose();
            fetchList({
                applicationId,
                folderId,
                page: pageInfo.page,
                size: pageInfo.size,
            });
        });
    };
    const handleClose = () => {
        setFuncDrawerVisible(false);
        setFunc(undefined);
        setIsEditType(false);
        closeDrawer(false);
    };
    return (react_1.default.createElement(index_1.OperationDrawer, { destroyOnClose: true, width: 480, open: editorDrawerOpen, title: editVariable && editVariable.id ? variable.edit : variable.add, onClose: handleClose, actions: react_1.default.createElement(antd_1.Button, { type: "primary", onClick: handleSave }, global.apply) }, editVariable ? (react_1.default.createElement(index_1.Group, null,
        react_1.default.createElement(index_1.Field, null,
            react_1.default.createElement(index_1.Label, null, editVariable && !editVariable.id && !!folderId
                ? global.nameLabelWithUnderline
                : global.nameLabel),
            react_1.default.createElement(antd_1.Input, { value: editVariable === null || editVariable === void 0 ? void 0 : editVariable.name, disabled: !!editVariable.id, placeholder: editVariable && !editVariable.id && !!folderId
                    ? global.nameLabelWithUnderline
                    : global.nameLabel, onChange: (e) => handleUpdateName(e.target.value) })),
        react_1.default.createElement(index_1.Field, null,
            react_1.default.createElement(index_1.Label, null, global.type),
            isEditType ? (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement(antd_1.Input, { disabled: !!editVariable.id, placeholder: global.type, value: type, onChange: (e) => {
                        updateContent('type', e.target.value);
                    }, style: { width: 200 } }),
                react_1.default.createElement(antd_1.Button, { disabled: !!editVariable.id, type: "default", icon: react_1.default.createElement(icons_1.BarsOutlined, null), onClick: () => {
                        setIsEditType(false);
                    }, style: { marginLeft: 4 } }))) : (react_1.default.createElement(react_1.default.Fragment, null,
                react_1.default.createElement(antd_1.Select, { disabled: !!editVariable.id, style: { width: 200 }, value: type, onChange: (value) => {
                        updateContent('type', value);
                    } }, index_2.VariableTypes.map((type) => (react_1.default.createElement(Option, { value: type, key: type }, type)))),
                react_1.default.createElement(antd_1.Button, { disabled: !!editVariable.id, style: { marginLeft: 4 }, type: "default", icon: react_1.default.createElement(icons_1.EditOutlined, null), onClick: () => {
                        setIsEditType(true);
                    } })))),
        type === index_2.VariableTypes[1] ? (react_1.default.createElement(react_1.default.Fragment, null,
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, functionI18n.name),
                react_1.default.createElement(antd_1.Table, { columns: columns, bordered: true, dataSource: func ? [func] : [], pagination: false, size: "small" }),
                react_1.default.createElement(antd_1.Button, { type: "dashed", size: "small", style: { width: '100%', marginTop: 12 }, onClick: () => {
                        setFuncDrawerVisible(true);
                    } }, variable.selectFunction)),
            react_1.default.createElement(index_1.Field, null,
                react_1.default.createElement(index_1.Label, null, variable.args),
                react_1.default.createElement(index_1.JSONEditor, { jsonData: editVariable.content.schemas[0].props.args || [], onChangeJSON: (json) => {
                        updateVariableContentProps('args', json);
                    }, onError: () => {
                        updateVariableContentProps('args', []);
                    } })))) : (react_1.default.createElement(index_1.Field, null,
            react_1.default.createElement(index_1.Label, null, variable.value),
            react_1.default.createElement(index_1.JSONEditor, { refreshFlag: editVariable.id, jsonData: ((_c = (_b = (_a = editVariable.content.schemas) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.props) === null || _c === void 0 ? void 0 : _c.value) || {}, onChangeJSON: (json) => {
                    updateContent('props', {
                        value: json,
                        type: 'json',
                    });
                }, onError: () => {
                    updateContent('props', {
                        value: {},
                        type: 'json',
                    });
                } }))),
        react_1.default.createElement(FunctionSelect_1.default, { applicationId: applicationId, funcId: func === null || func === void 0 ? void 0 : func.id, folderId: folderId, visible: funcDrawerVisible, onChange: (selectedFunc) => {
                handleVariableFunctionChange(selectedFunc);
            }, onClose: () => setFuncDrawerVisible(false) }))) : (react_1.default.createElement("div", null))));
};
exports.default = (0, react_redux_1.connect)(mapStateToProps, mapDispatchToProps)(EditDrawer);
