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

'use strict';

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

var _asyncToGenerator = require('@babel/runtime/helpers/asyncToGenerator');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var vue = require('vue');
var _regeneratorRuntime = require('@babel/runtime/regenerator');
var iconsVueNext = require('@ldesign/icons-vue-next');
var isArray = require('lodash/isArray');
var isNumber = require('lodash/isNumber');
var isString = require('lodash/isString');
var isBoolean = require('lodash/isBoolean');
var cloneDeep = require('lodash/cloneDeep');
var get = require('lodash/get');
var lodashSet = require('lodash/set');
var isNil = require('lodash/isNil');
var lodashTemplate = require('lodash/template');
var hooks_useGlobalIcon = require('../hooks/useGlobalIcon.js');
var form_formModel = require('./form-model.js');
var form_formItemProps = require('./form-item-props.js');
var form_const = require('./const.js');
var configProvider_useConfig = require('../config-provider/useConfig.js');
var hooks_useConfig = require('../hooks/useConfig.js');
var hooks_tnode = require('../hooks/tnode.js');
require('../_chunks/dep-f4db2590.js');
require('lodash/isEmpty');
require('lodash/isObject');
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/isFunction');
require('../config-provider/context.js');
require('lodash/mergeWith');
require('lodash/merge');
require('../_common/js/global-config/default-config.js');
require('../_common/js/global-config/locale/zh_CN.js');
require('@babel/runtime/helpers/typeof');
require('dayjs');
require('lodash/kebabCase');
require('../utils/render-tnode.js');

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

