/**
 * amis-ui v6.14.0-beta.1
 * 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 Group = require('./Group.js');
var config = require('./config.js');
var PickerContainer = require('../PickerContainer.js');
var ResultBox = require('../ResultBox.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 QueryBuilder = /** @class */ (function (_super) {
    tslib.__extends(QueryBuilder, _super);
    function QueryBuilder() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.config = tslib.__assign(tslib.__assign({}, config["default"]), _this.props.config);
        _this.lastMoveAt = 0;
        return _this;
    }
    QueryBuilder.prototype.handleDragStart = function (e) {
        var _a = this.props.draggable, draggable = _a === void 0 ? true : _a;
        // draggable为false时不可拖拽
        if (!draggable)
            return;
        var target = e.currentTarget;
        var item = target.closest('[data-id]');
        this.dragTarget = item;
        // this.dragNextSibling = item.nextElementSibling;
        this.host = item.closest('[data-group-id]');
        var ghost = item.cloneNode(true);
        ghost.classList.add('is-ghost');
        this.ghost = ghost;
        e.dataTransfer.setDragImage(item.firstChild, 0, 0);
        target.addEventListener('dragend', this.handleDragEnd);
        document.body.addEventListener('dragover', this.handleDragOver);
        document.body.addEventListener('drop', this.handleDragDrop);
        this.lastX = e.clientX;
        this.lastY = e.clientY;
        // 应该是 chrome 的一个bug，如果你马上修改，会马上执行 dragend
        setTimeout(function () {
            item.classList.add('is-dragging');
            // item.parentElement!.insertBefore(
            //   item,
            //   item.parentElement!.firstElementChild
            // ); // 挪到第一个，主要是因为样式问题。
        }, 5);
    };
    QueryBuilder.prototype.handleDragOver = function (e) {
        e.preventDefault();
        var item = e.target.closest('[data-id]');
        var dx = e.clientX - this.lastX;
        var dy = e.clientY - this.lastY;
        var d = Math.max(Math.abs(dx), Math.abs(dy));
        var now = Date.now();
        // 没移动还是不要处理，免得晃动个不停。
        if (d < 5) {
            if (this.lastMoveAt === 0) ;
            else if (now - this.lastMoveAt > 500) {
                var host = e.target.closest('[data-group-id]');
                if (host) {
                    this.host = host;
                    this.lastMoveAt = now;
                    this.lastX = 0;
                    this.lastY = 0;
                    this.handleDragOver(e);
                    return;
                }
            }
            return;
        }
        this.lastMoveAt = now;
        this.lastX = e.clientX;
        this.lastY = e.clientY;
        if (!item ||
            item.classList.contains('is-ghost') ||
            item.closest('[data-group-id]') !== this.host) {
            return;
        }
        var container = item.parentElement;
        var children = [].slice.apply(container.children);
        var idx = children.indexOf(item);
        if (this.ghost.parentElement !== container) {
            container.appendChild(this.ghost);
        }
        var rect = item.getBoundingClientRect();
        var isAfter = dy > 0 && e.clientY > rect.top + rect.height / 2;
        var gIdx = isAfter ? idx : idx - 1;
        var cgIdx = children.indexOf(this.ghost);
        if (gIdx !== cgIdx) {
            amisCore.animation.capture(container);
            if (gIdx === children.length - 1) {
                container.appendChild(this.ghost);
            }
            else {
                container.insertBefore(this.ghost, children[gIdx + 1]);
            }
            amisCore.animation.animateAll();
        }
    };
    QueryBuilder.prototype.handleDragDrop = function () {
        var _a, _b;
        var onChange = this.props.onChange;
        var fromId = this.dragTarget.getAttribute('data-id');
        var toId = this.host.getAttribute('data-group-id');
        var children = [].slice.call(this.ghost.parentElement.children);
        var idx = children.indexOf(this.dragTarget);
        if (~idx) {
            children.splice(idx, 1);
        }
        var toIndex = children.indexOf(this.ghost);
        var value = this.props.value;
        var indexes = amisCore.findTreeIndex([value], function (item) { return item.id === fromId; });
        if (indexes) {
            var origin_1 = amisCore.getTree([value], indexes.concat());
            _a = tslib.__read(amisCore.spliceTree([value], indexes, 1), 1), value = _a[0];
            var indexes2 = amisCore.findTreeIndex([value], function (item) { return item.id === toId; });
            if (indexes2) {
                _b = tslib.__read(amisCore.spliceTree([value], indexes2.concat(toIndex), 0, origin_1), 1), value = _b[0];
                onChange(value);
            }
        }
    };
    QueryBuilder.prototype.handleDragEnd = function (e) {
        var _a;
        var target = e.target;
        target.removeEventListener('dragend', this.handleDragEnd);
        document.body.removeEventListener('dragover', this.handleDragOver);
        document.body.removeEventListener('drop', this.handleDragDrop);
        this.dragTarget.classList.remove('is-dragging');
        // if (this.dragNextSibling) {
        //   this.dragTarget.parentElement!.insertBefore(
        //     this.dragTarget,
        //     this.dragNextSibling
        //   );
        // } else {
        //   this.dragTarget.parentElement!.appendChild(this.dragTarget);
        // }
        delete this.dragTarget;
        // delete this.dragNextSibling;
        (_a = this.ghost.parentElement) === null || _a === void 0 ? void 0 : _a.removeChild(this.ghost);
        delete this.ghost;
    };
    QueryBuilder.prototype.handleClear = function () {
        this.props.onChange();
    };
    QueryBuilder.prototype.highlightValue = function (value) {
        var _a = this.props, cx = _a.classnames, __ = _a.translate;
        var html = {
            __html: "<span class=\"label label-info\">".concat(__('Condition.configured'), "</span>")
        };
        return (_J$X_("div", { className: cx('CPGroup-result'), dangerouslySetInnerHTML: html }));
    };
    QueryBuilder.prototype.renderBody = function (onChange, value, popOverContainer) {
        var _a = this.props, cx = _a.classnames, fieldClassName = _a.fieldClassName, fields = _a.fields, funcs = _a.funcs, showNot = _a.showNot, showANDOR = _a.showANDOR, data = _a.data, disabled = _a.disabled, _b = _a.draggable, draggable = _b === void 0 ? true : _b, searchable = _a.searchable, builderMode = _a.builderMode, formula = _a.formula, renderEtrValue = _a.renderEtrValue, selectMode = _a.selectMode, isAddBtnVisibleOn = _a.isAddBtnVisibleOn, isAddGroupBtnVisibleOn = _a.isAddGroupBtnVisibleOn, showIf = _a.showIf, uniqueFields = _a.uniqueFields, formulaForIf = _a.formulaForIf, testIdBuilder = _a.testIdBuilder;
        var normalizedValue = Array.isArray(value === null || value === void 0 ? void 0 : value.children)
            ? tslib.__assign(tslib.__assign({}, value), { children: amisCore.mapTree(value.children, function (value) {
                    if (value.id) {
                        return value;
                    }
                    return tslib.__assign(tslib.__assign({}, value), { id: amisCore.guid() });
                }) }) : value;
        var finalFields = fields || this.config.fields;
        if (uniqueFields && Array.isArray(value === null || value === void 0 ? void 0 : value.children)) {
            finalFields = amisCore.mapTree(finalFields, function (field) {
                var selected = amisCore.findTree(value === null || value === void 0 ? void 0 : value.children, function (rule) { var _a, _b; return ((_a = rule.left) === null || _a === void 0 ? void 0 : _a.type) === 'field' && ((_b = rule.left) === null || _b === void 0 ? void 0 : _b.field) === field.name; });
                if (selected) {
                    return tslib.__assign(tslib.__assign({}, field), { disabled: true });
                }
                return field;
            });
        }
        return (_J$X_(Group["default"], { builderMode: builderMode, config: this.config, funcs: funcs || this.config.funcs, fields: finalFields, value: normalizedValue, onChange: onChange, classnames: cx, fieldClassName: fieldClassName, removeable: false, onDragStart: this.handleDragStart, showANDOR: showANDOR, showNot: showNot, data: data, disabled: disabled, draggable: draggable, searchable: searchable, formula: formula, renderEtrValue: renderEtrValue, popOverContainer: popOverContainer, selectMode: selectMode, depth: 1, isAddBtnVisibleOn: isAddBtnVisibleOn, isAddGroupBtnVisibleOn: isAddGroupBtnVisibleOn, showIf: showIf, formulaForIf: formulaForIf, testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('group') }));
    };
    QueryBuilder.prototype.render = function () {
        var _this = this;
        var _a = this.props, cx = _a.classnames, placeholder = _a.placeholder, _b = _a.embed, embed = _b === void 0 ? true : _b, pickerIcon = _a.pickerIcon, locale = _a.locale, translate = _a.translate, classPrefix = _a.classPrefix, onFinalChange = _a.onChange, value = _a.value, title = _a.title, disabled = _a.disabled, popOverContainer = _a.popOverContainer, testIdBuilder = _a.testIdBuilder, mobileUI = _a.mobileUI;
        if (embed) {
            return this.renderBody(onFinalChange, value, popOverContainer);
        }
        /** 因为 ConditionBuilder特殊的数据结构，提供给 ResultBox 的需要处理一下 */
        var resultBoxValue = embed === false
            ? !value ||
                !(value === null || value === void 0 ? void 0 : value.hasOwnProperty('children')) ||
                !Array.isArray(value.children) ||
                value.children.length < 1
                ? undefined
                : value
            : value;
        return (_J$X_(PickerContainer["default"], { classnames: cx, classPrefix: classPrefix, translate: translate, locale: locale, onConfirm: onFinalChange, value: value, size: 'md', popOverContainer: popOverContainer, bodyRender: function (params) { return _this.renderBody(params.onChange, params.value); }, title: title }, function (_a) {
            var onClick = _a.onClick, isOpened = _a.isOpened;
            return (_J$X_(ResultBox["default"], { classnames: cx, classPrefix: classPrefix, translate: translate, locale: locale, className: cx('CBGroup-result', { 'is-active': isOpened }), allowInput: false, clearable: true, result: resultBoxValue, itemRender: _this.highlightValue, onResultChange: amisCore.noop, onClear: _this.handleClear, disabled: disabled, borderMode: 'full', placeholder: placeholder, actions: pickerIcon && (_J$X_("span", { className: cx('CBPicker-trigger'), onClick: onClick }, pickerIcon)), mobileUI: mobileUI, onResultClick: onClick, testIdBuilder: testIdBuilder === null || testIdBuilder === void 0 ? void 0 : testIdBuilder.getChild('result-box') }));
        }));
    };
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], QueryBuilder.prototype, "handleDragStart", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [DragEvent]),
        tslib.__metadata("design:returntype", void 0)
    ], QueryBuilder.prototype, "handleDragOver", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], QueryBuilder.prototype, "handleDragDrop", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Event]),
        tslib.__metadata("design:returntype", void 0)
    ], QueryBuilder.prototype, "handleDragEnd", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", []),
        tslib.__metadata("design:returntype", void 0)
    ], QueryBuilder.prototype, "handleClear", null);
    tslib.__decorate([
        amisCore.autobind,
        tslib.__metadata("design:type", Function),
        tslib.__metadata("design:paramtypes", [Object]),
        tslib.__metadata("design:returntype", void 0)
    ], QueryBuilder.prototype, "highlightValue", null);
    return QueryBuilder;
}(React__default["default"].Component));
var ConditionBuilder = amisCore.themeable(amisCore.localeable(amisCore.uncontrollable(QueryBuilder, {
    value: 'onChange'
})));

exports.QueryBuilder = QueryBuilder;
exports["default"] = ConditionBuilder;
