var _excluded = ["value", "onChange"],
  _excluded2 = ["className"],
  _excluded3 = ["className"],
  _excluded4 = ["getOptions"];
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useMemo } from 'react';
import { DatePicker, Form } from 'antd';
import dayjs from 'dayjs';
import classNames from 'classnames';
import { fieldMaps } from "../../../table/Table/fields";
import { PisellSingleLineText } from "../../../pisellSingleLineText";
import { PisellLongText } from "../../../pisellLongText";
import { PisellEmail } from "../../../pisellEmail";
import { PisellPhone } from "../../../pisellPhone";
import { PisellUrl } from "../../../pisellUrl";
import { PisellNumber } from "../../../pisellNumber";
import { PisellCurrency } from "../../../pisellCurrency";
import { PisellPercent } from "../../../pisellPercent";
import { PisellRating } from "../../../pisellRating";
import { PisellSingleSelect } from "../../../pisellSingleSelect";
import { PisellMultipleSelect } from "../../../pisellMultipleSelect";
import { getText } from "../../../../locales";
import { PisellMobileDateRangePicker } from "../../../pisellMobileDateRangePicker";
import AsyncOptionsSelectWrapper from "./AsyncOptionsSelectWrapper";
import "./index.less";
var RangePicker = DatePicker.RangePicker;

/** 手机 Filter 抽屉：控件统一 small，下拉关闭搜索与自动聚焦 */
function applyPhoneFilterControlProps(props, phoneLayout) {
  var _props$size;
  if (!phoneLayout) return props;
  return _objectSpread(_objectSpread({}, props), {}, {
    size: (_props$size = props.size) !== null && _props$size !== void 0 ? _props$size : 'small',
    showSearch: false,
    autoFocus: false,
    defaultOpen: false
  });
}

/** 列 type（RecordBoardFieldType）对应 Pisell 组件，用于筛选项编辑态；与 RecordBoard 列 type 一致 */
var PISELL_FIELD_TYPE_MAP = {
  singleLineText: PisellSingleLineText,
  longText: PisellLongText,
  email: PisellEmail,
  phone: PisellPhone,
  url: PisellUrl,
  number: PisellNumber,
  currency: PisellCurrency,
  percent: PisellPercent,
  rating: PisellRating,
  singleSelect: PisellSingleSelect,
  multipleSelect: PisellMultipleSelect
};

/** 筛选类型到 table field 类型的映射（table fields 无 single/input，用 select/text） */
var FILTER_TYPE_TO_FIELD = {
  single: 'select',
  input: 'text',
  datePicker: 'date',
  rangePicker: 'rangePicker',
  search: 'search'
};

/** 将 form 中可能为 string[] 或 dayjs[] 的值转为 RangePicker 需要的 [Dayjs, Dayjs] | null */
function toRangePickerValue(val) {
  if (val == null) return null;
  if (Array.isArray(val) && val.length >= 2) {
    var start = val[0] ? dayjs.isDayjs(val[0]) ? val[0] : dayjs(val[0]) : null;
    var end = val[1] ? dayjs.isDayjs(val[1]) ? val[1] : dayjs(val[1]) : null;
    if (start && end) return [start, end];
  }
  return null;
}

/** 使用 antd RangePicker，仅做 value 归一化以兼容 form 里存的 string[] */
var AntdRangePickerWithValue = /*#__PURE__*/React.forwardRef(function AntdRangePickerWithValue(_ref, ref) {
  var value = _ref.value,
    _onChange = _ref.onChange,
    rest = _objectWithoutProperties(_ref, _excluded);
  var normalized = toRangePickerValue(value);
  return /*#__PURE__*/React.createElement(RangePicker, _extends({}, rest, {
    ref: ref,
    placeholder: [getText('table-action-range-picker-placeholder-start'), getText('table-action-range-picker-placeholder-end')],
    value: normalized,
    onChange: function onChange(dates) {
      return _onChange === null || _onChange === void 0 ? void 0 : _onChange(dates !== null && dates !== void 0 ? dates : undefined);
    }
  }));
});

/** 手机抽屉筛选项：Form.Item 纵向布局 class，配合 Dropdown phone-drawer 样式 */
var getPhoneFormItemClassName = function getPhoneFormItemClassName(phoneLayout, extraClassName) {
  return classNames(phoneLayout && 'filter-dropdown-form-item--phone', extraClassName);
};