var _asyncToGenerator__default = /*#__PURE__*/_interopDefaultLegacy(_asyncToGenerator);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _regeneratorRuntime__default = /*#__PURE__*/_interopDefaultLegacy(_regeneratorRuntime);
var isArray__default = /*#__PURE__*/_interopDefaultLegacy(isArray);
var isNumber__default = /*#__PURE__*/_interopDefaultLegacy(isNumber);
var isString__default = /*#__PURE__*/_interopDefaultLegacy(isString);
var isBoolean__default = /*#__PURE__*/_interopDefaultLegacy(isBoolean);
var cloneDeep__default = /*#__PURE__*/_interopDefaultLegacy(cloneDeep);
var get__default = /*#__PURE__*/_interopDefaultLegacy(get);
var lodashSet__default = /*#__PURE__*/_interopDefaultLegacy(lodashSet);
var isNil__default = /*#__PURE__*/_interopDefaultLegacy(isNil);
var lodashTemplate__default = /*#__PURE__*/_interopDefaultLegacy(lodashTemplate);

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 _FormItem = vue.defineComponent({
  name: "TFormItem",
  props: _objectSpread({}, form_formItemProps["default"]),
  setup: function setup(props2, _ref) {
    var slots = _ref.slots;
    var renderContent = hooks_tnode.useTNodeJSX();
    var CLASS_NAMES = form_const.useCLASSNAMES();
    var _useConfig = configProvider_useConfig.useConfig("form"),
      globalConfig = _useConfig.globalConfig;
    var _useGlobalIcon = hooks_useGlobalIcon.useGlobalIcon({
        CheckCircleFilledIcon: iconsVueNext.CheckCircleFilledIcon,
        CloseCircleFilledIcon: iconsVueNext.CloseCircleFilledIcon,
        ErrorCircleFilledIcon: iconsVueNext.ErrorCircleFilledIcon
      }),
      CheckCircleFilledIcon = _useGlobalIcon.CheckCircleFilledIcon,
      CloseCircleFilledIcon = _useGlobalIcon.CloseCircleFilledIcon,
      ErrorCircleFilledIcon = _useGlobalIcon.ErrorCircleFilledIcon;
    var form = vue.inject(form_const.FormInjectionKey, void 0);
    var FORM_ITEM_CLASS_PREFIX = hooks_useConfig.usePrefixClass("form-item__");
    var needRequiredMark = vue.computed(function () {
      var _ref2, _props2$requiredMark;
      var requiredMark = (_ref2 = (_props2$requiredMark = props2.requiredMark) !== null && _props2$requiredMark !== void 0 ? _props2$requiredMark : form === null || form === void 0 ? void 0 : form.requiredMark) !== null && _ref2 !== void 0 ? _ref2 : globalConfig.value.requiredMark;
      var isRequired = innerRules.value.filter(function (rule) {
        return rule.required;
      }).length > 0;
      return requiredMark !== null && requiredMark !== void 0 ? requiredMark : isRequired;
    });
    var hasLabel = vue.computed(function () {
      return slots.label || props2.label;
    });
    var hasColon = vue.computed(function () {
      return !!(form !== null && form !== void 0 && form.colon && hasLabel.value);
    });
    var FROM_LABEL = hooks_useConfig.usePrefixClass("form__label");
    var labelAlign = vue.computed(function () {
      return isNil__default["default"](props2.labelAlign) ? form === null || form === void 0 ? void 0 : form.labelAlign : props2.labelAlign;
    });
    var labelWidth = vue.computed(function () {
      return isNil__default["default"](props2.labelWidth) ? form === null || form === void 0 ? void 0 : form.labelWidth : props2.labelWidth;
    });
    var labelClasses = vue.computed(function () {
      var _ref3;
      return [CLASS_NAMES.value.label, (_ref3 = {}, _defineProperty__default["default"](_ref3, "".concat(FROM_LABEL.value, "--required"), needRequiredMark.value), _defineProperty__default["default"](_ref3, "".concat(FROM_LABEL.value, "--colon"), hasColon.value), _defineProperty__default["default"](_ref3, "".concat(FROM_LABEL.value, "--top"), hasLabel.value && (labelAlign.value === "top" || !labelWidth.value)), _defineProperty__default["default"](_ref3, "".concat(FROM_LABEL.value, "--left"), labelAlign.value === "left" && labelWidth.value), _defineProperty__default["default"](_ref3, "".concat(FROM_LABEL.value, "--right"), labelAlign.value === "right" && labelWidth.value), _ref3)];
    });
    var renderLabel = function renderLabel() {
      if (Number(labelWidth.value) === 0) return;
      var labelStyle = {};
      if (labelWidth.value && labelAlign.value !== "top") {
        if (isNumber__default["default"](labelWidth.value)) labelStyle = {
          width: "".concat(labelWidth.value, "px")
        };else labelStyle = {
          width: labelWidth.value
        };
      }
      return vue.createVNode("div", {
        "class": labelClasses.value,
        "style": labelStyle
      }, [vue.createVNode("label", {
        "for": props2["for"]
      }, [renderContent("label")])]);
    };
    var getDefaultIcon = function getDefaultIcon() {
      var resultIcon = function resultIcon(Icon) {
        return vue.createVNode("span", {
          "class": CLASS_NAMES.value.status
        }, [vue.createVNode(Icon, null, null)]);
      };
      var list = errorList.value;
      if (verifyStatus.value === form_const.ValidateStatus.SUCCESS) return resultIcon(CheckCircleFilledIcon);
      if (list !== null && list !== void 0 && list[0]) {
        var type = list[0].type || "error";
        var icon = {
          error: CloseCircleFilledIcon,
          warning: ErrorCircleFilledIcon
        }[type] || CheckCircleFilledIcon;
        return resultIcon(icon);
      }
      return null;
    };
    var renderSuffixIcon = function renderSuffixIcon() {
      var statusIcon = props2.statusIcon;
      if (statusIcon === false) return;
      var resultIcon = renderContent("statusIcon", {
        defaultNode: getDefaultIcon()
      });
      if (resultIcon) return vue.createVNode("span", {
        "class": CLASS_NAMES.value.status
      }, [resultIcon]);
      if (resultIcon === false) return;
      resultIcon = form === null || form === void 0 ? void 0 : form.renderContent("statusIcon", {
        defaultNode: getDefaultIcon()
      });
      if (resultIcon) return resultIcon;
    };
    var errorClasses = vue.computed(function () {
      if (!showErrorMessage.value) return "";
      if (verifyStatus.value === form_const.ValidateStatus.SUCCESS) {
        return props2.successBorder ? [CLASS_NAMES.value.success, CLASS_NAMES.value.successBorder].join(" ") : CLASS_NAMES.value.success;
      }
      if (!errorList.value.length) return;
      var type = errorList.value[0].type || "error";
      return type === "error" ? CLASS_NAMES.value.error : CLASS_NAMES.value.warning;
    });
    var contentClasses = vue.computed(function () {
      return [CLASS_NAMES.value.controls, errorClasses.value];
    });
    var contentStyle = vue.computed(function () {
      var contentStyle2 = {};
      if (labelWidth.value && labelAlign.value !== "top") {
        if (isNumber__default["default"](labelWidth.value)) contentStyle2 = {
          marginLeft: "".concat(labelWidth.value, "px")
        };else contentStyle2 = {
          marginLeft: labelWidth.value
        };
      }
      return contentStyle2;
    });
    var errorList = vue.ref([]);
    var successList = vue.ref([]);
    var verifyStatus = vue.ref(form_const.ValidateStatus.TO_BE_VALIDATED);
    var resetValidating = vue.ref(false);
    var needResetField = vue.ref(false);
    var resetHandler = function resetHandler() {
      needResetField.value = false;
      errorList.value = [];
      successList.value = [];
      verifyStatus.value = form_const.ValidateStatus.TO_BE_VALIDATED;
    };
    var getEmptyValue = function getEmptyValue() {
      var type = Object.prototype.toString.call(get__default["default"](form === null || form === void 0 ? void 0 : form.data, props2.name));
      var emptyValue;
      if (type === "[object String]") emptyValue = "";
      if (type === "[object Array]") emptyValue = [];
      if (type === "[object Object]") emptyValue = {};
      return emptyValue;
    };
    var resetField = /*#__PURE__*/function () {
      var _ref4 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee() {
        var resetType,
          _args = arguments;
        return _regeneratorRuntime__default["default"].wrap(function _callee$(_context) {
          while (1) switch (_context.prev = _context.next) {
            case 0:
              resetType = _args.length > 0 && _args[0] !== undefined ? _args[0] : form === null || form === void 0 ? void 0 : form.resetType;
              if (props2.name) {
                _context.next = 3;
                break;
              }
              return _context.abrupt("return");
            case 3:
              if (resetType === "empty") lodashSet__default["default"](form === null || form === void 0 ? void 0 : form.data, props2.name, getEmptyValue());else if (resetType === "initial") lodashSet__default["default"](form === null || form === void 0 ? void 0 : form.data, props2.name, initialValue.value);
              _context.next = 6;
              return vue.nextTick();
            case 6:
              if (resetValidating.value) needResetField.value = true;else resetHandler();
            case 7:
            case "end":
              return _context.stop();
          }
        }, _callee);
      }));
      return function resetField() {
        return _ref4.apply(this, arguments);
      };
    }();
    var errorMessages = vue.computed(function () {
      var _form$errorMessage;
      return (_form$errorMessage = form === null || form === void 0 ? void 0 : form.errorMessage) !== null && _form$errorMessage !== void 0 ? _form$errorMessage : globalConfig.value.errorMessage;
    });
    var innerRules = vue.computed(function () {
      var _props2$rules;
      if ((_props2$rules = props2.rules) !== null && _props2$rules !== void 0 && _props2$rules.length) return props2.rules;
      if (!props2.name) return [];
      var index = "".concat(props2.name).lastIndexOf(".") || -1;
      var pRuleName = "".concat(props2.name).slice(index + 1);
      return get__default["default"](form === null || form === void 0 ? void 0 : form.rules, props2.name) || get__default["default"](form === null || form === void 0 ? void 0 : form.rules, pRuleName) || [];
    });
    var analysisValidateResult = /*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee2(trigger) {
        var _result$rules;
        var result;
        return _regeneratorRuntime__default["default"].wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              result = {
                successList: [],
                errorList: [],
                rules: [],
                resultList: [],
                allowSetValue: false
              };
              result.rules = trigger === "all" ? innerRules.value : innerRules.value.filter(function (item) {
                return (item.trigger || "change") === trigger;
              });
              if (!(innerRules.value.length && !((_result$rules = result.rules) !== null && _result$rules !== void 0 && _result$rules.length))) {
                _context2.next = 4;
                break;
              }
              return _context2.abrupt("return", result);
            case 4:
              result.allowSetValue = true;
              _context2.next = 7;
              return form_formModel.validate(value.value, result.rules);
            case 7:
              result.resultList = _context2.sent;
              result.errorList = result.resultList.filter(function (item) {
                return item.result !== true;
              }).map(function (item) {
                Object.keys(item).forEach(function (key) {
                  if (!item.message && errorMessages.value[key]) {
                    var compiled = lodashTemplate__default["default"](errorMessages.value[key]);
                    var name2 = isString__default["default"](props2.label) ? props2.label : props2.name;
                    item.message = compiled({
                      name: name2,
                      validate: item[key]
                    });
                  }
                });
                return item;
              });
              result.successList = result.resultList.filter(function (item) {
                return item.result === true && item.message && item.type === "success";
              });
              return _context2.abrupt("return", result);
            case 11:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return function analysisValidateResult(_x) {
        return _ref5.apply(this, arguments);
      };
    }();
    var validateHandler = /*#__PURE__*/function () {
      var _ref6 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee3(trigger, showErrorMessage2) {
        var _yield$analysisValida, innerSuccessList, innerErrorList, rules, resultList, allowSetValue;
        return _regeneratorRuntime__default["default"].wrap(function _callee3$(_context3) {
          while (1) switch (_context3.prev = _context3.next) {
            case 0:
              resetValidating.value = true;
              freeShowErrorMessage.value = showErrorMessage2;
              _context3.next = 4;
              return analysisValidateResult(trigger);
            case 4:
              _yield$analysisValida = _context3.sent;
              innerSuccessList = _yield$analysisValida.successList;
              innerErrorList = _yield$analysisValida.errorList;
              rules = _yield$analysisValida.rules;
              resultList = _yield$analysisValida.resultList;
              allowSetValue = _yield$analysisValida.allowSetValue;
              if (allowSetValue) {
                successList.value = innerSuccessList;
                errorList.value = innerErrorList;
              }
              if (rules.length) verifyStatus.value = innerErrorList.length ? form_const.ValidateStatus.FAIL : form_const.ValidateStatus.SUCCESS;
              if (needResetField.value) resetHandler();
              resetValidating.value = false;
              return _context3.abrupt("return", _defineProperty__default["default"]({}, props2.name, innerErrorList.length === 0 ? true : resultList));
            case 15:
            case "end":
              return _context3.stop();
          }
        }, _callee3);
      }));
      return function validateHandler(_x2, _x3) {
        return _ref6.apply(this, arguments);
      };
    }();
    var validateOnly = /*#__PURE__*/function () {
      var _ref8 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee4(trigger) {
        var _yield$analysisValida2, innerErrorList, resultList;
        return _regeneratorRuntime__default["default"].wrap(function _callee4$(_context4) {
          while (1) switch (_context4.prev = _context4.next) {
            case 0:
              _context4.next = 2;
              return analysisValidateResult(trigger);
            case 2:
              _yield$analysisValida2 = _context4.sent;
              innerErrorList = _yield$analysisValida2.errorList;
              resultList = _yield$analysisValida2.resultList;
              return _context4.abrupt("return", _defineProperty__default["default"]({}, props2.name, innerErrorList.length === 0 ? true : resultList));
            case 6:
            case "end":
              return _context4.stop();
          }
        }, _callee4);
      }));
      return function validateOnly(_x4) {
        return _ref8.apply(this, arguments);
      };
    }();
    var setValidateMessage = function setValidateMessage(validateMessage) {
      if (!validateMessage && !isArray__default["default"](validateMessage)) return;
      if (validateMessage.length === 0) {
        errorList.value = [];
        verifyStatus.value = form_const.ValidateStatus.SUCCESS;
      }
      errorList.value = validateMessage.map(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          result: false
        });
      });
      verifyStatus.value = form_const.ValidateStatus.FAIL;
    };
    var value = vue.computed(function () {
      return (form === null || form === void 0 ? void 0 : form.data) && get__default["default"](form === null || form === void 0 ? void 0 : form.data, props2.name);
    });
    var initialValue = vue.ref(void 0);
    var _toRefs = vue.toRefs(props2),
      name = _toRefs.name;
    var context = vue.reactive({
      name: name,
      resetHandler: resetHandler,
      resetField: resetField,
      validate: validateHandler,
      validateOnly: validateOnly,
      setValidateMessage: setValidateMessage
    });
    vue.onMounted(function () {
      initialValue.value = cloneDeep__default["default"](value.value);
      form === null || form === void 0 ? void 0 : form.children.push(context);
    });
    vue.onBeforeUnmount(function () {
      if (form) form.children = form === null || form === void 0 ? void 0 : form.children.filter(function (ctx) {
        return ctx !== context;
      });
    });
    vue.watch(value, /*#__PURE__*/_asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee5() {
      return _regeneratorRuntime__default["default"].wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            _context5.next = 2;
            return validateHandler("change");
          case 2:
          case "end":
            return _context5.stop();
        }
      }, _callee5);
    })), {
      deep: true
    });
    vue.watch(function () {
      return [props2.name, JSON.stringify(props2.rules)].join(",");
    }, function () {
      validateHandler("change");
    });
    var freeShowErrorMessage = vue.ref(void 0);
    var showErrorMessage = vue.computed(function () {
      if (isBoolean__default["default"](freeShowErrorMessage.value)) return freeShowErrorMessage.value;
      if (isBoolean__default["default"](props2.showErrorMessage)) return props2.showErrorMessage;
      return form === null || form === void 0 ? void 0 : form.showErrorMessage;
    });
    var classes = vue.computed(function () {
      var _ref11;
      return [CLASS_NAMES.value.formItem, FORM_ITEM_CLASS_PREFIX.value + (props2.name || ""), (_ref11 = {}, _defineProperty__default["default"](_ref11, CLASS_NAMES.value.formItemWithHelp, helpNode.value), _defineProperty__default["default"](_ref11, CLASS_NAMES.value.formItemWithExtra, extraNode.value), _ref11)];
    });
    var helpNode = vue.computed(function () {
      var help = renderContent("help");
      if (help) return vue.createVNode("div", {
        "class": CLASS_NAMES.value.help
      }, [help]);
      return null;
    });
    var extraNode = vue.computed(function () {
      var _list$;
      var getExtraNode = function getExtraNode(content) {
        return vue.createVNode("div", {
          "class": CLASS_NAMES.value.extra
        }, [content]);
      };
      var list = errorList.value;
      if (showErrorMessage.value && list !== null && list !== void 0 && (_list$ = list[0]) !== null && _list$ !== void 0 && _list$.message) return getExtraNode(list[0].message);
      if (successList.value.length) return getExtraNode(successList.value[0].message);
      return null;
    });
    var handleBlur = /*#__PURE__*/function () {
      var _ref12 = _asyncToGenerator__default["default"]( /*#__PURE__*/_regeneratorRuntime__default["default"].mark(function _callee6() {
        return _regeneratorRuntime__default["default"].wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              _context6.next = 2;
              return validateHandler("blur");
            case 2:
            case "end":
              return _context6.stop();
          }
        }, _callee6);
      }));
      return function handleBlur() {
        return _ref12.apply(this, arguments);
      };
    }();
    vue.provide(form_const.FormItemInjectionKey, {
      handleBlur: handleBlur
    });
    return function () {
      return vue.createVNode("div", {
        "class": classes.value
      }, [renderLabel(), vue.createVNode("div", {
        "class": contentClasses.value,
        "style": contentStyle.value
      }, [vue.createVNode("div", {
        "class": CLASS_NAMES.value.controlsContent
      }, [renderContent("default"), renderSuffixIcon()]), [helpNode.value, extraNode.value]])]);
    };
  }
});

exports["default"] = _FormItem;
//# sourceMappingURL=form-item.js.map
