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

'use strict';

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

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var vue = require('vue');
var get = require('lodash/get');
var isFunction = require('lodash/isFunction');
var table_utils = require('../utils.js');
var form_formModel = require('../../form/form-model.js');
var table_hooks_useRowspanAndColspan = require('./useRowspanAndColspan.js');
require('@babel/runtime/helpers/typeof');
require('lodash/isObject');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/regenerator');
require('../../_chunks/dep-7f0559c3.js');
require('lodash/isEmpty');
require('lodash/isNumber');
require('lodash/isBoolean');
require('../../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@babel/runtime/helpers/slicedToArray');
require('lodash/camelCase');
require('lodash/isUndefined');
require('lodash/isNull');
require('lodash/isArray');
require('lodash/isString');
require('../../_common/js/log/log.js');

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

var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
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 cellRuleMap = /* @__PURE__ */new Map();
function useRowEdit(props) {
  var errorListMap = vue.ref({});
  var editableKeysMap = vue.computed(function () {
    return table_utils.getEditableKeysMap(props.editableRowKeys, props.data, props.rowKey || "id");
  });
  var editingCells = vue.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__default["default"](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__default["default"](col.edit.rules) ? col.edit.rules(item) : col.edit.rules;
        if (!col.edit || !rules || !rules.length) {
          resolve(_objectSpread(_objectSpread({}, item), {}, {
            errorList: []
          }));
          return;
        }
        form_formModel.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__default["default"](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(context) {
    if (props.editableRowKeys) {
      var rowValue = get__default["default"](context.row, props.rowKey || "id");
      var rules = cellRuleMap.get(rowValue);
      if (rules) {
        var index = rules.findIndex(function (t) {
          return t.col.colKey === context.col.colKey;
        });
        if (index === -1) rules.push(context);else rules[index] = context;
        cellRuleMap.set(rowValue, rules);
      } else {
        cellRuleMap.set(rowValue, [context]);
      }
    }
  };
  var clearValidateData = function clearValidateData() {
    errorListMap.value = {};
  };
  var onPrimaryTableCellEditChange = function onPrimaryTableCellEditChange(params) {
    var cellKey = table_hooks_useRowspanAndColspan.getCellKey(params.row, props.rowKey, params.col.colKey, params.colIndex);
    if (params.isEdit) editingCells.value[cellKey] = params;else delete editingCells.value[cellKey];
  };
  return {
    errorListMap: errorListMap,
    editableKeysMap: editableKeysMap,
    validateTableData: validateTableData,
    validateRowData: validateRowData,
    onRuleChange: onRuleChange,
    clearValidateData: clearValidateData,
    onPrimaryTableCellEditChange: onPrimaryTableCellEditChange
  };
}

exports["default"] = useRowEdit;
//# sourceMappingURL=useEditableRow.js.map
