var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/editable-table/index.tsx
var editable_table_exports = {};
__export(editable_table_exports, {
  default: () => editable_table_default
});
module.exports = __toCommonJS(editable_table_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_hooks = require("../_util/hooks");
var import_context = require("../config-provider/context");
var import_drag_table = __toESM(require("../drag-table"));
var import_index = require("./index.less");
var FIELD_NAME = "dataSource";
var PREFIX = "$$dynamic_id_";
function getRowNamePath(columns, index, prefix) {
  let fieldArr = columns.filter((item) => {
    var _a;
    return !!((_a = item.formItemProps) == null ? void 0 : _a.rules);
  }).map((item) => item.dataIndex), namePath = [];
  fieldArr.forEach((key) => namePath.push([prefix, index, key]));
  return namePath;
}
var EditTable = (0, import_react.forwardRef)((props, ref) => {
  const componentContext = (0, import_react.useContext)(import_context.ConfigContext);
  const { uiLocale } = componentContext;
  const { dragger, rowKey = "id", name = FIELD_NAME, columns, dataSource, form: outerForm, placeholder = "-", onSort, footer, ...rest } = props;
  const [form] = import_antd.Form.useForm(outerForm);
  const [editMap, setEditMap] = (0, import_react.useState)({});
  const [activeIndex, setActiveIndex] = (0, import_react.useState)();
  const operateRef = (0, import_react.useRef)();
  const [operation, setOperation] = (0, import_react.useState)();
  const cacheRecord = (0, import_react.useRef)({});
  const getDataSource = () => form.getFieldsValue()[name] || [];
  (0, import_react.useEffect)(() => {
    dataSource !== void 0 && form.setFieldsValue({ [name]: dataSource });
  }, [dataSource, form, name]);
  (0, import_react.useEffect)(() => {
    setOperation(operateRef.current);
  }, []);
  const setMode = (key, bool) => {
    setEditMap({ ...editMap, [key]: bool });
  };
  const setIndex = (key) => {
    var _a;
    setActiveIndex((_a = getDataSource()) == null ? void 0 : _a.findIndex((item) => (item[rowKey] ?? item[PREFIX]) === key));
  };
  const _onConfirm = (key, index, fn) => {
    var _a, _b;
    setIndex(key);
    let currRecord = ((_b = (_a = getDataSource()) == null ? void 0 : _a.filter((item) => (item[rowKey] ?? item[PREFIX]) === key)) == null ? void 0 : _b[0]) || {};
    form.validateFields(getRowNamePath(columns, index, name)).then(() => {
      if (fn) {
        if (currRecord == null ? void 0 : currRecord[PREFIX]) {
          delete currRecord[PREFIX];
        }
        let res = fn(currRecord, index) || {};
        if (res.then) {
          res.then(() => {
            setMode(key, false);
          });
          return;
        }
      }
      setMode(key, false);
    });
  };
  const _onCancel = (key, index) => {
    setIndex(key);
    if (key.toString().includes(PREFIX)) {
      operation == null ? void 0 : operation.remove(index);
    } else {
      let currDataSource = getDataSource();
      currDataSource.splice(index, 1, cacheRecord.current[key]);
      form.setFieldsValue({ [name]: currDataSource });
    }
    delete cacheRecord.current[key];
    setMode(key, false);
  };
  const _onEdit = (key, record) => {
    setIndex(key);
    cacheRecord.current[key] = record;
    setMode(key, true);
  };
  const _onDelete = (key, index) => {
    setIndex(key);
    operation == null ? void 0 : operation.remove(index);
    setMode(key, false);
  };
  const _onAdd = (value, index) => {
    let dynamicId = `${PREFIX}${Date.now()}`;
    operation == null ? void 0 : operation.add(value || { [PREFIX]: dynamicId }, index);
    setIndex(dynamicId);
    setMode(dynamicId, true);
  };
  const _onSort = (from, to, move) => {
    let allData = getDataSource();
    const [item] = allData.splice(from, 1);
    allData.splice(to, 0, item);
    move(from, to);
    onSort && onSort(allData);
  };
  const renderColumns = (column) => (text, record, index) => {
    const { fieldType, fieldProps, dataIndex, formItemProps = {}, editable, render } = column;
    let relRecord = form.getFieldValue([name, index]) || {}, relText = relRecord[dataIndex];
    const onlyKey = relRecord[rowKey] ?? relRecord[PREFIX];
    const isEdit = editable ? typeof editable === "boolean" ? editable : editable(relText, relRecord, index) : !!editMap[onlyKey];
    if (fieldType && render) {
      console.warn("fieldType 与 render属性结合使用时，fieldType属性无效!");
    }
    if (render) {
      let renderDom = render(relText, relRecord, index, {
        activeIndex,
        editable: isEdit,
        onConfirm: (fn) => _onConfirm(onlyKey, index, fn),
        onCancel: () => _onCancel(onlyKey, index),
        onEdit: () => _onEdit(onlyKey, relRecord),
        onDelete: () => _onDelete(onlyKey, index)
      });
      return (0, import_react.isValidElement)(renderDom) ? /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { ...formItemProps, className: "in-cell-field", name: [index, dataIndex] }, renderDom) : renderDom;
    }
    if (isEdit) {
      let formDom = relText ?? placeholder;
      fieldType === "input" && (formDom = /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { placeholder: uiLocale.global.inputPlaceholder, ...fieldProps }));
      fieldType === "textarea" && (formDom = /* @__PURE__ */ import_react.default.createElement(import_antd.Input.TextArea, { placeholder: uiLocale.global.inputPlaceholder, ...fieldProps }));
      fieldType === "inputNumber" && (formDom = /* @__PURE__ */ import_react.default.createElement(import_antd.InputNumber, { placeholder: uiLocale.global.inputPlaceholder, ...fieldProps }));
      return /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { ...formItemProps, className: "in-cell-field", name: [index, dataIndex] }, formDom);
    }
    return relText ?? placeholder;
  };
  const options = {
    ...operation,
    add: _onAdd
  };
  (0, import_react.useImperativeHandle)(ref, () => options);
  const tableProps = {
    ...rest,
    columns: columns.map((item) => {
      return {
        ...item,
        render: renderColumns(item)
      };
    }),
    footer: footer ? (data) => footer(data, options) : void 0
  };
  const content = /* @__PURE__ */ import_react.default.createElement(import_antd.Form.List, { name }, (fields, { add, remove, move }) => {
    !operateRef.current && (operateRef.current = { add, remove, move });
    return dragger ? /* @__PURE__ */ import_react.default.createElement(import_drag_table.default, { ...tableProps, rowKey: "key", dataSource: fields, onSort: (from, to) => _onSort(from, to, move) }) : /* @__PURE__ */ import_react.default.createElement(import_antd.Table, { ...tableProps, rowKey: "key", dataSource: fields });
  });
  return (0, import_hooks.useConfig)(
    /* @__PURE__ */ import_react.default.createElement("div", { className: "u-editable-table" }, outerForm ? content : /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, autoComplete: "off" }, content))
  );
});
var editable_table_default = EditTable;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {});
