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

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { defineComponent, inject, computed, createVNode, ref, nextTick, toRefs, reactive, onMounted, onBeforeUnmount, watch, provide } from 'vue';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } from '@ldesign/icons-vue-next';
import isArray from 'lodash/isArray';
import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import isBoolean from 'lodash/isBoolean';
import cloneDeep from 'lodash/cloneDeep';
import get from 'lodash/get';
import lodashSet from 'lodash/set';
import isNil from 'lodash/isNil';
import lodashTemplate from 'lodash/template';
import '../hooks/index.js';
import { useGlobalIcon } from '../hooks/useGlobalIcon.js';
import { validate } from './form-model.js';
import props from './form-item-props.js';
import { useCLASSNAMES, FormInjectionKey, ValidateStatus, FormItemInjectionKey } from './const.js';
import { useTNodeJSX } from '../hooks/tnode.js';
import { useConfig } from '../config-provider/useConfig.js';
import { usePrefixClass } from '../hooks/useConfig.js';
import '../hooks/icon.js';
import 'lodash/isFunction';
import '../hooks/slot.js';
import '../hooks/useCommonClassName.js';
import '../hooks/useDefaultValue.js';
import 'lodash/kebabCase';
import '../hooks/useDestroyOnClose.js';
import '../hooks/useKeepAnimation.js';
import '../config-provider/context.js';
import 'lodash/mergeWith';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.js';
import '@babel/runtime/helpers/typeof';
import '../_chunks/dep-2e5d8948.js';
import 'dayjs';
import '../_chunks/dep-4580aabe.js';
import '../hooks/useRipple.js';
import '../utils/set-style.js';
import '../hooks/useVirtualScroll.js';
import '../hooks/useVModel.js';
import 'lodash/isEmpty';
import 'lodash/isObject';
import '../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '@babel/runtime/helpers/slicedToArray';
import 'lodash/camelCase';
import 'lodash/isUndefined';
import 'lodash/isNull';
import '../utils/render-tnode.js';
import '../config-provider/type.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 _FormItem = defineComponent({
  name: "TFormItem",
  props: _objectSpread({}, props),
  setup: function setup(props2, _ref) {
    var slots = _ref.slots;
    var renderContent = useTNodeJSX();
    var CLASS_NAMES = useCLASSNAMES();
    var _useConfig = useConfig("form"),
      globalConfig = _useConfig.globalConfig;
    var _useGlobalIcon = useGlobalIcon({
        CheckCircleFilledIcon: CheckCircleFilledIcon,
        CloseCircleFilledIcon: CloseCircleFilledIcon,
        ErrorCircleFilledIcon: ErrorCircleFilledIcon
      }),
      CheckCircleFilledIcon$1 = _useGlobalIcon.CheckCircleFilledIcon,
      CloseCircleFilledIcon$1 = _useGlobalIcon.CloseCircleFilledIcon,
      ErrorCircleFilledIcon$1 = _useGlobalIcon.ErrorCircleFilledIcon;
    var form = inject(FormInjectionKey, void 0);
    var FORM_ITEM_CLASS_PREFIX = usePrefixClass("form-item__");
    var needRequiredMark = 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 = computed(function () {
      return slots.label || props2.label;
    });
    var hasColon = computed(function () {
      return !!(form !== null && form !== void 0 && form.colon && hasLabel.value);
    });
    var FROM_LABEL = usePrefixClass("form__label");
    var labelAlign = computed(function () {
      return isNil(props2.labelAlign) ? form === null || form === void 0 ? void 0 : form.labelAlign : props2.labelAlign;
    });
    var labelWidth = computed(function () {
      return isNil(props2.labelWidth) ? form === null || form === void 0 ? void 0 : form.labelWidth : props2.labelWidth;
    });
    var labelClasses = computed(function () {
      var _ref3;
      return [CLASS_NAMES.value.label, (_ref3 = {}, _defineProperty(_ref3, "".concat(FROM_LABEL.value, "--required"), needRequiredMark.value), _defineProperty(_ref3, "".concat(FROM_LABEL.value, "--colon"), hasColon.value), _defineProperty(_ref3, "".concat(FROM_LABEL.value, "--top"), hasLabel.value && (labelAlign.value === "top" || !labelWidth.value)), _defineProperty(_ref3, "".concat(FROM_LABEL.value, "--left"), labelAlign.value === "left" && labelWidth.value), _defineProperty(_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(labelWidth.value)) labelStyle = {
          width: "".concat(labelWidth.value, "px")
        };else labelStyle = {
          width: labelWidth.value
        };
      }
      return createVNode("div", {
        "class": labelClasses.value,
        "style": labelStyle
      }, [createVNode("label", {
        "for": props2["for"]
      }, [renderContent("label")])]);
    };
    var getDefaultIcon = function getDefaultIcon() {
      var resultIcon = function resultIcon(Icon) {
        return createVNode("span", {
          "class": CLASS_NAMES.value.status
        }, [createVNode(Icon, null, null)]);
      };
      var list = errorList.value;
      if (verifyStatus.value === ValidateStatus.SUCCESS) return resultIcon(CheckCircleFilledIcon$1);
      if (list !== null && list !== void 0 && list[0]) {
        var type = list[0].type || "error";
        var icon = {
          error: CloseCircleFilledIcon$1,
          warning: ErrorCircleFilledIcon$1
        }[type] || CheckCircleFilledIcon$1;
        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 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 = computed(function () {
      if (!showErrorMessage.value) return "";
      if (verifyStatus.value === 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 = computed(function () {
      return [CLASS_NAMES.value.controls, errorClasses.value];
    });
    var contentStyle = computed(function () {
      var contentStyle2 = {};
      if (labelWidth.value && labelAlign.value !== "top") {
        if (isNumber(labelWidth.value)) contentStyle2 = {
          marginLeft: "".concat(labelWidth.value, "px")
        };else contentStyle2 = {
          marginLeft: labelWidth.value
        };
      }
      return contentStyle2;
    });
    var errorList = ref([]);
    var successList = ref([]);
    var verifyStatus = ref(ValidateStatus.TO_BE_VALIDATED);
    var resetValidating = ref(false);
    var needResetField = ref(false);
    var resetHandler = function resetHandler() {
      needResetField.value = false;
      errorList.value = [];
      successList.value = [];
      verifyStatus.value = ValidateStatus.TO_BE_VALIDATED;
    };
    var getEmptyValue = function getEmptyValue() {
      var type = Object.prototype.toString.call(get(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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var resetType,
          _args = arguments;
        return _regeneratorRuntime.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(form === null || form === void 0 ? void 0 : form.data, props2.name, getEmptyValue());else if (resetType === "initial") lodashSet(form === null || form === void 0 ? void 0 : form.data, props2.name, initialValue.value);
              _context.next = 6;
              return 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 = 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 = 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(form === null || form === void 0 ? void 0 : form.rules, props2.name) || get(form === null || form === void 0 ? void 0 : form.rules, pRuleName) || [];
    });
    var analysisValidateResult = /*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(trigger) {
        var _result$rules;
        var result;
        return _regeneratorRuntime.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 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(errorMessages.value[key]);
                    var name2 = isString(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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(trigger, showErrorMessage2) {
        var _yield$analysisValida, innerSuccessList, innerErrorList, rules, resultList, allowSetValue;
        return _regeneratorRuntime.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 ? ValidateStatus.FAIL : ValidateStatus.SUCCESS;
              if (needResetField.value) resetHandler();
              resetValidating.value = false;
              return _context3.abrupt("return", _defineProperty({}, 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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(trigger) {
        var _yield$analysisValida2, innerErrorList, resultList;
        return _regeneratorRuntime.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({}, 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(validateMessage)) return;
      if (validateMessage.length === 0) {
        errorList.value = [];
        verifyStatus.value = ValidateStatus.SUCCESS;
      }
      errorList.value = validateMessage.map(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          result: false
        });
      });
      verifyStatus.value = ValidateStatus.FAIL;
    };
    var value = computed(function () {
      return (form === null || form === void 0 ? void 0 : form.data) && get(form === null || form === void 0 ? void 0 : form.data, props2.name);
    });
    var initialValue = ref(void 0);
    var _toRefs = toRefs(props2),
      name = _toRefs.name;
    var context = reactive({
      name: name,
      resetHandler: resetHandler,
      resetField: resetField,
      validate: validateHandler,
      validateOnly: validateOnly,
      setValidateMessage: setValidateMessage
    });
    onMounted(function () {
      initialValue.value = cloneDeep(value.value);
      form === null || form === void 0 ? void 0 : form.children.push(context);
    });
    onBeforeUnmount(function () {
      if (form) form.children = form === null || form === void 0 ? void 0 : form.children.filter(function (ctx) {
        return ctx !== context;
      });
    });
    watch(value, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5() {
      return _regeneratorRuntime.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
    });
    watch(function () {
      return [props2.name, JSON.stringify(props2.rules)].join(",");
    }, function () {
      validateHandler("change");
    });
    var freeShowErrorMessage = ref(void 0);
    var showErrorMessage = computed(function () {
      if (isBoolean(freeShowErrorMessage.value)) return freeShowErrorMessage.value;
      if (isBoolean(props2.showErrorMessage)) return props2.showErrorMessage;
      return form === null || form === void 0 ? void 0 : form.showErrorMessage;
    });
    var classes = computed(function () {
      var _ref11;
      return [CLASS_NAMES.value.formItem, FORM_ITEM_CLASS_PREFIX.value + (props2.name || ""), (_ref11 = {}, _defineProperty(_ref11, CLASS_NAMES.value.formItemWithHelp, helpNode.value), _defineProperty(_ref11, CLASS_NAMES.value.formItemWithExtra, extraNode.value), _ref11)];
    });
    var helpNode = computed(function () {
      var help = renderContent("help");
      if (help) return createVNode("div", {
        "class": CLASS_NAMES.value.help
      }, [help]);
      return null;
    });
    var extraNode = computed(function () {
      var _list$;
      var getExtraNode = function getExtraNode(content) {
        return 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( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6() {
        return _regeneratorRuntime.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);
      };
    }();
    provide(FormItemInjectionKey, {
      handleBlur: handleBlur
    });
    return function () {
      return createVNode("div", {
        "class": classes.value
      }, [renderLabel(), createVNode("div", {
        "class": contentClasses.value,
        "style": contentStyle.value
      }, [createVNode("div", {
        "class": CLASS_NAMES.value.controlsContent
      }, [renderContent("default"), renderSuffixIcon()]), [helpNode.value, extraNode.value]])]);
    };
  }
});

export { _FormItem as default };
//# sourceMappingURL=form-item.js.map
