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

import { h as helper } from '../_chunks/dep-37d5b9c4.js';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _typeof from '@babel/runtime/helpers/typeof';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { defineComponent, toRefs, ref, computed, watch } from '@vue/composition-api';
import get from 'lodash/get';
import set from 'lodash/set';
import { Edit1Icon } from 'tdesign-icons-vue';
import useClassName from './hooks/useClassName.js';
import { renderCell } from './tr.js';
import { validate } from '../form/form-model.js';
import '../_common/js/log/index.js';
import log from '../_common/js/log/log.js';
import '../config-provider/useConfig.js';
import 'lodash/cloneDeep';
import 'lodash/mergeWith';
import '../config-provider/context.js';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '../config-provider/type.js';
import 'lodash/isFunction';
import 'lodash/upperFirst';
import 'lodash/isString';
import 'lodash/pick';
import './utils.js';
import 'lodash/isObject';
import './hooks/useFixed.js';
import '@babel/runtime/helpers/slicedToArray';
import '../_common/js/utils/getScrollbarWidth.js';
import '../utils/dom.js';
import 'vue';
import 'raf';
import '../utils/easing.js';
import './ellipsis.js';
import 'lodash/debounce';
import '../utils/render-tnode.js';
import '../popup/index.js';
import '../popup/popup.js';
import '@popperjs/core';
import '../config.js';
import '../utils/classnames.js';
import '../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import 'lodash/camelCase';
import '../_common/js/utils/set-style.js';
import '../popup/props.js';
import '../popup/container.js';
import '../utils/map-props.js';
import '../utils/withInstall.js';
import 'lodash/capitalize';
import './style/css.js';
import '../popup/type.js';
import './base-table-props.js';
import './hooks/useLazyLoad.js';
import '../_common/js/utils/observe.js';
import '@babel/runtime/helpers/asyncToGenerator';
import '@babel/runtime/regenerator';
import '../_chunks/dep-8600dc2e.js';
import 'lodash/isEmpty';
import 'lodash/isNumber';

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(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 = defineComponent({
  name: "TableEditableCell",
  props: {
    row: Object,
    rowIndex: Number,
    col: Object,
    colIndex: Number,
    oldCell: [Function, String]
  },
  setup: function setup(props, context) {
    var _toRefs = toRefs(props),
        row = _toRefs.row,
        col = _toRefs.col;

    var _useClassName = useClassName(),
        tableBaseClass = _useClassName.tableBaseClass;

    var tableEditableCellRef = ref(null);
    var isEdit = ref(false);
    var editValue = ref();
    var errorList = ref();
    var currentRow = computed(function () {
      var newRow = _objectSpread({}, row.value);

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

      var edit = col.value.edit;
      if (!edit) return {};

      var editProps = _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 = 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() {
      return new Promise(function (resolve) {
        var _col$value$edit, _col$value$edit2;

        if (!((_col$value$edit = col.value.edit) !== null && _col$value$edit !== void 0 && _col$value$edit.rules)) {
          resolve(true);
          return;
        }

        validate(editValue.value, (_col$value$edit2 = col.value.edit) === null || _col$value$edit2 === void 0 ? void 0 : _col$value$edit2.rules).then(function (result) {
          errorList.value = result === null || result === void 0 ? void 0 : result.filter(function (t) {
            return !t.result;
          });

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

    var isSame = function isSame(a, b) {
      if (_typeof(a) === "object" && _typeof(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().then(function (result) {
        if (result !== true) return;

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

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

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

      var edit = col.value.edit;
      if (!isEdit.value) return;
      if (!(edit !== null && edit !== void 0 && (_edit$abortEditOnEven3 = edit.abortEditOnEvent) !== null && _edit$abortEditOnEven3 !== void 0 && _edit$abortEditOnEven3.length)) return {};
      var tListeners = {};
      edit.abortEditOnEvent.forEach(function (itemEvent) {
        if (itemEvent === "onChange") return;
        var outsideAbortEvent = edit.props[itemEvent];

        tListeners[itemEvent] = 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) {
      editValue.value = val;

      if (isAbortEditOnChange.value) {
        var _col$value$edit3;

        var outsideAbortEvent = (_col$value$edit3 = col.value.edit) === null || _col$value$edit3 === void 0 ? void 0 : _col$value$edit3.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 _tableEditableCellRef, _e$path, _tableEditableCellRef2;

      if (!col.value.edit || !col.value.edit.component) return;
      if (!isEdit.value || !((_tableEditableCellRef = tableEditableCellRef.value) !== null && _tableEditableCellRef !== void 0 && _tableEditableCellRef.$el)) return;
      if ((_e$path = e.path) !== null && _e$path !== void 0 && _e$path.includes((_tableEditableCellRef2 = tableEditableCellRef.value) === null || _tableEditableCellRef2 === void 0 ? void 0 : _tableEditableCellRef2.$el)) return;
      var outsideAbortEvent = col.value.edit.onEdited;
      updateAndSaveAbort(outsideAbortEvent, {
        trigger: "document",
        newRowData: currentRow.value,
        rowIndex: props.rowIndex
      });
    };

    watch(row, function (row2) {
      var val = get(row2, col.value.colKey);

      if (_typeof(val) === "object") {
        val = val instanceof Array ? _toConsumableArray(val) : _objectSpread({}, val);
      }

      editValue.value = val;
    }, {
      immediate: true
    });
    watch(isEdit, function (isEdit2) {
      if (!col.value.edit || !col.value.edit.component) return;

      if (isEdit2) {
        document.addEventListener("click", documentClickHandler);
      } else {
        document.removeEventListener("click", documentClickHandler);
      }
    });
    return {
      editValue: editValue,
      isEdit: isEdit,
      tableBaseClass: tableBaseClass,
      cellNode: cellNode,
      isAbortEditOnChange: isAbortEditOnChange,
      listeners: listeners,
      componentProps: componentProps,
      tableEditableCellRef: tableEditableCellRef,
      errorList: errorList,
      onEditChange: onEditChange
    };
  },
  render: function render() {
    var _this = this,
        _this$col$edit,
        _this$errorList,
        _this$errorList$,
        _this$errorList2,
        _this$errorList2$;

    var h = arguments[0];

    if (!this.isEdit) {
      return h("div", {
        "class": this.tableBaseClass.cellEditable,
        "on": {
          "click": function click(e) {
            _this.isEdit = true;
            e.stopPropagation();
          }
        }
      }, [this.cellNode, h(Edit1Icon, {
        "attrs": {
          "size": "12px"
        }
      })]);
    }

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

    if (!component) {
      log.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.tableBaseClass.cellEditWrap
    }, [h(component, 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
      }
    }]))]);
  }
});

export { EditableCell as default };
//# sourceMappingURL=editable-cell.js.map
