/**
 * ldesign v0.2.22
 * (c) 2022/12/7 16:21 built by swimly
 * @license MIT
 */

'use strict';

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

var VueCompositionAPI = require('@vue/composition-api');
var get = require('lodash/get');
var isFunction = require('lodash/isFunction');
var components_table_utils = require('../utils.js');
var components_form_model = require('../../form/model.js');
require('lodash/isObject');
require('../../../chunks/_commonjsHelpers.js');
require('lodash/isEmpty');
require('lodash/isNumber');
require('../../../utils/helper.js');
require('lodash/camelCase');

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

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

const cellRuleMap = /* @__PURE__ */new Map();
function useRowEdit(props, context) {
  const errorListMap = VueCompositionAPI.ref({});
  const editableKeysMap = VueCompositionAPI.computed(() => components_table_utils.getEditableKeysMap(props.editableRowKeys, props.data, props.rowKey || "id"));
  const getErrorListMapByErrors = errors => {
    const errorMap = {};
    errors.forEach(_ref => {
      let {
        row,
        col,
        errorList
      } = _ref;
      const rowValue = get__default["default"](row, props.rowKey || "id");
      const key = [rowValue, col.colKey].join("__");
      if (errorList?.length) errorMap[key] = errorList;else delete errorMap[key];
    });
    return errorMap;
  };
  const validateOneRowData = rowValue => {
    const rowRules = cellRuleMap.get(rowValue);
    if (!rowRules) return;
    const list = rowRules.map(item => new Promise(resolve => {
      const {
        editedRow,
        col
      } = item;
      const rules = isFunction__default["default"](col.edit.rules) ? col.edit.rules(item) : col.edit.rules;
      if (!col.edit || !rules || !rules.length) {
        resolve({
          ...item,
          errorList: []
        });
        return;
      }
      components_form_model.validate(editedRow[col.colKey], rules).then(r => {
        resolve({
          ...item,
          errorList: r.filter(t => !t.result)
        });
      });
    }));
    return new Promise((resolve, reject) => {
      Promise.all(list).then(errors => {
        resolve({
          errors: errors.filter(t => t.errorList?.length),
          errorMap: getErrorListMapByErrors(errors)
        });
      }, reject);
    });
  };
  const validateRowData = rowValue => new Promise((resolve, reject) => {
    validateOneRowData(rowValue).then(_ref2 => {
      let {
        errors,
        errorMap
      } = _ref2;
      errorListMap.value = errorMap;
      const tTrigger = "parent";
      props.onRowValidate?.({
        trigger: tTrigger,
        result: errors
      });
      resolve({
        trigger: tTrigger,
        result: errors
      });
    }, reject);
  });
  const validateTableData = () => {
    const promiseList = [];
    const data = props.data || [];
    for (let i = 0, len = data.length; i < len; i++) {
      const rowValue = get__default["default"](data[i], props.rowKey || "id");
      promiseList.push(validateOneRowData(rowValue));
    }
    return new Promise((resolve, reject) => {
      Promise.all(promiseList).then(rList => {
        const allErrorListMap = {};
        rList.forEach(function () {
          let {
            errorMap
          } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
            errors: [],
            errorMap: {}
          };
          errorMap && Object.assign(allErrorListMap, errorMap);
        });
        errorListMap.value = allErrorListMap;
        props.onValidate?.({
          result: allErrorListMap
        });
        resolve({
          result: allErrorListMap
        });
      }, reject);
    });
  };
  const onRuleChange = context2 => {
    if (props.editableRowKeys) {
      const rowValue = get__default["default"](context2.row, props.rowKey || "id");
      const rules = cellRuleMap.get(rowValue);
      if (rules) {
        const index = rules.findIndex(t => 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]);
      }
    }
  };
  const clearValidateData = () => {
    errorListMap.value = {};
  };
  const onPrimaryTableRowEdit = params => {
    props.onRowEdit?.(params);
    context.emit("row-edit", params);
  };
  const onPrimaryTableRowValidate = params => {
    props.onRowValidate?.(params);
    context.emit("row-validate", params);
  };
  return {
    errorListMap,
    editableKeysMap,
    validateTableData,
    validateRowData,
    onRuleChange,
    clearValidateData,
    onPrimaryTableRowEdit,
    onPrimaryTableRowValidate
  };
}

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