/**
 * amis-ui v6.14.0-beta.1
 * Copyright 2018-2025 fex
 */

import { __extends, __assign, __rest, __decorate, __metadata } from 'tslib';
import React__default from 'react';
import { guid, autobind } from 'amis-core';
import Button from '../Button.js';
import { Icon } from '../icons.js';
import InputBox from '../InputBox.js';
import { SchemaEditorItemCommon, ITEMMAP } from './Common.js';
import { SchemaEditorItem } from './Item.js';
import PickerContainer from '../PickerContainer.js';
import { Controller } from '../FormField.js';
import Checkbox from '../Checkbox.js';

var SchemaEditorItemObject = /** @class */ (function (_super) {
    __extends(SchemaEditorItemObject, _super);
    function SchemaEditorItemObject() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            members: _this.propsToMembers(_this.props),
            collapsed: false
        };
        return _this;
    }
    SchemaEditorItemObject.prototype.componentDidUpdate = function (prevProps) {
        var props = this.props;
        // 外部属性变化，更新 state
        if (props.value !== prevProps.value &&
            JSON.stringify(props.value) !== JSON.stringify(this.lastValue)) {
            this.setState({
                members: this.propsToMembers(props)
            });
        }
    };
    SchemaEditorItemObject.prototype.propsToMembers = function (props) {
        var _a, _b;
        var members = [];
        var required = Array.isArray((_a = props.value) === null || _a === void 0 ? void 0 : _a.required)
            ? props.value.required
            : [];
        if ((_b = props.value) === null || _b === void 0 ? void 0 : _b.properties) {
            var properties_1 = props.value.properties;
            Object.keys(properties_1).forEach(function (key) {
                var value = properties_1[key];
                members.push({
                    id: guid(),
                    key: key || '',
                    hasError: !key || members.some(function (i) { return i.key === key; }),
                    required: !!~required.indexOf(key),
                    schema: value
                });
            });
        }
        return members;
    };
    SchemaEditorItemObject.prototype.pipeOut = function () {
        var members = this.state.members;
        var _a = this.props, value = _a.value, onChange = _a.onChange;
        var properties = {};
        var required = [];
        members
            .filter(function (item) { return !item.hasError; })
            .forEach(function (member) {
            properties[member.key] = member.schema;
            if (member.required) {
                required.push(member.key);
            }
        });
        this.lastValue = __assign(__assign({}, value), { properties: properties, required: required });
        onChange === null || onChange === void 0 ? void 0 : onChange(this.lastValue);
    };
    SchemaEditorItemObject.prototype.handleAdd = function () {
        var members = this.state.members.concat();
        members.push({
            id: guid(),
            key: '',
            hasError: true,
            required: false,
            schema: {
                type: 'string'
            }
        });
        this.setState({
            members: members
        }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handleAddProppertyConfirm = function (_a) {
        var key = _a.key, required = _a.isRequired, value = __rest(_a, ["key", "isRequired"]);
        var members = this.state.members.concat();
        if (members.some(function (member) { return member.key === key; })) {
            throw new Error(this.props.translate('JSONSchema.key_duplicated'));
        }
        members.push({
            id: guid(),
            key: key || '',
            hasError: false,
            required: required,
            schema: value
        });
        this.setState({
            members: members
        }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handleEditProppertyConfirm = function (index, value) {
        var exists = this.state.members.some(function (m, i) { return i !== index && m.key === value.key; });
        if (exists) {
            throw new Error(this.props.translate('JSONSchema.key_duplicated'));
        }
    };
    SchemaEditorItemObject.prototype.handlePropKeyChange = function (index, key) {
        var members = this.state.members.concat();
        members[index] = __assign(__assign({}, members[index]), { key: key, hasError: !key || members.some(function (m, i) { return i !== index && m.key === key; }) });
        this.setState({ members: members }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handlePropTitleChange = function (index, title) {
        var members = this.state.members.concat();
        members[index] = __assign(__assign({}, members[index]), { schema: __assign(__assign({}, members[index].schema), { title: title }) });
        this.setState({ members: members }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handlePropRemove = function (index) {
        var members = this.state.members.concat();
        members.splice(index, 1);
        this.setState({ members: members }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handlePropChange = function (index, _a) {
        var key = _a.key, required = _a.isRequired, item = __rest(_a, ["key", "isRequired"]);
        var mini = this.props.mini;
        var members = this.state.members.concat();
        members[index] = __assign(__assign(__assign({}, members[index]), (mini
            ? {
                key: key,
                required: required
            }
            : undefined)), { schema: __assign({}, item) });
        this.setState({ members: members }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handlePropRequiredChange = function (index, required) {
        var members = this.state.members.concat();
        members[index] = __assign(__assign({}, members[index]), { required: required });
        this.setState({ members: members }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.toggleCollapsed = function () {
        this.setState({
            collapsed: !this.state.collapsed
        });
    };
    SchemaEditorItemObject.prototype.renderFormPrefix = function (methods) {
        var _a = this.props, placeholder = _a.placeholder, mobileUI = _a.mobileUI, cx = _a.classnames, __ = _a.translate;
        return (React__default.createElement(React__default.Fragment, null,
            React__default.createElement(Controller, { label: __('JSONSchema.key'), name: "key", control: methods.control, rules: { maxLength: 20, isVariableName: true }, isRequired: true, render: function (_a) {
                    var _b;
                    var field = _a.field;
                    return (React__default.createElement(InputBox, __assign({}, field, { placeholder: __((_b = placeholder === null || placeholder === void 0 ? void 0 : placeholder.key) !== null && _b !== void 0 ? _b : ''), mobileUI: mobileUI })));
                } }),
            React__default.createElement(Controller, { label: __('JSONSchema.required'), name: "isRequired", control: methods.control, render: function (_a) {
                    var field = _a.field;
                    return (React__default.createElement(Checkbox, __assign({}, field, { value: !!field.value, className: cx('SchemaEditor-required'), label: __('Required') })));
                } })));
    };
    SchemaEditorItemObject.prototype.rendererProps = function () {
        var _this = this;
        var _a;
        var _b = this.props, value = _b.value, __ = _b.translate, cx = _b.classnames, renderExtraProps = _b.renderExtraProps, renderModalProps = _b.renderModalProps, locale = _b.locale, classPrefix = _b.classPrefix, disabled = _b.disabled, showInfo = _b.showInfo, types = _b.types, onTypeChange = _b.onTypeChange, enableAdvancedSetting = _b.enableAdvancedSetting, popOverContainer = _b.popOverContainer, placeholder = _b.placeholder, mobileUI = _b.mobileUI, mini = _b.mini, addButtonText = _b.addButtonText, dataName = _b.dataName;
        var members = this.state.members;
        return (React__default.createElement("div", { className: cx('SchemaEditorProps', {
                'SchemaEditorProps--depth': showInfo !== false
            }) },
            members.length ? (members.map(function (member, index) {
                var _a, _b;
                var memberKey = dataName
                    ? dataName + '-' + member.key
                    : member.key;
                return (React__default.createElement(SchemaEditorItem, { dataName: memberKey, mobileUI: mobileUI, mini: mini, key: member.id, types: types, onTypeChange: onTypeChange, enableAdvancedSetting: enableAdvancedSetting, popOverContainer: popOverContainer, prefix: mini ? undefined : (React__default.createElement(React__default.Fragment, null,
                        React__default.createElement(InputBox, { className: cx('SchemaEditor-key'), hasError: member.hasError, value: member.key || '', onChange: _this.handlePropKeyChange.bind(_this, index), placeholder: __((_a = placeholder === null || placeholder === void 0 ? void 0 : placeholder.key) !== null && _a !== void 0 ? _a : ''), disabled: disabled || !!(value === null || value === void 0 ? void 0 : value.$ref), mobileUI: mobileUI, dataName: "".concat(memberKey, "-key") }),
                        React__default.createElement(InputBox, { className: cx('SchemaEditor-title'), value: member.schema.title || '', onChange: _this.handlePropTitleChange.bind(_this, index), placeholder: __((_b = placeholder === null || placeholder === void 0 ? void 0 : placeholder.title) !== null && _b !== void 0 ? _b : ''), disabled: disabled || !!(value === null || value === void 0 ? void 0 : value.$ref), mobileUI: mobileUI, dataName: "".concat(memberKey, "-title") }))), affix: React__default.createElement(Button, { className: cx('SchemaEditor-btn'), onClick: _this.handlePropRemove.bind(_this, index), iconOnly: !mini, level: mini ? 'link' : 'default', disabled: disabled || !!(value === null || value === void 0 ? void 0 : value.$ref) },
                        React__default.createElement(Icon, { icon: "remove", className: "icon" })), value: mini
                        ? __assign(__assign({}, member.schema), { key: member.key, isRequired: member.required })
                        : member.schema, onChange: _this.handlePropChange.bind(_this, index), onFormConfirm: _this.handleEditProppertyConfirm.bind(_this, index), renderExtraProps: renderExtraProps, renderModalProps: renderModalProps, locale: locale, translate: __, classnames: cx, classPrefix: classPrefix, disabled: disabled || !!(value === null || value === void 0 ? void 0 : value.$ref), required: member.required, onRequiredChange: _this.handlePropRequiredChange.bind(_this, index), placeholder: placeholder, formPrefixRender: _this.renderFormPrefix }));
            })) : (React__default.createElement("div", { className: cx('SchemaEditorProps-placeholder') }, __((_a = placeholder === null || placeholder === void 0 ? void 0 : placeholder.empty) !== null && _a !== void 0 ? _a : ''))),
            mini ? (React__default.createElement(PickerContainer, { mobileUI: mobileUI, value: {
                    type: 'string'
                }, bodyRender: function (_a) {
                    var isOpened = _a.isOpened, value = _a.value, onChange = _a.onChange, ref = _a.ref;
                    return isOpened ? (React__default.createElement(SchemaEditorItem, { types: types, value: value, onChange: onChange, renderExtraProps: renderExtraProps, renderModalProps: renderModalProps, locale: locale, translate: __, classnames: cx, classPrefix: classPrefix, disabled: disabled, onTypeChange: _this.handleTypeChange, enableAdvancedSetting: enableAdvancedSetting, popOverContainer: popOverContainer, placeholder: placeholder, mobileUI: mobileUI, mini: mini, formRef: ref, formMode: true, formPrefixRender: _this.renderFormPrefix })) : null;
                }, beforeConfirm: this.handleBeforeSubmit, onConfirm: this.handleAddProppertyConfirm, title: __('JSONSchema.add_prop'), popOverContainer: popOverContainer }, function (_a) {
                var onClick = _a.onClick;
                return (React__default.createElement(Button, { level: "enhance", block: true, onClick: onClick, size: "sm", disabled: disabled || !!(value === null || value === void 0 ? void 0 : value.$ref) }, addButtonText !== null && addButtonText !== void 0 ? addButtonText : __('JSONSchema.add_prop')));
            })) : (React__default.createElement(Button, { level: "link", onClick: this.handleAdd, size: "xs", disabled: disabled || !!(value === null || value === void 0 ? void 0 : value.$ref) }, addButtonText !== null && addButtonText !== void 0 ? addButtonText : __('JSONSchema.add_prop')))));
    };
    SchemaEditorItemObject.prototype.render = function () {
        var _a = this.props, cx = _a.classnames, showInfo = _a.showInfo, __ = _a.translate, formMode = _a.formMode; _a.disabled; var locale = _a.locale, classPrefix = _a.classPrefix, mini = _a.mini, types = _a.types, placeholder = _a.placeholder, mobileUI = _a.mobileUI, expandMembers = _a.expandMembers;
        if (formMode) {
            return this.renderForm({
                formAffixRender: function (methods) {
                    return (React__default.createElement(React__default.Fragment, null,
                        React__default.createElement(Controller, { label: __('JSONSchema.members'), name: "properties", control: methods.control, render: function (_a) {
                                var field = _a.field;
                                return (React__default.createElement(SchemaEditorItem, __assign({}, field, { types: types, value: {
                                        type: 'object',
                                        required: [],
                                        properties: field.value
                                    }, onChange: function (value) { return field.onChange(value.properties); }, placeholder: placeholder, mobileUI: mobileUI, locale: locale, translate: __, classnames: cx, classPrefix: classPrefix, mini: false })));
                            } })));
                }
            });
        }
        return (React__default.createElement("div", { className: cx('SchemaEditorItem SchemaEditorObject', {
                'is-collapsed': this.state.collapsed,
                'SchemaEditorItem--mini': mini
            }), "data-amis-name": this.props.dataName },
            showInfo !== false ? (React__default.createElement(React__default.Fragment, null,
                mini ? null : (React__default.createElement("a", { className: cx('SchemaEditor-caret', {
                        'is-collapsed': this.state.collapsed
                    }), onClick: this.toggleCollapsed },
                    React__default.createElement(Icon, { icon: "caret", className: "icon" }))),
                this.renderCommon())) : null,
            this.state.collapsed || (mini && expandMembers !== true)
                ? null
                : this.rendererProps()));
    };
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "pipeOut", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handleAdd", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handleAddProppertyConfirm", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Number, Object]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handleEditProppertyConfirm", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Number, String]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropKeyChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Number, String]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropTitleChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Number]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropRemove", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Number, Object]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Number, Boolean]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropRequiredChange", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", []),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "toggleCollapsed", null);
    __decorate([
        autobind,
        __metadata("design:type", Function),
        __metadata("design:paramtypes", [Object]),
        __metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "renderFormPrefix", null);
    return SchemaEditorItemObject;
}(SchemaEditorItemCommon));
ITEMMAP.object = SchemaEditorItemObject;

export { SchemaEditorItemObject };
