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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useMemo, useState, useCallback } from "react";
import { Popover, Tooltip, Button, Modal, Form, Select } from "antd";
import { useDebounceFn } from "ahooks";
import Table from "../table";
import fields from "./fields";
import Price from "./fields/Price";
import useEngineContext from "../../hooks/useEngineContext";
import { getText } from "../../locales/index";
import "./index.less";
var BatchEditor = function BatchEditor(props) {
  var _context$appHelper, _store$getState, _otherTableProps$filt;
  var columns = props.columns,
    _props$dataSource = props.dataSource,
    dataSource = _props$dataSource === void 0 ? [] : _props$dataSource,
    onChange = props.onChange,
    rowKey = props.rowKey,
    otherTableProps = props.otherTableProps;
  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    form = _Form$useForm2[0];
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    openModal = _useState2[0],
    setOpenModal = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    selectList = _useState4[0],
    setSelectList = _useState4[1];
  var context = useEngineContext();
  var _ref = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    store = _ref.store;
  var symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || "$";

  /**
   * @title: 渲染column
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-06-17 13:21
   */
  var renderColumnItem = useCallback(function (_item) {
    return function (text, record) {
      // 没有type 按文本渲染
      if (!_item.type) {
        var _Com = fields["text"];
        return /*#__PURE__*/React.createElement("div", {
          className: "editor-item"
        }, /*#__PURE__*/React.createElement(_Com, null, text));
      }

      // 如果当前record单独禁止编辑某些字段
      if ((record.disabledList || []).includes(_item.dataIndex)) {
        return /*#__PURE__*/React.createElement("div", {
          className: "editor-item",
          style: {
            padding: "0 11px"
          }
        }, /*#__PURE__*/React.createElement(Tooltip, {
          overlay: record !== null && record !== void 0 && record.disabledTexts ?
          //@ts-ignore
          (record === null || record === void 0 ? void 0 : record.disabledTexts[_item.dataIndex]) || text : text
        }, /*#__PURE__*/React.createElement("div", {
          className: "name"
        }, record !== null && record !== void 0 && record.disabledTexts ?
        //@ts-ignore
        (record === null || record === void 0 ? void 0 : record.disabledTexts[_item.dataIndex]) || text : text)));
      }
      var Com = fields[_item.type];
      if (Com) {
        return /*#__PURE__*/React.createElement("div", {
          className: "editor-item"
        }, /*#__PURE__*/React.createElement(Com, _extends({
          status: record.status,
          value: text
          // 为了应对每个字段需要设置不同的 placeholder
        }, _item.componentProps, {
          placeholder: _item.placeholder || record[_item.dataIndex + "placeholder"],
          symbol: symbol,
          onChange: function onChange(e) {
            handleChange(e, _item.dataIndex, record[rowKey]);
          }
        })));
      }
      return /*#__PURE__*/React.createElement("div", {
        className: "editor-item"
      }, "-");
    };
  }, [dataSource, rowKey, columns]);

  /**
   * dataSource 的返回事件
   * @param newDataSource
   */
  var _onChange = function _onChange(newDataSource) {
    onChange === null || onChange === void 0 || onChange(newDataSource);
  };

  /**
   * @title: 编辑某个字段
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-06-17 13:22
   */
  var handleChange = function handleChange(val, key, id) {
    var _dataSource = JSON.parse(JSON.stringify(dataSource));
    var fn = function fn(_list) {
      var _iterator = _createForOfIteratorHelper(_list),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var d = _step.value;
          if (d[rowKey] === id) {
            d[key] = val;
            break;
          }
          if (d.children && d.children.length) {
            fn(d.children);
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
    };
    fn(_dataSource || []);
    _onChange(_dataSource);
  };

  /**
   * @title: 批量编辑
   * @description:
   * @param {any} val
   * @param {any} key
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-06-17 13:22
   */
  var handleBatchEditChange = function handleBatchEditChange(val, key) {
    var _dataSource = JSON.parse(JSON.stringify(dataSource));
    var fn = function fn(_list) {
      var _iterator2 = _createForOfIteratorHelper(_list),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var d = _step2.value;
          if (selectList.includes(d[rowKey]) && !(d.disabledList || []).includes(key)) {
            d[key] = val;
          }
          if (d.children && d.children.length) {
            fn(d.children);
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    };
    fn(_dataSource || []);
    _onChange(_dataSource);
  };

  /**
   * @title: 删除record
   * @description:
   * @param {any} ids
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-06-17 13:22
   */
  var handleRemove = function handleRemove(ids) {
    var _dataSource = JSON.parse(JSON.stringify(dataSource));
    if (_dataSource.some(function (d) {
      return ids.includes(d[rowKey]);
    })) {
      _dataSource = _dataSource.filter(function (d) {
        return !ids.includes(d[rowKey]);
      });
    } else {
      _dataSource.forEach(function (d) {
        if (d.children) {
          d.children = d.children.filter(function (d) {
            return !ids.includes(d[rowKey]);
          });
        }
      });
    }
    _onChange(_dataSource);
  };
  var setDebounceValue = useDebounceFn(function (_dataSource) {
    _onChange(_dataSource);
  }, {
    wait: 300
  });

  // 渲染弹窗内容
  var renderPopoverContent = useCallback(function (_item) {
    var Com = fields[_item.type];
    var val;
    return /*#__PURE__*/React.createElement("div", {
      className: "batch-popover-content"
    }, /*#__PURE__*/React.createElement("div", {
      className: "editor-item"
    }, /*#__PURE__*/React.createElement(Com, {
      symbol: symbol,
      onBlur: function onBlur() {
        if (val !== undefined) {
          handleBatchEditChange(val, _item.dataIndex);
        }
      },
      onChange: function onChange(e) {
        val = e;
      }
    })));
  }, [dataSource, selectList]);

  /**
   * @title: 渲染表格列标题
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-06-17 13:23
   */
  var renderColumnTitle = useCallback(function (item) {
    return /*#__PURE__*/React.createElement("div", {
      className: "column-title"
    }, /*#__PURE__*/React.createElement("span", null, item.title), selectList.length && item.batchEdit ? /*#__PURE__*/React.createElement(Popover, {
      destroyTooltipOnHide: true,
      trigger: ["click"],
      placement: "bottom",
      title: "".concat(getText("batch-editor-batch-edit"), ": ").concat(item.title),
      content: renderPopoverContent(item)
    }, /*#__PURE__*/React.createElement("a", {
      style: {
        marginLeft: 4
      }
    }, getText("batch-editor-batch-edit"))) : null);
  }, [dataSource, rowKey, selectList]);

  /**
   * @title: 表格列
   * @description:
   * @param {*} useMemo
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-06-17 13:23
   */
  var _columns = useMemo(function () {
    return columns.filter(function (d) {
      return !d.hide;
    }).map(function (d) {
      return _objectSpread(_objectSpread({}, d), {}, {
        titleStr: d.title,
        title: renderColumnTitle(d),
        render: renderColumnItem(d)
      });
    }).concat([{
      title: getText("batch-editor-actions"),
      dataIndex: rowKey,
      key: "actions",
      align: "center",
      fixed: "right",
      width: 100,
      dataSource: dataSource,
      selectList: selectList,
      render: function render(text, record) {
        return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement(Button, {
          onClick: function onClick() {
            handleRemove([text]);
          }
        }, getText("batch-editor-remove")));
      }
    }]);
  }, [renderColumnItem, rowKey, dataSource, selectList]);
  var selectOptions = useMemo(function () {
    return _columns.filter(function (d) {
      return d.batchEdit;
    }).map(function (d) {
      return {
        label: d.titleStr,
        value: d.dataIndex
      };
    });
  }, [_columns]);
  var onFinish = function onFinish(values) {
    handleBatchEditChange(values.value, values.key);
    onCancel();
    setSelectList([]);
  };
  var onCancel = function onCancel() {
    form.resetFields();
    setOpenModal(false);
  };
  var onOpenMOdal = function onOpenMOdal() {
    setOpenModal(true);
    form.setFieldsValue({
      key: selectOptions[0].value
    });
  };
  var modalTitle = useMemo(function () {
    var str = "";
    var selectItems = [];
    selectList.forEach(function (item) {
      var productItem = dataSource.find(function (d) {
        return d[rowKey] === item;
      });
      if (productItem) {
        selectItems.push(productItem);
      } else {
        dataSource.forEach(function (d) {
          if (d.children) {
            var childProductItem = d.children.find(function (t) {
              return t[rowKey] === item;
            });
            if (childProductItem) {
              selectItems.push(childProductItem);
            }
          }
        });
      }
    });
    str = "";
    if (selectItems.length > 1) {
      var _selectItems$;
      str = getText("batch-editor-quick-edit-title")((_selectItems$ = selectItems[0]) === null || _selectItems$ === void 0 ? void 0 : _selectItems$.title, selectItems.length);
    } else {
      var _selectItems$2;
      str = getText("batch-editor-quick-edit-title-2")((_selectItems$2 = selectItems[0]) === null || _selectItems$2 === void 0 ? void 0 : _selectItems$2.title);
    }
    return str;
  }, [selectList, dataSource]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Table, _extends({
    actionButtons: !!selectList.length && [{
      title: getText("batch-editor-batch-remove"),
      size: "large",
      onClick: function onClick() {
        handleRemove(selectList);
        setSelectList([]);
      }
    }, {
      title: getText("batch-editor-batch-edit"),
      onClick: onOpenMOdal,
      size: "large",
      type: "primary"
    }],
    bordered: true,
    dataSource: dataSource,
    columns: _columns,
    className: "batch-editor-table",
    rowKey: rowKey,
    rowSelection: {
      type: "checkbox",
      selectedRowKeys: selectList,
      onChange: function onChange(keys) {
        setSelectList(keys);
      }
    },
    scroll: {
      autoCalc: true
    },
    pagination: {
      localPagination: true,
      showSizeChanger: true,
      size: "default"
    }
  }, otherTableProps, {
    onValuesChange: function onValuesChange(values) {
      var _otherTableProps$onVa;
      setSelectList([]);
      otherTableProps === null || otherTableProps === void 0 || (_otherTableProps$onVa = otherTableProps.onValuesChange) === null || _otherTableProps$onVa === void 0 || _otherTableProps$onVa.call(otherTableProps, values);
    },
    filter: _objectSpread(_objectSpread({
      show: true,
      sortButtonShow: false,
      quickFilterMaxLength: 3,
      storageMode: "localStorage"
    }, (otherTableProps === null || otherTableProps === void 0 ? void 0 : otherTableProps.filter) || {}), {}, {
      list: [{
        type: "search",
        name: "keywords",
        key: "keywords",
        localFilter: true,
        other: {
          trigger: ["onChange"],
          allowClear: true,
          size: "large",
          placeholder: getText("batch-editor-search"),
          onChange: function onChange() {
            setSelectList([]);
          }
        }
      }].concat(_toConsumableArray((otherTableProps === null || otherTableProps === void 0 || (_otherTableProps$filt = otherTableProps.filter) === null || _otherTableProps$filt === void 0 ? void 0 : _otherTableProps$filt.list) || []))
    })
  })), /*#__PURE__*/React.createElement(Modal, {
    title: getText("batch-editor-quick-edit"),
    open: openModal,
    footer: null,
    onCancel: function onCancel() {
      setOpenModal(false);
    }
  }, /*#__PURE__*/React.createElement("div", {
    className: "title",
    style: {
      marginBottom: 20
    }
  }, modalTitle), /*#__PURE__*/React.createElement(Form, {
    layout: "vertical",
    form: form,
    onFinish: onFinish
  }, /*#__PURE__*/React.createElement(Form.Item, {
    label: getText("batch-editor-what-price"),
    name: "key"
  }, /*#__PURE__*/React.createElement(Select, {
    size: "large",
    options: selectOptions
  })), /*#__PURE__*/React.createElement(Form.Item, {
    label: getText("batch-editor-price"),
    name: "value"
  }, /*#__PURE__*/React.createElement(Price, {
    symbol: symbol
  }))), /*#__PURE__*/React.createElement("div", {
    className: "",
    style: {
      display: "flex",
      gap: 20,
      width: "100%"
    }
  }, /*#__PURE__*/React.createElement(Button, {
    size: "large",
    style: {
      flex: 1
    },
    onClick: onCancel
  }, getText("batch-editor-cancel")), /*#__PURE__*/React.createElement(Button, {
    size: "large",
    type: "primary",
    onClick: function onClick() {
      form.submit();
    },
    style: {
      flex: 1
    }
  }, getText("batch-editor-confirm")))));
};
export default BatchEditor;