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/components/batch-editor/index.tsx
var batch_editor_exports = {};
__export(batch_editor_exports, {
  default: () => batch_editor_default
});
module.exports = __toCommonJS(batch_editor_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_table = __toESM(require("../table"));
var import_fields = __toESM(require("./fields"));
var import_Price = __toESM(require("./fields/Price"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_locales = require("../../locales/index");
var import_index = require("./index.less");
var BatchEditor = (props) => {
  var _a, _b, _c, _d, _e;
  const { columns, dataSource = [], onChange, rowKey, otherTableProps } = props;
  const [form] = import_antd.Form.useForm();
  const [openModal, setOpenModal] = (0, import_react.useState)(false);
  const [selectList, setSelectList] = (0, import_react.useState)([]);
  const context = (0, import_useEngineContext.default)();
  const { store } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const symbol = ((_d = (_c = (_b = store == null ? void 0 : store.getState) == null ? void 0 : _b.call(store)) == null ? void 0 : _c.global) == null ? void 0 : _d.symbol) || "$";
  const renderColumnItem = (0, import_react.useCallback)(
    (_item) => {
      return (text, record) => {
        if (!_item.type) {
          const Com2 = import_fields.default["text"];
          return /* @__PURE__ */ import_react.default.createElement("div", { className: "editor-item" }, /* @__PURE__ */ import_react.default.createElement(Com2, null, text));
        }
        if ((record.disabledList || []).includes(_item.dataIndex)) {
          return /* @__PURE__ */ import_react.default.createElement("div", { className: "editor-item", style: { padding: `0 11px` } }, /* @__PURE__ */ import_react.default.createElement(
            import_antd.Tooltip,
            {
              overlay: (record == null ? void 0 : record.disabledTexts) ? (
                //@ts-ignore
                (record == null ? void 0 : record.disabledTexts[_item.dataIndex]) || text
              ) : text
            },
            /* @__PURE__ */ import_react.default.createElement("div", { className: "name" }, (record == null ? void 0 : record.disabledTexts) ? (
              //@ts-ignore
              (record == null ? void 0 : record.disabledTexts[_item.dataIndex]) || text
            ) : text)
          ));
        }
        const Com = import_fields.default[_item.type];
        if (Com) {
          return /* @__PURE__ */ import_react.default.createElement("div", { className: "editor-item" }, /* @__PURE__ */ import_react.default.createElement(
            Com,
            {
              status: record.status,
              value: text,
              ..._item.componentProps,
              placeholder: _item.placeholder || record[_item.dataIndex + "placeholder"],
              symbol,
              onChange: (e) => {
                handleChange(e, _item.dataIndex, record[rowKey]);
              }
            }
          ));
        }
        return /* @__PURE__ */ import_react.default.createElement("div", { className: "editor-item" }, "-");
      };
    },
    [dataSource, rowKey, columns]
  );
  const _onChange = (newDataSource) => {
    onChange == null ? void 0 : onChange(newDataSource);
  };
  const handleChange = (val, key, id) => {
    let _dataSource = JSON.parse(JSON.stringify(dataSource));
    let fn = (_list) => {
      for (let d of _list) {
        if (d[rowKey] === id) {
          d[key] = val;
          break;
        }
        if (d.children && d.children.length) {
          fn(d.children);
        }
      }
    };
    fn(_dataSource || []);
    _onChange(_dataSource);
  };
  const handleBatchEditChange = (val, key) => {
    let _dataSource = JSON.parse(JSON.stringify(dataSource));
    let fn = (_list) => {
      for (let d of _list) {
        if (selectList.includes(d[rowKey]) && !(d.disabledList || []).includes(key)) {
          d[key] = val;
        }
        if (d.children && d.children.length) {
          fn(d.children);
        }
      }
    };
    fn(_dataSource || []);
    _onChange(_dataSource);
  };
  const handleRemove = (ids) => {
    let _dataSource = JSON.parse(JSON.stringify(dataSource));
    if (_dataSource.some((d) => ids.includes(d[rowKey]))) {
      _dataSource = _dataSource.filter((d) => !ids.includes(d[rowKey]));
    } else {
      _dataSource.forEach((d) => {
        if (d.children) {
          d.children = d.children.filter((d2) => !ids.includes(d2[rowKey]));
        }
      });
    }
    _onChange(_dataSource);
  };
  const setDebounceValue = (0, import_ahooks.useDebounceFn)(
    (_dataSource) => {
      _onChange(_dataSource);
    },
    {
      wait: 300
    }
  );
  const renderPopoverContent = (0, import_react.useCallback)(
    (_item) => {
      const Com = import_fields.default[_item.type];
      let val;
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "batch-popover-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "editor-item" }, /* @__PURE__ */ import_react.default.createElement(
        Com,
        {
          symbol,
          onBlur: () => {
            if (val !== void 0) {
              handleBatchEditChange(val, _item.dataIndex);
            }
          },
          onChange: (e) => {
            val = e;
          }
        }
      )));
    },
    [dataSource, selectList]
  );
  const renderColumnTitle = (0, import_react.useCallback)(
    (item) => {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "column-title" }, /* @__PURE__ */ import_react.default.createElement("span", null, item.title), selectList.length && item.batchEdit ? /* @__PURE__ */ import_react.default.createElement(
        import_antd.Popover,
        {
          destroyTooltipOnHide: true,
          trigger: ["click"],
          placement: "bottom",
          title: `${(0, import_locales.getText)("batch-editor-batch-edit")}: ${item.title}`,
          content: renderPopoverContent(item)
        },
        /* @__PURE__ */ import_react.default.createElement("a", { style: { marginLeft: 4 } }, (0, import_locales.getText)("batch-editor-batch-edit"))
      ) : null);
    },
    [dataSource, rowKey, selectList]
  );
  const _columns = (0, import_react.useMemo)(() => {
    return columns.filter((d) => !d.hide).map((d) => {
      return {
        ...d,
        titleStr: d.title,
        title: renderColumnTitle(d),
        render: renderColumnItem(d)
      };
    }).concat([
      {
        title: (0, import_locales.getText)("batch-editor-actions"),
        dataIndex: rowKey,
        key: "actions",
        align: "center",
        fixed: "right",
        width: 100,
        dataSource,
        selectList,
        render: (text, record) => {
          return /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              onClick: () => {
                handleRemove([text]);
              }
            },
            (0, import_locales.getText)("batch-editor-remove")
          ));
        }
      }
    ]);
  }, [renderColumnItem, rowKey, dataSource, selectList]);
  const selectOptions = (0, import_react.useMemo)(() => {
    return _columns.filter((d) => d.batchEdit).map((d) => {
      return {
        label: d.titleStr,
        value: d.dataIndex
      };
    });
  }, [_columns]);
  const onFinish = (values) => {
    handleBatchEditChange(values.value, values.key);
    onCancel();
    setSelectList([]);
  };
  const onCancel = () => {
    form.resetFields();
    setOpenModal(false);
  };
  const onOpenMOdal = () => {
    setOpenModal(true);
    form.setFieldsValue({
      key: selectOptions[0].value
    });
  };
  const modalTitle = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    let str = "";
    let selectItems = [];
    selectList.forEach((item) => {
      let productItem = dataSource.find((d) => d[rowKey] === item);
      if (productItem) {
        selectItems.push(productItem);
      } else {
        dataSource.forEach((d) => {
          if (d.children) {
            let childProductItem = d.children.find(
              (t) => t[rowKey] === item
            );
            if (childProductItem) {
              selectItems.push(childProductItem);
            }
          }
        });
      }
    });
    str = ``;
    if (selectItems.length > 1) {
      str = (0, import_locales.getText)("batch-editor-quick-edit-title")(
        (_a2 = selectItems[0]) == null ? void 0 : _a2.title,
        selectItems.length
      );
    } else {
      str = (0, import_locales.getText)("batch-editor-quick-edit-title-2")((_b2 = selectItems[0]) == null ? void 0 : _b2.title);
    }
    return str;
  }, [selectList, dataSource]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_table.default,
    {
      actionButtons: !!selectList.length && [
        {
          title: (0, import_locales.getText)("batch-editor-batch-remove"),
          size: "large",
          onClick: () => {
            handleRemove(selectList);
            setSelectList([]);
          }
        },
        {
          title: (0, import_locales.getText)("batch-editor-batch-edit"),
          onClick: onOpenMOdal,
          size: "large",
          type: "primary"
        }
      ],
      bordered: true,
      dataSource,
      columns: _columns,
      className: "batch-editor-table",
      rowKey,
      rowSelection: {
        type: "checkbox",
        selectedRowKeys: selectList,
        onChange: (keys) => {
          setSelectList(keys);
        }
      },
      scroll: { autoCalc: true },
      pagination: {
        localPagination: true,
        showSizeChanger: true,
        size: "default"
      },
      ...otherTableProps,
      onValuesChange: (values) => {
        var _a2;
        setSelectList([]);
        (_a2 = otherTableProps == null ? void 0 : otherTableProps.onValuesChange) == null ? void 0 : _a2.call(otherTableProps, values);
      },
      filter: {
        show: true,
        sortButtonShow: false,
        quickFilterMaxLength: 3,
        storageMode: "localStorage",
        ...(otherTableProps == null ? void 0 : otherTableProps.filter) || {},
        list: [
          {
            type: "search",
            name: "keywords",
            key: "keywords",
            localFilter: true,
            other: {
              trigger: ["onChange"],
              allowClear: true,
              size: "large",
              placeholder: (0, import_locales.getText)("batch-editor-search"),
              onChange: () => {
                setSelectList([]);
              }
            }
          },
          ...((_e = otherTableProps == null ? void 0 : otherTableProps.filter) == null ? void 0 : _e.list) || []
        ]
      }
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Modal,
    {
      title: (0, import_locales.getText)("batch-editor-quick-edit"),
      open: openModal,
      footer: null,
      onCancel: () => {
        setOpenModal(false);
      }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "title", style: { marginBottom: 20 } }, modalTitle),
    /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { layout: "vertical", form, onFinish }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: (0, import_locales.getText)("batch-editor-what-price"), name: "key" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Select, { size: "large", options: selectOptions })), /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: (0, import_locales.getText)("batch-editor-price"), name: "value" }, /* @__PURE__ */ import_react.default.createElement(import_Price.default, { symbol }))),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "", style: { display: "flex", gap: 20, width: "100%" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { size: "large", style: { flex: 1 }, onClick: onCancel }, (0, import_locales.getText)("batch-editor-cancel")), /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        size: "large",
        type: "primary",
        onClick: () => {
          form.submit();
        },
        style: { flex: 1 }
      },
      (0, import_locales.getText)("batch-editor-confirm")
    ))
  ));
};
var batch_editor_default = BatchEditor;