/** 合并 formItemProps，保留手机抽屉纵向布局 class */
function mergePhoneFormItemProps(phoneLayout, formItemProps) {
  var props = _typeof(formItemProps) === 'object' && formItemProps !== null ? formItemProps : {};
  var _ref2 = props,
    className = _ref2.className,
    rest = _objectWithoutProperties(_ref2, _excluded2);
  return _objectSpread(_objectSpread({}, rest), {}, {
    className: getPhoneFormItemClassName(phoneLayout, className)
  });
}

/** 与 Form.Item name 一致：快筛可能为 string[] */
function resolveFilterFieldName(name) {
  if (Array.isArray(name)) {
    var last = name[name.length - 1];
    return last != null ? String(last) : '';
  }
  if (name == null) return '';
  return String(name);
}

/**
 * 手机布局下：orderDate 等日期-only 快筛用 antd-mobile 范围日历，避免 MUI 单框与文案重复。
 * 含 showTime 时仍走原 rangePicker（MUI），以免丢失时间维度。
 */
function shouldUseAntdMobileRangePickerForPhone(type, phoneLayout, name, other, itemProps) {
  if (type !== 'rangePicker' || !phoneLayout) return false;
  if ((other === null || other === void 0 ? void 0 : other.useAntdMobileRangePicker) === false) return false;
  var merged = _objectSpread(_objectSpread({}, _typeof(itemProps) === 'object' && itemProps ? itemProps : {}), other && _typeof(other) === 'object' ? other : {});
  var hasShowTime = Boolean(merged.showTime);
  if ((other === null || other === void 0 ? void 0 : other.useAntdMobileRangePicker) === true) {
    return !hasShowTime;
  }
  if (resolveFilterFieldName(name) !== 'orderDate') return false;
  return !hasShowTime;
}
function toBoundaryDate(val) {
  if (val == null) return undefined;
  if (val instanceof Date) return val;
  if (dayjs.isDayjs(val)) return val.toDate();
  if (typeof val === 'string' || typeof val === 'number') {
    var d = dayjs(val);
    return d.isValid() ? d.toDate() : undefined;
  }
  return undefined;
}
var FilterItem = function FilterItem(props) {
  var _componentProps$getOp;
  var label = props.label,
    type = props.type,
    name = props.name,
    other = props.other,
    isHidden = props.isHidden,
    itemProps = props.props,
    phoneLayout = props.phoneLayout,
    phoneQuickFilterSlot = props.phoneQuickFilterSlot;
  var fieldTypeFromColumn = other === null || other === void 0 ? void 0 : other.fieldType;
  var PisellCom = fieldTypeFromColumn ? PISELL_FIELD_TYPE_MAP[fieldTypeFromColumn] : undefined;

  // 无 type 列的自定义筛选组件：接收 value/onChange（由 Form.Item 注入）
  if (type === 'custom') {
    var CustomComponent = other === null || other === void 0 ? void 0 : other.component;
    if (!CustomComponent) return null;
    var _componentProps = applyPhoneFilterControlProps(_objectSpread(_objectSpread({}, itemProps || {}), other || {}), phoneLayout);
    delete _componentProps.component;
    /** 自定义容器内自行挂多个 Form.Item（多字段）时，外层不注册 name，避免与内层字段冲突 */
    var isMultiFieldComposite = Array.isArray(other === null || other === void 0 ? void 0 : other.compositeFilterFieldNames) && other.compositeFilterFieldNames.length > 0;
    return /*#__PURE__*/React.createElement(Form.Item, _extends({
      label: label,
      name: isMultiFieldComposite ? undefined : name,
      hidden: isHidden
    }, mergePhoneFormItemProps(phoneLayout, other === null || other === void 0 ? void 0 : other.formItemProps)), /*#__PURE__*/React.createElement(CustomComponent, _componentProps));
  }

  // rangePickerNew：使用 antd DatePicker.RangePicker，样式按 Figma；prefixCls 使 DOM 使用 pisell-lowcode- 便于样式隔离。rangePicker 走下方 fieldMaps，使用物料库自研 RangePicker。
  if (type === 'rangePickerNew') {
    var _componentProps2 = applyPhoneFilterControlProps(_objectSpread(_objectSpread(_objectSpread({}, itemProps || {}), other || {}), {}, {
      prefixCls: 'pisell-lowcode'
    }), phoneLayout);
    var formItemProps = _typeof(other === null || other === void 0 ? void 0 : other.formItemProps) === 'object' && other.formItemProps !== null ? other.formItemProps : {};
    var _ref3 = formItemProps,
      formItemClassName = _ref3.className,
      restFormItemProps = _objectWithoutProperties(_ref3, _excluded3);
    return /*#__PURE__*/React.createElement(Form.Item, _extends({
      label: label,
      name: name
    }, restFormItemProps, {
      hidden: isHidden,
      className: classNames('pisell-lowcode-range-picker-wrap', getPhoneFormItemClassName(phoneLayout, formItemClassName))
    }), /*#__PURE__*/React.createElement(AntdRangePickerWithValue, _componentProps2));
  }
  if (shouldUseAntdMobileRangePickerForPhone(type, phoneLayout, name, other, itemProps)) {
    var _merged$minDate, _merged$maxDate;
    var merged = _objectSpread(_objectSpread({}, _typeof(itemProps) === 'object' && itemProps ? itemProps : {}), other && _typeof(other) === 'object' ? other : {});
    var formatStr = typeof merged.format === 'string' && merged.format ? merged.format : 'DD/MM/YYYY';
    var placeholderStr = typeof merged.placeholder === 'string' && merged.placeholder || getText('table-action-range-picker-placeholder-start');
    return /*#__PURE__*/React.createElement(Form.Item, _extends({
      label: phoneQuickFilterSlot ? undefined : label,
      name: name,
      hidden: isHidden
    }, mergePhoneFormItemProps(phoneLayout, other === null || other === void 0 ? void 0 : other.formItemProps)), /*#__PURE__*/React.createElement(PisellMobileDateRangePicker, {
      variant: phoneQuickFilterSlot || phoneLayout ? 'toolbar' : 'filter',
      format: formatStr,
      placeholder: placeholderStr,
      title: label,
      allowClear: merged.allowClear !== false,
      min: toBoundaryDate((_merged$minDate = merged.minDate) !== null && _merged$minDate !== void 0 ? _merged$minDate : merged.min),
      max: toBoundaryDate((_merged$maxDate = merged.maxDate) !== null && _merged$maxDate !== void 0 ? _merged$maxDate : merged.max),
      onOpen: other === null || other === void 0 ? void 0 : other.onOpen,
      onClose: other === null || other === void 0 ? void 0 : other.onClose
    }));
  }
  var Com = useMemo(function () {
    var _FILTER_TYPE_TO_FIELD, _fieldMaps;
    if (PisellCom) return PisellCom;
    var fieldType = (_FILTER_TYPE_TO_FIELD = FILTER_TYPE_TO_FIELD[type]) !== null && _FILTER_TYPE_TO_FIELD !== void 0 ? _FILTER_TYPE_TO_FIELD : type;
    return (_fieldMaps = fieldMaps[fieldType]) === null || _fieldMaps === void 0 ? void 0 : _fieldMaps.edit;
  }, [type, PisellCom]);
  if (!Com) {
    return null;
  }
  var isPisell = Boolean(PisellCom);
  var isSelectFilter = type === 'single' || fieldTypeFromColumn === 'singleSelect' || fieldTypeFromColumn === 'multipleSelect';
  var componentProps = applyPhoneFilterControlProps(_objectSpread(_objectSpread(_objectSpread({}, itemProps || {}), other || {}), isPisell ? {
    mode: 'edit'
  } : {}), phoneLayout);
  var getOptions = (_componentProps$getOp = componentProps.getOptions) !== null && _componentProps$getOp !== void 0 ? _componentProps$getOp : other === null || other === void 0 ? void 0 : other.getOptions;
  var useAsyncOptions = isPisell && typeof getOptions === 'function' && (fieldTypeFromColumn === 'singleSelect' || fieldTypeFromColumn === 'multipleSelect');
  if (useAsyncOptions && fieldTypeFromColumn) {
    var _go = componentProps.getOptions,
      restProps = _objectWithoutProperties(componentProps, _excluded4);
    return /*#__PURE__*/React.createElement(Form.Item, _extends({
      label: label,
      name: name,
      hidden: isHidden
    }, mergePhoneFormItemProps(phoneLayout, other === null || other === void 0 ? void 0 : other.formItemProps)), /*#__PURE__*/React.createElement(AsyncOptionsSelectWrapper, _extends({
      getOptions: getOptions,
      fieldType: fieldTypeFromColumn
    }, restProps)));
  }
  return /*#__PURE__*/React.createElement(Form.Item, _extends({
    label: label,
    name: name,
    hidden: isHidden
  }, mergePhoneFormItemProps(phoneLayout, other === null || other === void 0 ? void 0 : other.formItemProps)), /*#__PURE__*/React.createElement(Com, componentProps));
};
export default FilterItem;