/**
 * tdesign v0.46.4
 * (c) 2022 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var helper = require('../_chunks/dep-d7a1e02c.js');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var _typeof = require('@babel/runtime/helpers/typeof');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var VueCompositionAPI = require('@vue/composition-api');
var get = require('lodash/get');
var lodashSet = require('lodash/set');
var isFunction = require('lodash/isFunction');
var tdesignIconsVue = require('tdesign-icons-vue');
var hooks_useGlobalIcon = require('../hooks/useGlobalIcon.js');
var table_tr = require('./tr.js');
var form_formModel = require('../form/form-model.js');
var _common_js_log_log = require('../_common/js/log/log.js');
require('../config-provider/useConfig.js');
require('../config-provider/context.js');
require('lodash/merge');
require('lodash/mergeWith');
require('../_common/js/global-config/default-config.js');
require('../_common/js/global-config/locale/zh_CN.js');
require('lodash/upperFirst');
require('lodash/isString');
require('lodash/pick');
require('./utils.js');
require('lodash/isObject');
require('./hooks/useFixed.js');
require('lodash/debounce');
require('../_common/js/utils/getScrollbarWidth.js');
require('../_common/js/utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('../utils/dom.js');
require('vue');
require('raf');
require('../utils/easing.js');
require('./hooks/useClassName.js');
require('./ellipsis.js');
require('../utils/render-tnode.js');
require('lodash/camelCase');
require('lodash/kebabCase');
require('../tooltip/index.js');
require('../tooltip/tooltip.js');
require('../tooltip/props.js');
require('../popup/props.js');
require('../popup/popup.js');
require('@popperjs/core');
require('../utils/helper.js');
require('../_common/js/utils/set-style.js');
require('../popup/container.js');
require('../config-provider/config-receiver.js');
require('../utils/mixins.js');
require('../utils/map-props.js');
require('../utils/withInstall.js');
require('lodash/capitalize');
require('./base-table-props.js');
require('./hooks/useRowspanAndColspan.js');
require('../hooks/useLazyLoad.js');
require('../_common/js/utils/observe.js');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/regenerator');
require('../_chunks/dep-f8992a6f.js');
require('lodash/isEmpty');
require('lodash/isNumber');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var _slicedToArray__default = /*#__PURE__*/_interopDefaultLegacy(_slicedToArray);
var _toConsumableArray__default = /*#__PURE__*/_interopDefaultLegacy(_toConsumableArray);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
var lodashSet__default = /*#__PURE__*/_interopDefaultLegacy(lodashSet);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty__default["default"](target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
var EditableCell = VueCompositionAPI.defineComponent({
  name: "TableEditableCell",
  props: {
    row: Object,
    rowIndex: Number,
    col: Object,
    colIndex: Number,
    oldCell: [Function, String],
    tableBaseClass: Object,
    cellEmptyContent: [Function, String],
    editable: {
      type: Boolean,
      "default": void 0
    },
    readonly: {
      type: Boolean
    },
    errors: {
      type: Array,
      "default": void 0
    },
    onChange: Function,
    onValidate: Function,
    onRuleChange: Function
  },
  setup: function setup(props, context) {
    var _props$col$edit;

    var _toRefs = VueCompositionAPI.toRefs(props),
        row = _toRefs.row,
        col = _toRefs.col;

    var tableEditableCellRef = VueCompositionAPI.ref(null);
    var isEdit = VueCompositionAPI.ref(((_props$col$edit = props.col.edit) === null || _props$col$edit === void 0 ? void 0 : _props$col$edit.defaultEditable) || false);
    var editValue = VueCompositionAPI.ref();
    var errorList = VueCompositionAPI.ref();

    var _useGlobalIcon = hooks_useGlobalIcon.useGlobalIcon({
      Edit1Icon: tdesignIconsVue.Edit1Icon
    }),
        Edit1Icon = _useGlobalIcon.Edit1Icon;

    var currentRow = VueCompositionAPI.computed(function () {
      var newRow = _objectSpread({}, row.value);

      col.value && lodashSet__default["default"](newRow, col.value.colKey, editValue.value);
      return newRow;
    });
    var cellNode = VueCompositionAPI.computed(function () {
      var node = table_tr.renderCell({
        row: currentRow.value,
        col: _objectSpread(_objectSpread({}, col.value), {}, {
          cell: props.oldCell
        }),
        rowIndex: props.rowIndex,
        colIndex: props.colIndex
      }, context.slots, {
        cellEmptyContent: props.cellEmptyContent
      });
      return node;
    });
    var componentProps = VueCompositionAPI.computed(function () {
      var _edit$abortEditOnEven;

      var edit = col.value.edit;
      if (!edit) return {};
      var editProps = isFunction__default["default"](edit.props) ? edit.props({
        col: col.value,
        row: row.value,
        rowIndex: props.rowIndex,
        colIndex: props.colIndex,
        editedRow: currentRow.value
      }) : _objectSpread({}, edit.props);
      delete editProps.onChange;
      delete editProps.value;
      (_edit$abortEditOnEven = edit.abortEditOnEvent) === null || _edit$abortEditOnEven === void 0 ? void 0 : _edit$abortEditOnEven.forEach(function (item) {
        delete editProps[item];
      });
      return editProps;
    });
    var isAbortEditOnChange = VueCompositionAPI.computed(function () {
      var _edit$abortEditOnEven2;

      var edit = col.value.edit;
      if (!edit) return false;
      return Boolean((_edit$abortEditOnEven2 = edit.abortEditOnEvent) === null || _edit$abortEditOnEven2 === void 0 ? void 0 : _edit$abortEditOnEven2.includes("onChange"));
    });

    var validateEdit = function validateEdit(trigger) {
      return new Promise(function (resolve) {
        var cellParams = {
          col: props.col,
          row: props.row,
          colIndex: props.colIndex,
          rowIndex: props.rowIndex
        };
        var params = {
          result: [_objectSpread(_objectSpread({}, cellParams), {}, {
            errorList: [],
            value: editValue.value
          })],
          trigger: trigger
        };
        var rules = isFunction__default["default"](col.value.edit.rules) ? col.value.edit.rules(cellParams) : col.value.edit.rules;

        if (!col.value.edit || !rules || !rules.length) {
          var _props$onValidate;

          (_props$onValidate = props.onValidate) === null || _props$onValidate === void 0 ? void 0 : _props$onValidate.call(props, params);
          resolve(true);
          return;
        }

        form_formModel.validate(editValue.value, rules).then(function (result) {
          var _props$onValidate2;

          var list = result === null || result === void 0 ? void 0 : result.filter(function (t) {
            return !t.result;
          });
          params.result[0].errorList = list;
          (_props$onValidate2 = props.onValidate) === null || _props$onValidate2 === void 0 ? void 0 : _props$onValidate2.call(props, params);

          if (!list || !list.length) {
            resolve(true);
          } else {
            errorList.value = list;
            resolve(list);
          }
        });
      });
    };

    var isSame = function isSame(a, b) {
      if (_typeof__default["default"](a) === "object" && _typeof__default["default"](b) === "object") {
        return JSON.stringify(a) === JSON.stringify(b);
      }

      return a === b;
    };

    var updateAndSaveAbort = function updateAndSaveAbort(outsideAbortEvent) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      validateEdit("self").then(function (result) {
        if (result !== true) return;
        var oldValue = get__default["default"](row.value, col.value.colKey);

        if (!isSame(editValue.value, oldValue)) {
          editValue.value = oldValue;
          outsideAbortEvent === null || outsideAbortEvent === void 0 ? void 0 : outsideAbortEvent.apply(void 0, args);
        }

        var timer = setTimeout(function () {
          isEdit.value = false;
          clearTimeout(timer);
        }, 0);
      });
    };

    var listeners = VueCompositionAPI.computed(function () {
      var _edit$abortEditOnEven3;

      var edit = col.value.edit;
      var isCellEditable = props.editable === void 0;
      if (!isEdit.value || !isCellEditable) return;
      if (!(edit !== null && edit !== void 0 && (_edit$abortEditOnEven3 = edit.abortEditOnEvent) !== null && _edit$abortEditOnEven3 !== void 0 && _edit$abortEditOnEven3.length)) return {};
      var tListeners = {};
      var outsideAbortEvent = edit === null || edit === void 0 ? void 0 : edit.onEdited;
      edit.abortEditOnEvent.forEach(function (itemEvent) {
        if (itemEvent === "onChange") return;
        var eventName = itemEvent.slice(2, 3).toLocaleLowerCase() + itemEvent.slice(3);

        tListeners[eventName] = function () {
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }

          updateAndSaveAbort.apply(void 0, [outsideAbortEvent, {
            trigger: itemEvent,
            newRowData: currentRow.value,
            rowIndex: props.rowIndex
          }].concat(args));
        };
      });
      return tListeners;
    });

    var onEditChange = function onEditChange(val) {
      var _props$onChange, _props$onRuleChange;

      editValue.value = val;
      var params = {
        row: props.row,
        rowIndex: props.rowIndex,
        value: val,
        col: props.col,
        colIndex: props.colIndex,
        editedRow: _objectSpread(_objectSpread({}, props.row), {}, _defineProperty__default["default"]({}, props.col.colKey, val))
      };
      (_props$onChange = props.onChange) === null || _props$onChange === void 0 ? void 0 : _props$onChange.call(props, params);
      (_props$onRuleChange = props.onRuleChange) === null || _props$onRuleChange === void 0 ? void 0 : _props$onRuleChange.call(props, params);
      var isCellEditable = props.editable === void 0;

      if (isCellEditable && isAbortEditOnChange.value) {
        var _col$value$edit;

        var outsideAbortEvent = (_col$value$edit = col.value.edit) === null || _col$value$edit === void 0 ? void 0 : _col$value$edit.onEdited;

        for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
          args[_key3 - 1] = arguments[_key3];
        }

        updateAndSaveAbort.apply(void 0, [outsideAbortEvent, {
          trigger: "onChange",
          newRowData: currentRow.value,
          rowIndex: props.rowIndex
        }].concat(args));
      }
    };

    var documentClickHandler = function documentClickHandler(e) {
      var _e$path, _tableEditableCellRef;

      if (!col.value.edit || !col.value.edit.component) return;
      if (!isEdit.value) return;
      if ((_e$path = e.path) !== null && _e$path !== void 0 && _e$path.includes((_tableEditableCellRef = tableEditableCellRef.value) === null || _tableEditableCellRef === void 0 ? void 0 : _tableEditableCellRef.$el)) return;

      for (var i = 0, len = e.path.length; i < len; i++) {
        var _node$classList, _node$classList$value;

        var node = e.path[i];

        if ((_node$classList = node.classList) !== null && _node$classList !== void 0 && (_node$classList$value = _node$classList.value) !== null && _node$classList$value !== void 0 && _node$classList$value.includes("popup__content")) {
          return;
        }
      }

      var outsideAbortEvent = col.value.edit.onEdited;
      updateAndSaveAbort(outsideAbortEvent, {
        trigger: "document",
        newRowData: currentRow.value,
        rowIndex: props.rowIndex
      });
    };

    var cellValue = VueCompositionAPI.computed(function () {
      return get__default["default"](row.value, col.value.colKey);
    });
    VueCompositionAPI.watch(cellValue, function (cellValue2) {
      var val = cellValue2;

      if (_typeof__default["default"](val) === "object" && val !== null) {
        val = val instanceof Array ? _toConsumableArray__default["default"](val) : _objectSpread({}, val);
      }

      editValue.value = val;
    }, {
      immediate: true
    });
    VueCompositionAPI.watch(isEdit, function (isEdit2) {
      var isCellEditable = props.editable === void 0;
      if (!col.value.edit || !col.value.edit.component || !isCellEditable) return;

      if (isEdit2) {
        document.addEventListener("click", documentClickHandler);
      } else {
        document.removeEventListener("click", documentClickHandler);
      }
    }, {
      immediate: true
    });
    VueCompositionAPI.watch(function () {
      return [props.editable, props.rowIndex, props.colIndex];
    }, function (_ref) {
      var _ref2 = _slicedToArray__default["default"](_ref, 3),
          editable = _ref2[0],
          rowIndex = _ref2[1],
          colIndex = _ref2[2];

      if (editable === false) {
        editValue.value = cellValue.value;
      } else {
        var _props$onRuleChange2;

        (_props$onRuleChange2 = props.onRuleChange) === null || _props$onRuleChange2 === void 0 ? void 0 : _props$onRuleChange2.call(props, {
          col: col.value,
          row: row.value,
          rowIndex: rowIndex,
          colIndex: colIndex,
          value: cellValue.value,
          editedRow: row.value
        });
      }
    }, {
      immediate: true
    });
    VueCompositionAPI.watch(function () {
      return props.errors;
    }, function (errors) {
      errorList.value = errors;
    });
    return {
      editValue: editValue,
      isEdit: isEdit,
      cellNode: cellNode,
      isAbortEditOnChange: isAbortEditOnChange,
      listeners: listeners,
      componentProps: componentProps,
      tableEditableCellRef: tableEditableCellRef,
      errorList: errorList,
      onEditChange: onEditChange,
      Edit1Icon: Edit1Icon
    };
  },
  render: function render() {
    var _this = this,
        _this$col$edit2,
        _this$errorList,
        _this$errorList$,
        _this$tableBaseClass2,
        _this$errorList2,
        _this$errorList2$;

    var h = arguments[0];

    if (this.readonly) {
      return h("div", [this.cellNode]);
    }

    if (this.editable === void 0 && !this.isEdit || this.editable === false) {
      var _this$tableBaseClass, _this$col$edit;

      var Edit1Icon = this.Edit1Icon;
      return h("div", {
        "class": (_this$tableBaseClass = this.tableBaseClass) === null || _this$tableBaseClass === void 0 ? void 0 : _this$tableBaseClass.cellEditable,
        "on": {
          "click": function click(e) {
            _this.isEdit = true;
            e.stopPropagation();
          }
        }
      }, [this.cellNode, ((_this$col$edit = this.col.edit) === null || _this$col$edit === void 0 ? void 0 : _this$col$edit.showEditIcon) !== false && h(Edit1Icon, {
        "attrs": {
          "size": "12px"
        }
      })]);
    }

    var Component = (_this$col$edit2 = this.col.edit) === null || _this$col$edit2 === void 0 ? void 0 : _this$col$edit2.component;

    if (!Component) {
      _common_js_log_log["default"].error("Table", "edit.component is required.");
      return null;
    }

    var errorMessage = (_this$errorList = this.errorList) === null || _this$errorList === void 0 ? void 0 : (_this$errorList$ = _this$errorList[0]) === null || _this$errorList$ === void 0 ? void 0 : _this$errorList$.message;
    return h("div", {
      "class": (_this$tableBaseClass2 = this.tableBaseClass) === null || _this$tableBaseClass2 === void 0 ? void 0 : _this$tableBaseClass2.cellEditWrap,
      "on": {
        "click": function click(e) {
          e.stopPropagation();
        }
      }
    }, [h(Component, helper.helper([{
      "ref": "tableEditableCellRef",
      "attrs": {
        "status": errorMessage ? ((_this$errorList2 = this.errorList) === null || _this$errorList2 === void 0 ? void 0 : (_this$errorList2$ = _this$errorList2[0]) === null || _this$errorList2$ === void 0 ? void 0 : _this$errorList2$.type) || "error" : void 0,
        "tips": errorMessage
      }
    }, {
      "props": this.componentProps
    }, {}, {
      "on": this.listeners
    }, {
      "attrs": {
        "value": this.editValue
      },
      "on": {
        "change": this.onEditChange
      }
    }]))]);
  }
});

exports["default"] = EditableCell;
//# sourceMappingURL=editable-cell.js.map
