/**
 * ldesign v0.2.14
 * (c) 2022/11/2 16:16 built by swimly
 * @license MIT
 */

'use strict';

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

var helper = require('../../../chunks/helper.js');
var VueCompositionAPI = require('@vue/composition-api');
var get = require('lodash/get');
var lodashSet = require('lodash/set');
var isFunction = require('lodash/isFunction');
var iconsVue = require('@ldesign/icons-vue');
var log = require('../../../chunks/log.js');
var hooks_useGlobalIcon = require('../../../hooks/use-global-icon.js');
var components_form_model = require('../../form/model.js');
var components_table_core_tr = require('./tr.js');
require('../../../chunks/_commonjsHelpers-2e6815bd.js');
require('../../config-provider/useConfig.js');
require('../../config-provider/context.js');
require('lodash');
require('../../../chunks/zh_CN.js');
require('../../../chunks/_commonjsHelpers.js');
require('lodash/isEmpty');
require('lodash/isNumber');
require('../../../utils/helper.js');
require('lodash/camelCase');
require('lodash/upperFirst');
require('lodash/isString');
require('lodash/pick');
require('../../../hooks/use-lazy-load.js');
require('../../../chunks/observe.js');
require('../utils.js');
require('lodash/isObject');
require('../hooks/useFixed.js');
require('lodash/debounce');
require('../../../chunks/helper2.js');
require('../../../utils/dom.js');
require('vue');
require('raf');
require('../../../utils/easing.js');
require('../hooks/useClassName.js');
require('../props.js');
require('../hooks/useRowspanAndColspan.js');
require('./ellipsis.js');
require('../../../utils/render-node.js');
require('../../tooltip/index.js');
require('../../../utils/map-props.js');
require('../../../utils/with-install.js');
require('../../../config.js');
require('../../tooltip/tooltip.js');
require('../../popup/props.js');
require('../../popup/popup.js');
require('@popperjs/core');
require('../../../chunks/set-style.js');
require('../../config-provider/config-receiver.js');
require('lodash/mergeWith');
require('../../../utils/mixins.js');
require('../../popup/container.js');
require('../../tooltip/props.js');

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

