import React from 'react';
import { CnPopup, formilyReact } from '@cainiaofe/cn-ui';
import './index.scss';
import isPlainObject from 'lodash/isPlainObject';
import classNames from 'classnames';
import { useModel } from '../mobx-react-simpler/index.js';
const { connect, observer, useFieldSchema } = formilyReact;
const DropdownFormItem = connect(observer((props) => {
    var _a;
    const { children, renderNode, onSubmit, columnWidth: propColumnWidth } = props;
    // const field = useField();
    const fieldSchema = useFieldSchema();
    // 获取列宽（用于设置弹窗宽度）
    const dataModel = useModel('dataModel');
    const { activeViewId } = dataModel || {};
    const viewConfig = activeViewId ? dataModel.getViewConfig(activeViewId) : null;
    const widthMap = ((_a = viewConfig === null || viewConfig === void 0 ? void 0 : viewConfig.custom) === null || _a === void 0 ? void 0 : _a.widthMap) || {};
    const columnId = fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema.name;
    const columnWidth = propColumnWidth || (columnId ? widthMap[columnId] : undefined) || 200;
    const disabled = fieldSchema['x-disabled'];
    const isCompose = (fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema['x-component']) === 'Compose';
    const isRangeDatePicker = [
        'RangePicker',
        'CnRangeDatePickerPro',
        'CnRangeTimePickerPro',
        'RangeTimePicker',
    ].includes(fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema['x-component']);
    const isCascaderSelect = [
        'CascaderSelect',
        'CnCascaderSelect',
        'TreeSelect',
        'AddressSelect',
        'DepartmentSelect',
        'CnDepartmentSelect',
        'CnAddress',
    ].includes(fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema['x-component']);
    const isDatePicker = ['DatePicker', 'CnDatePickerPro'].includes(fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema['x-component']);
    const isInner = ['Input', 'TextArea'].includes(fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema['x-component']);
    const isCurrencyAmount = (fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema['x-component']) === 'CnCurrencyAmountNumberPickerPro';
    // 挂载容器（避免被表格裁剪）
    const popupContainer = (e) => { var _a; return (_a = e === null || e === void 0 ? void 0 : e.closest('#cn-ui-page-scroll-container')) !== null && _a !== void 0 ? _a : document.body; };
    // 日期区间特殊宽度
    const contentStyle = {};
    // 日期区间选择器使用 CSS 类控制宽度（544px），不设置内联样式
    if (!isRangeDatePicker) {
        if (columnWidth) {
            contentStyle.width = `${columnWidth}px` || '200px';
        }
        if (isCascaderSelect) {
            contentStyle.width = '350px';
        }
        else if (isDatePicker) {
            contentStyle.width = '280px';
        }
    }
    const contentCls = classNames('cn-dropdown-form-item__content', {
        'cn-dropdown-form-item__content__date-range': isRangeDatePicker,
    });
    const renderComposePop = () => {
        const properties = fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema.properties;
        const keys = isPlainObject(properties) ? Object.keys(properties) : [];
        return (React.createElement(React.Fragment, null, keys.map((key) => (React.createElement("div", { key: key, className: "cn-ai-search-custom-select-popup-container", id: key })))));
    };
    // 处理币种金额组件的弹层关闭逻辑
    const handleVisibleChange = React.useCallback((visible) => {
        if (visible === false) {
            // 对于币种金额组件，延迟检查是否有币种下拉弹层打开
            if (isCurrencyAmount) {
                setTimeout(() => {
                    // 检查是否有币种下拉弹层打开
                    const currencyDropdown = document.querySelector('[class*="cn-select-dropdown"]');
                    // 如果币种下拉弹层还在，说明用户还在选择，不关闭外层弹层
                    if (currencyDropdown) {
                        return;
                    }
                    // 币种下拉弹层已关闭，可以关闭外层弹层并提交
                    onSubmit();
                }, 200);
            }
            else {
                onSubmit();
            }
        }
    }, [isCurrencyAmount, onSubmit]);
    return (React.createElement(CnPopup, { disabled: disabled, triggerType: "click", v2: true, onVisibleChange: handleVisibleChange, container: popupContainer, trigger: 
        // 单元格编辑时，trigger 就是当前值（由外部控制显示）
        React.createElement("div", { className: "cn-dropdown-form-item__trigger__wrapper" }, renderNode), offset: !isInner ? [-13, 13] : [-13, -30] },
        React.createElement("div", { className: contentCls, style: contentStyle },
            children,
            React.createElement("div", { className: "cn-search-custom-select-container" },
                React.createElement("div", { className: "cn-ai-search-custom-select-popup-container", id: fieldSchema === null || fieldSchema === void 0 ? void 0 : fieldSchema.name }),
                isCompose && renderComposePop()))));
}));
export default DropdownFormItem;
