/**
 * amis-ui v6.12.0-beta.0
 * Copyright 2018-2025 fex
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var tslib = require('tslib');
var React = require('react');
var amisCore = require('amis-core');
var Button = require('../Button.js');
var icons = require('../icons.js');
var InputBox = require('../InputBox.js');
var Common = require('./Common.js');
var Item = require('./Item.js');
var PickerContainer = require('../PickerContainer.js');
var FormField = require('../FormField.js');
var Checkbox = require('../Checkbox.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var React__default = /*#__PURE__*/_interopDefaultLegacy(React);

var __react_jsx__ = require('react');
var _J$X_ = (__react_jsx__["default"] || __react_jsx__).createElement;
(__react_jsx__["default"] || __react_jsx__).Fragment;
var SchemaEditorItemObject = /** @class */ (function (_super) {
    tslib.__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: amisCore.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 = tslib.__assign(tslib.__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: amisCore.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 = tslib.__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: amisCore.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] = tslib.__assign(tslib.__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] = tslib.__assign(tslib.__assign({}, members[index]), { schema: tslib.__assign(tslib.__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 = tslib.__rest(_a, ["key", "isRequired"]);
        var mini = this.props.mini;
        var members = this.state.members.concat();
        members[index] = tslib.__assign(tslib.__assign(tslib.__assign({}, members[index]), (mini
            ? {
                key: key,
                required: required
            }
            : undefined)), { schema: tslib.__assign({}, item) });
        this.setState({ members: members }, this.pipeOut);
    };
    SchemaEditorItemObject.prototype.handlePropRequiredChange = function (index, required) {
        var members = this.state.members.concat();
        members[index] = tslib.__assign(tslib.__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 (_J$X_(React__default["default"].Fragment, null,
            _J$X_(FormField.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 (_J$X_(InputBox["default"], tslib.__assign({}, field, { placeholder: __((_b = placeholder === null || placeholder === void 0 ? void 0 : placeholder.key) !== null && _b !== void 0 ? _b : ''), mobileUI: mobileUI })));
                } }),
            _J$X_(FormField.Controller, { label: __('JSONSchema.required'), name: "isRequired", control: methods.control, render: function (_a) {
                    var field = _a.field;
                    return (_J$X_(Checkbox["default"], tslib.__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 (_J$X_("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 (_J$X_(Item.SchemaEditorItem, { dataName: memberKey, mobileUI: mobileUI, mini: mini, key: member.id, types: types, onTypeChange: onTypeChange, enableAdvancedSetting: enableAdvancedSetting, popOverContainer: popOverContainer, prefix: mini ? undefined : (_J$X_(React__default["default"].Fragment, null,
                        _J$X_(InputBox["default"], { 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") }),
                        _J$X_(InputBox["default"], { 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: _J$X_(Button["default"], { 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) },
                        _J$X_(icons.Icon, { icon: "remove", className: "icon" })), value: mini
                        ? tslib.__assign(tslib.__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 }));
            })) : (_J$X_("div", { className: cx('SchemaEditorProps-placeholder') }, __((_a = placeholder === null || placeholder === void 0 ? void 0 : placeholder.empty) !== null && _a !== void 0 ? _a : ''))),
            mini ? (_J$X_(PickerContainer["default"], { mobileUI: mobileUI, value: {
                    type: 'string'
                }, bodyRender: function (_a) {
                    var isOpened = _a.isOpened, value = _a.value, onChange = _a.onChange, ref = _a.ref;
                    return isOpened ? (_J$X_(Item.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 (_J$X_(Button["default"], { 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')));
            })) : (_J$X_(Button["default"], { 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 (_J$X_(React__default["default"].Fragment, null,
                        _J$X_(FormField.Controller, { label: __('JSONSchema.members'), name: "properties", control: methods.control, render: function (_a) {
                                var field = _a.field;
                                return (_J$X_(Item.SchemaEditorItem, tslib.__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 (_J$X_("div", { className: cx('SchemaEditorItem SchemaEditorObject', {
                'is-collapsed': this.state.collapsed,
                'SchemaEditorItem--mini': mini
            }), "data-amis-name": this.props.dataName },
            showInfo !== false ? (_J$X_(React__default["default"].Fragment, null,
                mini ? null : (_J$X_("a", { className: cx('SchemaEditor-caret', {
                        'is-collapsed': this.state.collapsed
                    }), onClick: this.toggleCollapsed },
                    _J$X_(icons.Icon, { icon: "caret", className: "icon" }))),
                this.renderCommon())) : null,
            this.state.collapsed || (mini && expandMembers !== true)
                ? null
                : this.rendererProps()));
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "pipeOut", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handleAdd", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handleAddProppertyConfirm", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Number, Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handleEditProppertyConfirm", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Number, String]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropKeyChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Number, String]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropTitleChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Number]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropRemove", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Number, Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Number, Boolean]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "handlePropRequiredChange", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "toggleCollapsed", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], SchemaEditorItemObject.prototype, "renderFormPrefix", null);
    return SchemaEditorItemObject;
}(Common.SchemaEditorItemCommon));
Common.ITEMMAP.object = SchemaEditorItemObject;

exports.SchemaEditorItemObject = SchemaEditorItemObject;
