/**
 * ldesign v0.4.6
 * (c) 2023 ldesign
 * @license MIT
 */

import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { ref, computed } from '@vue/composition-api';
import get from 'lodash/get';
import isFunction from 'lodash/isFunction';
import { getEditableKeysMap } from '../utils.js';
import { validate } from '../../form/form-model.js';
import { getCellKey } from './useRowspanAndColspan.js';
import '@babel/runtime/helpers/typeof';
import 'lodash/isObject';
import '@babel/runtime/helpers/asyncToGenerator';
import '@babel/runtime/regenerator';
import '../../_chunks/dep-2cb61c79.js';
import 'lodash/isEmpty';
import 'lodash/isNumber';
import '../../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '@babel/runtime/helpers/slicedToArray';
import 'lodash/camelCase';
import '../../_common/js/log/log.js';

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 cellRuleMap = /* @__PURE__ */new Map();
function useRowEdit(props, context) {
  var errorListMap = ref({});
  var editableKeysMap = computed(function () {
    return getEditableKeysMap(props.editableRowKeys, props.data, props.rowKey || "id");
  });
  var editingCells = ref({});
  var getErrorListMapByErrors = function getErrorListMapByErrors(errors) {
    var errorMap = {};
    errors.forEach(function (_ref) {
      var row = _ref.row,
        col = _ref.col,
        errorList = _ref.errorList;
      var rowValue = get(row, props.rowKey || "id");
      var key = [rowValue, col.colKey].join("__");
      if (errorList !== null && errorList !== void 0 && errorList.length) errorMap[key] = errorList;else delete errorMap[key];
    });
    return errorMap;
  };
  var validateOneRowData = function validateOneRowData(rowValue) {
    var rowRules = cellRuleMap.get(rowValue);
    if (!rowRules) return;
    var list = rowRules.map(function (item) {
      return new Promise(function (resolve) {
        var editedRow = item.editedRow,
          col = item.col;
        var rules = isFunction(col.edit.rules) ? col.edit.rules(item) : col.edit.rules;
        if (!col.edit || !rules || !rules.length) {
          resolve(_objectSpread(_objectSpread({}, item), {}, {
            errorList: []
          }));
          return;
        }
        validate(editedRow[col.colKey], rules).then(function (r) {
          resolve(_objectSpread(_objectSpread({}, item), {}, {
            errorList: r.filter(function (t) {
              return !t.result;
            })
          }));
        });
      });
    });
    return new Promise(function (resolve, reject) {
      Promise.all(list).then(function (errors) {
        resolve({
          errors: errors.filter(function (t) {
            var _t$errorList;
            return (_t$errorList = t.errorList) === null || _t$errorList === void 0 ? void 0 : _t$errorList.length;
          }),
          errorMap: getErrorListMapByErrors(errors)
        });
      }, reject);
    });
  };
  var validateRowData = function validateRowData(rowValue) {
    return new Promise(function (resolve, reject) {
      validateOneRowData(rowValue).then(function (_ref2) {
        var _props$onRowValidate;
        var errors = _ref2.errors,
          errorMap = _ref2.errorMap;
        errorListMap.value = errorMap;
        var tTrigger = "parent";
        (_props$onRowValidate = props.onRowValidate) === null || _props$onRowValidate === void 0 ? void 0 : _props$onRowValidate.call(props, {
          trigger: tTrigger,
          result: errors
        });
        resolve({
          trigger: tTrigger,
          result: errors
        });
      }, reject);
    });
  };
  var validateTableCellData = function validateTableCellData() {
    var cellKeys = Object.keys(editingCells.value);
    var promiseList = cellKeys.map(function (cellKey) {
      return editingCells.value[cellKey].validateEdit("parent");
    });
    return new Promise(function (resolve, reject) {
      Promise.all(promiseList).then(function (arr) {
        var allErrorListMap = {};
        arr.forEach(function (result, index) {
          if (result === true) return;
          allErrorListMap[cellKeys[index]] = result;
        });
        resolve({
          result: allErrorListMap
        });
      }, reject);
    });
  };
  var validateTableData = function validateTableData() {
    if (Object.keys(editingCells.value).length) return validateTableCellData();
    var promiseList = [];
    var data = props.data || [];
    for (var i = 0, len = data.length; i < len; i++) {
      var rowValue = get(data[i], props.rowKey || "id");
      promiseList.push(validateOneRowData(rowValue));
    }
    return new Promise(function (resolve, reject) {
      Promise.all(promiseList).then(function (rList) {
        var _props$onValidate;
        var allErrorListMap = {};
        rList.forEach(function () {
          var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
              errors: [],
              errorMap: {}
            },
            errorMap = _ref3.errorMap;
          errorMap && Object.assign(allErrorListMap, errorMap);
        });
        errorListMap.value = allErrorListMap;
        (_props$onValidate = props.onValidate) === null || _props$onValidate === void 0 ? void 0 : _props$onValidate.call(props, {
          result: allErrorListMap
        });
        resolve({
          result: allErrorListMap
        });
      }, reject);
    });
  };
  var onRuleChange = function onRuleChange(context2) {
    if (props.editableRowKeys) {
      var rowValue = get(context2.row, props.rowKey || "id");
      var rules = cellRuleMap.get(rowValue);
      if (rules) {
        var index = rules.findIndex(function (t) {
          return t.col.colKey === context2.col.colKey;
        });
        if (index === -1) rules.push(context2);else rules[index] = context2;
        cellRuleMap.set(rowValue, rules);
      } else {
        cellRuleMap.set(rowValue, [context2]);
      }
    }
  };
  var clearValidateData = function clearValidateData() {
    errorListMap.value = {};
  };
  var onPrimaryTableCellEditChange = function onPrimaryTableCellEditChange(params) {
    var cellKey = getCellKey(params.row, props.rowKey, params.col.colKey, params.colIndex);
    if (params.isEdit) editingCells.value[cellKey] = params;else delete editingCells.value[cellKey];
  };
  var onPrimaryTableRowEdit = function onPrimaryTableRowEdit(params) {
    var _props$onRowEdit;
    (_props$onRowEdit = props.onRowEdit) === null || _props$onRowEdit === void 0 ? void 0 : _props$onRowEdit.call(props, params);
    context.emit("row-edit", params);
  };
  var onPrimaryTableRowValidate = function onPrimaryTableRowValidate(params) {
    var _props$onRowValidate2;
    (_props$onRowValidate2 = props.onRowValidate) === null || _props$onRowValidate2 === void 0 ? void 0 : _props$onRowValidate2.call(props, params);
    context.emit("row-validate", params);
  };
  return {
    errorListMap: errorListMap,
    editableKeysMap: editableKeysMap,
    validateTableData: validateTableData,
    validateRowData: validateRowData,
    onRuleChange: onRuleChange,
    clearValidateData: clearValidateData,
    onPrimaryTableRowEdit: onPrimaryTableRowEdit,
    onPrimaryTableRowValidate: onPrimaryTableRowValidate,
    onPrimaryTableCellEditChange: onPrimaryTableCellEditChange
  };
}

export { useRowEdit as default };
//# sourceMappingURL=useEditableRow.js.map
