"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _PublicService = _interopRequireDefault(require("../../_mapUtil/PublicService"));
var _button = _interopRequireDefault(require("antd/lib/button"));
var _popconfirm = _interopRequireDefault(require("antd/lib/popconfirm"));
var _table = _interopRequireDefault(require("antd/lib/table"));
var _divider = _interopRequireDefault(require("antd/lib/divider"));
var _vtxInput = _interopRequireDefault(require("@vtx/components/lib/vtx-input"));
var _react = _interopRequireWildcard(require("react"));
var _FormItem = require("../FormItem");
var _index = _interopRequireDefault(require("./index.less"));
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
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 _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 _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; }
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); }
// let timer = null;
// function debounce(fn, delay) {
//   timer && clearTimeout(timer);
//   timer = setTimeout(() => {
//     fn()
//   }, delay)
// }

var FORM = {
  input: _FormItem.useRenderInput,
  // 输入框
  number: _FormItem.useRenderNumber,
  // 数值
  textArea: function textArea(_ref) {
    var itemProps = _ref.itemProps;
    return /*#__PURE__*/_react["default"].createElement(_vtxInput["default"].TextArea, _extends({
      placeholder: "\u8BF7\u8F93\u5165"
    }, itemProps));
  },
  radio: _FormItem.useRenderRadio,
  // 单选
  checkbox: _FormItem.useRenderCheckBox,
  // 多选
  rate: _FormItem.useRenderRate,
  // 打分
  "switch": _FormItem.useRenderSwitch,
  // 开关
  slider: _FormItem.useRenderSlider,
  // 开关
  timePicker: _FormItem.useRenderTime,
  // 时间选择器

  rangePicker: _FormItem.useRenderRangePicker,
  // 时间段选择器
  datePicker: _FormItem.useRenderDatePicker,
  // 日期选择器
  weekPicker: _FormItem.useRenderWeekPicker,
  // 星期选择器
  monthPicker: _FormItem.useRenderMonthPicker,
  // 月选择器
  quarterPicker: _FormItem.useRenderQuarterPicker,
  // 月选择器
  yearPicker: _FormItem.useRenderYearPicker,
  // 年选择器
  select: _FormItem.useRenderSelect,
  // 下拉选
  treeSelect: _FormItem.useRenderTreeSelect,
  // 树下拉
  cascade: _FormItem.useRenderCascade // 级联下拉
};
var MyEditable = /*#__PURE__*/(0, _react.forwardRef)(function (props, ref) {
  var _props$columns = props.columns,
    columns = _props$columns === void 0 ? [] : _props$columns,
    _props$btnTitle = props.btnTitle,
    btnTitle = _props$btnTitle === void 0 ? '' : _props$btnTitle,
    onChange = props.onChange,
    disabled = props.disabled,
    _props$tableData = props.tableData,
    tableData = _props$tableData === void 0 ? [] : _props$tableData,
    hideOperation = props.hideOperation,
    hideAddBtn = props.hideAddBtn,
    _props$title = props.title,
    _title = _props$title === void 0 ? '' : _props$title,
    showSerialNum = props.showSerialNum,
    _props$showAddType = props.showAddType,
    showAddType = _props$showAddType === void 0 ? false : _props$showAddType,
    _props$maxLength = props.maxLength,
    maxLength = _props$maxLength === void 0 ? 100 : _props$maxLength,
    getCurrentData = props.getCurrentData,
    onRow = props.onRow,
    scroll = props.scroll,
    loading = props.loading,
    _props$isNeedExternal = props.isNeedExternalRender,
    isNeedExternalRender = _props$isNeedExternal === void 0 ? false : _props$isNeedExternal,
    onCopy = props.onCopy,
    onDelete = props.onDelete,
    onDeleteData = props.onDeleteData,
    cockpit = props.cockpit,
    _props$tableDataChang = props.tableDataChange,
    tableDataChange = _props$tableDataChang === void 0 ? null : _props$tableDataChang,
    handleDisabled = props.handleDisabled,
    _props$showEmpty = props.showEmpty,
    showEmpty = _props$showEmpty === void 0 ? false : _props$showEmpty;
  var _useState = (0, _react.useState)([]),
    _useState2 = _slicedToArray(_useState, 2),
    dataSource = _useState2[0],
    setDataSource = _useState2[1];
  var _useState3 = (0, _react.useState)([]),
    _useState4 = _slicedToArray(_useState3, 2),
    delData = _useState4[0],
    setDelData = _useState4[1];
  (0, _react.useEffect)(function () {
    if (showSerialNum) {
      tableData = _PublicService["default"].transformArrayData({
        data: tableData,
        needColNum: true
      });
    }
    setDataSource(tableData);
  }, [tableData]);

  // 提供获取数据的方法
  function _getData() {
    return _toConsumableArray(dataSource);
  }

  // 提供获取被删除数据的方法
  function _getDelData() {
    return _toConsumableArray(delData);
  }
  (0, _react.useImperativeHandle)(ref, function () {
    return {
      getData: function getData() {
        return _getData();
      },
      getDelData: function getDelData() {
        return _getDelData();
      }
    };
  });
  function handleDelete(key) {
    var _delData = JSON.parse(JSON.stringify(delData));
    var newData = dataSource.filter(function (item) {
      return item.key !== key;
    });
    var listData = dataSource.filter(function (item) {
      return item.key === key;
    });
    if (newData !== null && newData !== void 0 && newData.length) {
      newData.map(function (item, index) {
        item.num = index + 1;
      });
    }
    if (listData && listData.length) {
      _delData.push(listData[0]);
    }
    if (onDeleteData) {
      // 操作删除的数据
      var isDelete = onDeleteData(listData === null || listData === void 0 ? void 0 : listData[0]);
      if (!isDelete) return;
    }
    if (onDelete) {
      // 操作删除后的数据
      return onDelete(newData);
    }
    tableDataChange && tableDataChange(newData);
    setTableData(newData);
    setDelData(_delData);
  }

  // 查看时数据回显
  function setDisabledValue(col, record) {
    var dataIndex = col.dataIndex,
      formType = col.formType,
      valueIndex = col.valueIndex,
      _col$isShowDataIndex = col.isShowDataIndex,
      isShowDataIndex = _col$isShowDataIndex === void 0 ? false : _col$isShowDataIndex;
    var value = record[dataIndex];
    switch (formType) {
      case 'select':
        value = isShowDataIndex ? value : valueIndex === 'duty' || isShowDataIndex ? {
          '1': '组长',
          '2': '组员'
        }[record[valueIndex]] : record[valueIndex];
        break;
      case 'treeSelect':
        value = isShowDataIndex ? value : record[valueIndex];
        break;
      case 'datePicker':
        value = isShowDataIndex ? value : record[valueIndex];
        break;
      case 'switch':
        value = record[dataIndex] ? '是' : '否';
        break;
      default:
        break;
    }
    return value;
  }
  var initColumns = function initColumns() {
    var propsColumns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    propsColumns.map(function (col) {
      if (col.formType) {
        if (!disabled) {
          if (col.required && !col.transTitle) {
            col.title = /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement("span", {
              style: {
                color: '#f00'
              }
            }, "*"), col.title);
            col.transTitle = true;
          }
          col.render = function (text, record, index) {
            var value = setItem(col, record);
            if (!record.disabled) {
              col.itemProps = _objectSpread(_objectSpread(_objectSpread({
                disabled: false
              }, col.itemProps), value), {}, {
                addonafter: record[col.addonafter],
                onChange: function onChange(val, label) {
                  col.onChange && col.onChange(val);
                  onChangeData({
                    record: record,
                    formType: col.formType,
                    dataIndex: col.dataIndex,
                    val: val,
                    label: label,
                    index: index
                  });
                }
              });
              handleDisabled && handleDisabled(col, record); // 是否更改可填写状态
              if (record.isDynamic && record.dynamicOptions && col.valueIndex === record.dynamicFields) {
                var optionData = record.dynamicOptions.filter(function (r) {
                  return r["".concat(record.relationFields)] === record["".concat(record.relationFields)];
                });
                col.itemProps.options = optionData && optionData.length && optionData[0].options || [];
              }
              var newCol = col;
              if (newCol.callbackModalData) {
                newCol = newCol.callbackModalData(newCol, record);
              }
              return FORM[newCol.formType](newCol);
            } else {
              return setDisabledValue(col, record);
            }
          };
        } else if (!isNeedExternalRender) {
          // isNeedExternalRender是否需要外部渲染
          col.render = function (text, record) {
            return setDisabledValue(col, record);
          };
        }
      }
      return col;
    });
    return propsColumns;
  };
  var defaultColumns = [].concat(_toConsumableArray(showSerialNum ? [{
    title: '序号',
    dataIndex: 'num',
    width: 70
  }] : []), _toConsumableArray(initColumns(columns)), _toConsumableArray(!(disabled || hideOperation) ? [{
    title: '操作',
    dataIndex: 'operation',
    width: 160,
    render: function render(_, record) {
      return dataSource.length >= 1 ? /*#__PURE__*/_react["default"].createElement(_react["default"].Fragment, null, /*#__PURE__*/_react["default"].createElement(_popconfirm["default"], {
        title: "\u662F\u5426\u786E\u8BA4\u5220\u9664?",
        onConfirm: function onConfirm() {
          return handleDelete(record.key);
        }
      }, /*#__PURE__*/_react["default"].createElement("a", null, "\u5220\u9664")), record && record.isCopy && /*#__PURE__*/_react["default"].createElement(_divider["default"], {
        type: "vertical"
      }), record && record.isCopy && /*#__PURE__*/_react["default"].createElement("a", {
        onClick: function onClick() {
          onCopy && onCopy(record);
        }
      }, "\u590D\u5236")) : null;
    }
  }] : []));
  function handleAdd() {
    var newData = {
      key: Date.now()
    };
    if (showSerialNum) {
      newData.num = dataSource.length + 1;
    }
    if (showAddType) {
      newData.TYPE = 'add';
    }
    var result = [].concat(_toConsumableArray(dataSource), [newData]);
    tableDataChange && tableDataChange(result);
    setTableData(result);
  }
  function handleSave(row) {
    var newData = _toConsumableArray(dataSource);
    var index = newData.findIndex(function (item) {
      return row.key === item.key;
    });
    var item = newData[index];
    newData.splice(index, 1, _objectSpread(_objectSpread({}, item), row));
    setTableData(newData);
  }

  // 提供获取当前表格数据入口
  function setTableData(data) {
    getCurrentData && getCurrentData(data);
    setDataSource(data);
  }
  function onChangeData(_ref2) {
    var record = _ref2.record,
      formType = _ref2.formType,
      dataIndex = _ref2.dataIndex,
      val = _ref2.val,
      label = _ref2.label,
      index = _ref2.index;
    var value = val;
    if (formType === 'input' || formType === 'textArea' || formType === 'radio') {
      value = value.target.value;
    }
    onChange && onChange({
      record: record,
      dataIndex: dataIndex,
      val: value,
      label: label,
      index: index
    });
    record[dataIndex] = value;
    handleSave(record);
  }

  // 数据回显
  function setItem(col, record) {
    var dataIndex = col.dataIndex,
      formType = col.formType;
    var itemData = {};
    if (formType) {
      switch (formType) {
        case 'switch':
          itemData = {
            checked: record[dataIndex] || false
          };
          break;
        case 'treeSelect':
          itemData = {
            value: record[dataIndex] || []
          };
          break;
        default:
          itemData = {
            value: !['null', 'undefined'].includes(String(record[dataIndex])) ? record[dataIndex] : null
          };
          break;
      }
    }
    return itemData;
  }
  return /*#__PURE__*/_react["default"].createElement("div", {
    className: "".concat(_index["default"].editable, " ").concat(showEmpty && _index["default"].showEmpty, " ").concat(cockpit && _index["default"].cockpitEditable),
    ref: ref
  }, /*#__PURE__*/_react["default"].createElement(_table["default"], {
    title: function title() {
      return _title;
    },
    rowClassName: function rowClassName() {
      return 'editable-row';
    },
    bordered: true,
    dataSource: dataSource,
    pagination: false,
    columns: defaultColumns,
    onRow: onRow,
    scroll: scroll,
    loading: loading,
    rowKey: function rowKey(record) {
      return record.key;
    }
  }), !disabled && !(dataSource.length >= maxLength) && !hideAddBtn && /*#__PURE__*/_react["default"].createElement(_button["default"], {
    onClick: handleAdd,
    style: {
      marginBottom: 16
    }
  }, btnTitle));
});
var _default = exports["default"] = MyEditable;
//# sourceMappingURL=index.js.map