var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
var lodashSet__default = /*#__PURE__*/_interopDefaultLegacy(lodashSet);
var isFunction__default = /*#__PURE__*/_interopDefaultLegacy(isFunction);

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(props, context) {
    var _props$col$edit;
    const {
      row,
      col
    } = VueCompositionAPI.toRefs(props);
    const tableEditableCellRef = VueCompositionAPI.ref(null);
    const isEdit = VueCompositionAPI.ref(((_props$col$edit = props.col.edit) === null || _props$col$edit === void 0 ? void 0 : _props$col$edit.defaultEditable) || false);
    const editValue = VueCompositionAPI.ref();
    const errorList = VueCompositionAPI.ref();
    const {
      Edit1Icon
    } = hooks_useGlobalIcon.useGlobalIcon({
      Edit1Icon: iconsVue.Edit1Icon
    });
    const currentRow = VueCompositionAPI.computed(() => {
      const newRow = {
        ...row.value
      };
      col.value && lodashSet__default["default"](newRow, col.value.colKey, editValue.value);
      return newRow;
    });
    const cellParams = VueCompositionAPI.computed(() => ({
      rowIndex: props.rowIndex,
      colIndex: props.colIndex,
      col: props.col,
      row: props.row
    }));
    const cellNode = VueCompositionAPI.computed(() => {
      const node = components_table_core_tr.renderCell({
        row: currentRow.value,
        col: {
          ...col.value,
          cell: props.oldCell
        },
        rowIndex: props.rowIndex,
        colIndex: props.colIndex
      }, context.slots, {
        cellEmptyContent: props.cellEmptyContent
      });
      return node;
    });
    const componentProps = VueCompositionAPI.computed(() => {
      var _edit$abortEditOnEven;
      const {
        edit
      } = col.value;
      if (!edit) return {};
      const editProps = isFunction__default["default"](edit.props) ? edit.props({
        ...cellParams.value,
        editedRow: currentRow.value
      }) : {
        ...edit.props
      };
      delete editProps.onChange;
      delete editProps.value;
      (_edit$abortEditOnEven = edit.abortEditOnEvent) === null || _edit$abortEditOnEven === void 0 ? void 0 : _edit$abortEditOnEven.forEach(item => {
        delete editProps[item];
      });
      return editProps;
    });
    const isAbortEditOnChange = VueCompositionAPI.computed(() => {
      var _edit$abortEditOnEven2;
      const {
        edit
      } = col.value;
      if (!edit) return false;
      return Boolean((_edit$abortEditOnEven2 = edit.abortEditOnEvent) === null || _edit$abortEditOnEven2 === void 0 ? void 0 : _edit$abortEditOnEven2.includes("onChange"));
    });
    const validateEdit = trigger => new Promise(resolve => {
      const params = {
        result: [{
          ...cellParams.value,
          errorList: [],
          value: editValue.value
        }],
        trigger
      };
      const rules = isFunction__default["default"](col.value.edit.rules) ? col.value.edit.rules(cellParams.value) : 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;
      }
      components_form_model.validate(editValue.value, rules).then(result => {
        var _props$onValidate2;
        const list = result === null || result === void 0 ? void 0 : result.filter(t => !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);
        }
      });
    });
    const isSame = (a, b) => {
      if (typeof a === "object" && typeof b === "object") return JSON.stringify(a) === JSON.stringify(b);
      return a === b;
    };
    const updateAndSaveAbort = function (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(result => {
        if (result !== true) return;
        const 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(...args);
        }
        const timer = setTimeout(() => {
          isEdit.value = false;
          errorList.value = [];
          clearTimeout(timer);
        }, 0);
      });
    };
    const listeners = VueCompositionAPI.computed(() => {
      var _edit$abortEditOnEven3;
      const {
        edit
      } = col.value;
      const 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 {};
      const tListeners = {};
      const outsideAbortEvent = edit === null || edit === void 0 ? void 0 : edit.onEdited;
      edit.abortEditOnEvent.forEach(itemEvent => {
        if (itemEvent === "onChange") return;
        const 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(outsideAbortEvent, {
            ...cellParams.value,
            trigger: itemEvent,
            newRowData: currentRow.value
          }, ...args);
        };
      });
      return tListeners;
    });
    const onEditChange = function (val) {
      var _props$onChange, _props$onRuleChange;
      editValue.value = val;
      const params = {
        ...cellParams.value,
        value: val,
        editedRow: {
          ...props.row,
          [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);
      const isCellEditable = props.editable === void 0;
      if (isCellEditable && isAbortEditOnChange.value) {
        var _col$value$edit;
        const 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(outsideAbortEvent, {
          ...cellParams.value,
          trigger: "onChange",
          newRowData: currentRow.value
        }, ...args);
      }
    };
    const 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 (let i = 0, len = e.path.length; i < len; i++) {
        var _node$classList, _node$classList$value;
        const 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;
      }
      const outsideAbortEvent = col.value.edit.onEdited;
      updateAndSaveAbort(outsideAbortEvent, {
        ...cellParams.value,
        trigger: "document",
        newRowData: currentRow.value
      });
    };
    const cellValue = VueCompositionAPI.computed(() => get__default["default"](row.value, col.value.colKey));
    VueCompositionAPI.watch(cellValue, cellValue2 => {
      let val = cellValue2;
      if (typeof val === "object" && val !== null) val = Array.isArray(val) ? [...val] : {
        ...val
      };
      editValue.value = val;
    }, {
      immediate: true
    });
    VueCompositionAPI.watch(isEdit, isEdit2 => {
      const 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(() => [props.editable, props.rowIndex, props.colIndex], _ref => {
      let [editable, rowIndex, colIndex] = _ref;
      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,
          colIndex,
          value: cellValue.value,
          editedRow: row.value
        });
      }
    }, {
      immediate: true
    });
    VueCompositionAPI.watch(() => props.errors, errors => {
      errorList.value = errors;
    });
    return {
      editValue,
      isEdit,
      cellNode,
      isAbortEditOnChange,
      listeners,
      componentProps,
      tableEditableCellRef,
      errorList,
      onEditChange,
      Edit1Icon,
      cellParams
    };
  },
  render() {
    var _this$col$edit2, _this$errorList, _this$errorList$, _this$tableBaseClass2, _this$errorList2, _this$errorList2$;
    const 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;
      const {
        Edit1Icon
      } = this;
      return h("div", {
        "class": (_this$tableBaseClass = this.tableBaseClass) === null || _this$tableBaseClass === void 0 ? void 0 : _this$tableBaseClass.cellEditable,
        "on": {
          "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"
        }
      })]);
    }
    const Component = (_this$col$edit2 = this.col.edit) === null || _this$col$edit2 === void 0 ? void 0 : _this$col$edit2.component;
    if (!Component) {
      log.log.error("Table", "edit.component is required.");
      return null;
    }
    const 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": 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
