/**
 * ldesign v0.2.2
 * (c) 2022年9月20日 swimly
 * @license MIT
 */

import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import _regeneratorRuntime from '@babel/runtime/regenerator';
import Vue from 'vue';
import cloneDeep from 'lodash/cloneDeep';
import lodashGet from 'lodash/get';
import lodashSet from 'lodash/set';
import isNil from 'lodash/isNil';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } from '@ldesign/icons-vue';
import lodashTemplate from 'lodash/template';
import '../../chunks/index.js';
import { validate } from './model.js';
import { FormItemProps } from './props.js';
import mixins from '../../utils/mixins.js';
import getConfigReceiverMixins, { getGlobalIconMixins } from '../config-provider/config-receiver.js';
import { renderLNodeJSX } from '../../utils/render-node.js';
import { l as log } from '../../chunks/log.js';
import '@babel/runtime/helpers/typeof';
import '../../chunks/_commonjsHelpers.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 'lodash/mergeWith';
import 'lodash';
import '../config-provider/context.js';
import '../../chunks/zh_CN.js';
import '../config-provider/type.js';
import 'lodash/kebabCase';

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 VALIDATE_STATUS = /* @__PURE__ */function (VALIDATE_STATUS2) {
  VALIDATE_STATUS2["TO_BE_VALIDATED"] = "not";
  VALIDATE_STATUS2["SUCCESS"] = "success";
  VALIDATE_STATUS2["FAIL"] = "fail";
  return VALIDATE_STATUS2;
}(VALIDATE_STATUS || {});
var _FormItem = mixins(getConfigReceiverMixins("form"), getGlobalIconMixins()).extend({
  name: "LFormItem",
  props: _objectSpread({}, FormItemProps),
  inject: {
    form: {
      "default": void 0
    }
  },
  provide: function provide() {
    return {
      tFormItem: this
    };
  },
  data: function data() {
    return {
      errorList: [],
      successList: [],
      verifyStatus: "not"
      /* TO_BE_VALIDATED */
      ,
      resetValidating: false,
      needResetField: false,
      initialValue: void 0,
      freeShowErrorMessage: void 0
    };
  },
  computed: {
    needErrorMessage: function needErrorMessage() {
      if (this.freeShowErrorMessage !== void 0) return this.freeShowErrorMessage;
      if (typeof this.showErrorMessage === "boolean") return this.showErrorMessage;
      var parent = this.form;
      return parent === null || parent === void 0 ? void 0 : parent.showErrorMessage;
    },
    classes: function classes() {
      var _ref;

      return ["".concat(this.componentName, "__item"), "".concat(this.componentName, "-item__").concat(this.name || ""), (_ref = {}, _defineProperty(_ref, "".concat(this.componentName, "__item-with-help"), this.help), _defineProperty(_ref, "".concat(this.componentName, "__item-with-extra"), this.extraNode), _ref)];
    },
    extraNode: function extraNode() {
      var h = this.$createElement;
      var list = this.errorList;

      if (this.needErrorMessage && list && list[0] && list[0].message) {
        return h("div", {
          "class": "".concat(this.classPrefix, "-input__extra")
        }, [list[0].message]);
      }

      if (this.successList.length) {
        return h("div", {
          "class": "".concat(this.classPrefix, "-input__extra")
        }, [this.successList[0].message]);
      }

      return null;
    },
    labelClasses: function labelClasses() {
      var _ref2;

      var parent = this.form;
      var labelAlign = isNil(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
      var labelWidth = isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
      return ["".concat(this.componentName, "__label"), (_ref2 = {}, _defineProperty(_ref2, "".concat(this.componentName, "__label--required"), this.needRequiredMark), _defineProperty(_ref2, "".concat(this.componentName, "__label--colon"), this.hasColon), _defineProperty(_ref2, "".concat(this.componentName, "__label--top"), this.getLabelContent() && (labelAlign === "top" || !labelWidth)), _defineProperty(_ref2, "".concat(this.componentName, "__label--left"), labelAlign === "left" && labelWidth), _defineProperty(_ref2, "".concat(this.componentName, "__label--right"), labelAlign === "right" && labelWidth), _ref2)];
    },
    errorClasses: function errorClasses() {
      if (!this.needErrorMessage) return "";

      if (this.verifyStatus === "success"
      /* SUCCESS */
      ) {
        return this.successBorder ? [this.commonStatusClassName.success, "".concat(this.componentName, "--success-border")].join(" ") : this.commonStatusClassName.success;
      }

      var list = this.errorList;
      if (!list.length) return;
      var type = list[0].type || "error";
      return type === "error" ? this.commonStatusClassName.error : this.commonStatusClassName.warning;
    },
    disabled: function disabled() {
      return this.form.disabled;
    },
    contentClasses: function contentClasses() {
      var getErrorClass = this.errorClasses;
      return ["".concat(this.componentName, "__controls"), getErrorClass];
    },
    contentStyle: function contentStyle() {
      var parent = this.form;
      var labelAlign = isNil(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
      var labelWidth = isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
      var contentStyle = {};

      if (this.getLabelContent() && labelWidth && labelAlign !== "top") {
        if (typeof labelWidth === "number") {
          contentStyle = {
            marginLeft: "".concat(labelWidth, "px")
          };
        } else {
          contentStyle = {
            marginLeft: labelWidth
          };
        }
      }

      return contentStyle;
    },
    value: function value() {
      var parent = this.form;
      return parent && parent.data && lodashGet(parent.data, this.name);
    },
    hasColon: function hasColon() {
      var parent = this.form;
      return !!(parent && parent.colon && this.getLabelContent());
    },
    needRequiredMark: function needRequiredMark() {
      var requiredMark = this.$props.requiredMark;
      if (typeof requiredMark === "boolean") return requiredMark;
      var parent = this.form;
      var parentRequiredMark = (parent === null || parent === void 0 ? void 0 : parent.requiredMark) === void 0 ? this.global.requiredMark : parent.requiredMark;
      var isRequired = this.innerRules.filter(function (rule) {
        return rule.required;
      }).length > 0;
      return Boolean(parentRequiredMark && isRequired);
    },
    innerRules: function innerRules() {
      var _this$rules;

      var parent = this.form;
      if ((_this$rules = this.rules) !== null && _this$rules !== void 0 && _this$rules.length) return this.rules || [];
      if (!this.name) return [];
      var index = String(this.name || "").lastIndexOf(".") || -1;
      var pRuleName = String(this.name || "").slice(index + 1);
      return lodashGet(parent === null || parent === void 0 ? void 0 : parent.rules, this.name) || lodashGet(parent === null || parent === void 0 ? void 0 : parent.rules, pRuleName) || [];
    },
    errorMessages: function errorMessages() {
      var _this$form$errorMessa;

      return (_this$form$errorMessa = this.form.errorMessage) !== null && _this$form$errorMessa !== void 0 ? _this$form$errorMessa : this.global.errorMessage;
    }
  },
  watch: {
    value: function value() {
      this.validate("change");
    }
  },
  created: function created() {
    this.addWatch();
  },
  mounted: function mounted() {
    this.initialValue = cloneDeep(this.value);
    this.form.$emit("form-item-created", this);
  },
  beforeDestroy: function beforeDestroy() {
    this.form.$emit("form-item-destroyed", this);
  },
  methods: {
    addWatch: function addWatch() {
      var _this = this;

      if (this.disabled === void 0) return;
      this.$watch("disabled", function (val) {
        _this.$nextTick(function () {
          _this.setChildrenDisabled(val, _this.$children);
        });
      }, {
        immediate: true
      });
    },
    setChildrenDisabled: function setChildrenDisabled(disabled, children) {
      var _this2 = this;

      children.forEach(function (item) {
        var _this2$form$controlle, _item$$children;

        if ((_this2$form$controlle = _this2.form.controlledComponents) !== null && _this2$form$controlle !== void 0 && _this2$form$controlle.includes(item.$options.name)) {
          item.$data.formDisabled = disabled;
        }

        if ((_item$$children = item.$children) !== null && _item$$children !== void 0 && _item$$children.length) {
          _this2.setChildrenDisabled(disabled, item.$children);
        }
      });
    },
    setValidateMessage: function setValidateMessage(validateMessage) {
      if (!validateMessage || !Array.isArray(validateMessage)) return;

      if (validateMessage.length === 0) {
        this.errorList = [];
        this.verifyStatus = "success"
        /* SUCCESS */
        ;
        return;
      }

      this.errorList = validateMessage;
      this.verifyStatus = "fail"
      /* FAIL */
      ;
    },
    validate: function validate(trigger) {
      var _arguments = arguments,
          _this3 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var showErrorMessage, source, _yield$_this3$analysi, errorList, resultList, successList, rules, allowSetValue;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                showErrorMessage = _arguments.length > 1 && _arguments[1] !== undefined ? _arguments[1] : true;
                source = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : "submit-event";
                _this3.freeShowErrorMessage = source === "submit-function" ? showErrorMessage : void 0;
                _this3.resetValidating = true;
                _context.next = 6;
                return _this3.analysisValidateResult(trigger);

              case 6:
                _yield$_this3$analysi = _context.sent;
                errorList = _yield$_this3$analysi.errorList;
                resultList = _yield$_this3$analysi.resultList;
                successList = _yield$_this3$analysi.successList;
                rules = _yield$_this3$analysi.rules;
                allowSetValue = _yield$_this3$analysi.allowSetValue;

                if (allowSetValue) {
                  _this3.errorList = errorList;
                  _this3.successList = successList;
                }

                if (rules.length) {
                  _this3.verifyStatus = errorList.length ? "fail"
                  /* FAIL */
                  : "success"
                  /* SUCCESS */
                  ;
                } else {
                  _this3.verifyStatus = "not"
                  /* TO_BE_VALIDATED */
                  ;
                }

                if (_this3.needResetField) {
                  _this3.resetHandler();
                }

                _this3.resetValidating = false;
                return _context.abrupt("return", _defineProperty({}, _this3.name, errorList.length === 0 ? true : resultList));

              case 17:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }))();
    },
    validateOnly: function validateOnly(trigger) {
      var _this4 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var _yield$_this4$analysi, errorList, resultList;

        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                _context2.next = 2;
                return _this4.analysisValidateResult(trigger);

              case 2:
                _yield$_this4$analysi = _context2.sent;
                errorList = _yield$_this4$analysi.errorList;
                resultList = _yield$_this4$analysi.resultList;
                return _context2.abrupt("return", _defineProperty({}, _this4.name, errorList.length === 0 ? true : resultList));

              case 6:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }))();
    },
    analysisValidateResult: function analysisValidateResult(trigger) {
      var _this5 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3() {
        var result;
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                result = {
                  successList: [],
                  errorList: [],
                  rules: [],
                  resultList: [],
                  allowSetValue: false
                };
                result.rules = trigger === "all" ? _this5.innerRules : _this5.innerRules.filter(function (item) {
                  return (item.trigger || "change") === trigger;
                });

                if (!(_this5.innerRules.length && !result.rules.length)) {
                  _context3.next = 4;
                  break;
                }

                return _context3.abrupt("return", result);

              case 4:
                result.allowSetValue = true;
                _context3.next = 7;
                return validate(_this5.value, result.rules);

              case 7:
                result.resultList = _context3.sent;
                result.errorList = result.resultList.filter(function (item) {
                  return item.result !== true;
                }).map(function (item) {
                  Object.keys(item).forEach(function (key) {
                    if (typeof item.message === "undefined" && _this5.errorMessages[key]) {
                      var compiled = lodashTemplate(_this5.errorMessages[key]);
                      var name = typeof _this5.label === "string" ? _this5.label : _this5.name;
                      item.message = compiled({
                        name: name,
                        validate: item[key]
                      });
                    }
                  });
                  return item;
                });
                result.successList = result.resultList.filter(function (item) {
                  return item.result === true && item.message && item.type === "success";
                });
                return _context3.abrupt("return", result);

              case 11:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }))();
    },
    getLabelContent: function getLabelContent() {
      if (typeof this.label === "function") {
        return this.label(this.$createElement);
      }

      if (typeof this.$scopedSlots.label === "function") {
        return this.$scopedSlots.label(null);
      }

      return this.label;
    },
    getLabel: function getLabel() {
      var h = this.$createElement;
      var parent = this.form;
      var labelWidth = isNil(this.labelWidth) ? parent === null || parent === void 0 ? void 0 : parent.labelWidth : this.labelWidth;
      var labelAlign = isNil(this.labelAlign) ? parent === null || parent === void 0 ? void 0 : parent.labelAlign : this.labelAlign;
      if (Number(labelWidth) === 0) return;
      var labelStyle = {};

      if (labelWidth && labelAlign !== "top") {
        if (typeof labelWidth === "number") {
          labelStyle = {
            width: "".concat(labelWidth, "px")
          };
        } else {
          labelStyle = {
            width: labelWidth
          };
        }
      }

      return h("div", {
        "class": this.labelClasses,
        "style": labelStyle
      }, [h("label", {
        "attrs": {
          "for": this["for"]
        }
      }, [this.getLabelContent()])]);
    },
    getDefaultIcon: function getDefaultIcon() {
      var _this6 = this;

      var h = this.$createElement;

      var resultIcon = function resultIcon(Icon) {
        return h("span", {
          "class": "".concat(_this6.componentName, "__status")
        }, [h(Icon)]);
      };

      var list = this.errorList;

      var _this$useGlobalIcon = this.useGlobalIcon({
        CheckCircleFilledIcon: CheckCircleFilledIcon,
        CloseCircleFilledIcon: CloseCircleFilledIcon,
        ErrorCircleFilledIcon: ErrorCircleFilledIcon
      }),
          CheckCircleFilledIcon$1 = _this$useGlobalIcon.CheckCircleFilledIcon,
          CloseCircleFilledIcon$1 = _this$useGlobalIcon.CloseCircleFilledIcon,
          ErrorCircleFilledIcon$1 = _this$useGlobalIcon.ErrorCircleFilledIcon;

      if (this.verifyStatus === "success"
      /* SUCCESS */
      ) {
        return resultIcon(CheckCircleFilledIcon$1);
      }

      if (list && list[0]) {
        var type = list[0].type || "error";
        var icon = {
          error: CloseCircleFilledIcon$1,
          warning: ErrorCircleFilledIcon$1
        }[type] || CheckCircleFilledIcon$1;
        return resultIcon(icon);
      }

      return null;
    },
    getIcon: function getIcon(statusIcon, slotStatusIcon, props2) {
      var _this7 = this;

      var h = this.$createElement;

      var resultIcon = function resultIcon(otherContent) {
        return h("span", {
          "class": "".concat(_this7.componentName, "__status")
        }, [otherContent]);
      };

      if (statusIcon === true) {
        return this.getDefaultIcon();
      }

      if (typeof statusIcon === "function") {
        return resultIcon(statusIcon(this.$createElement, props2));
      }

      if (typeof slotStatusIcon === "function") {
        return resultIcon(slotStatusIcon(null));
      }

      return null;
    },
    getSuffixIcon: function getSuffixIcon() {
      var parent = this.form;
      var statusIcon = this.statusIcon;
      var slotStatusIcon = this.$scopedSlots.statusIcon;
      var parentStatusIcon = parent.statusIcon;
      var parentSlotStatusIcon = parent.$scopedSlots.statusIcon;
      if (statusIcon === false) return;
      var resultIcon = this.getIcon(statusIcon, slotStatusIcon);
      if (resultIcon) return resultIcon;
      if (resultIcon === false) return;
      resultIcon = this.getIcon(parentStatusIcon, parentSlotStatusIcon, this.$props);
      if (resultIcon) return resultIcon;
    },
    getEmptyValue: function getEmptyValue() {
      var parent = this.form;
      var type = Object.prototype.toString.call(lodashGet(parent.data, this.name));
      var emptyValue;

      if (type === "[object String]") {
        emptyValue = "";
      }

      if (type === "[object Array]") {
        emptyValue = [];
      }

      if (type === "[object Object]") {
        emptyValue = {};
      }

      return emptyValue;
    },
    resetField: function resetField() {
      var _this8 = this;

      var resetType = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "initial";
      var parent = this.form;

      if (!this.name && this.label) {
        log.warn("Form", "name is required for validating.");
        return;
      }

      var tResetType = resetType || parent.resetType;

      if (tResetType === "empty") {
        lodashSet(parent.data, this.name, this.getEmptyValue());
      }

      if (tResetType === "initial") {
        lodashSet(parent.data, this.name, this.initialValue);
      }

      Vue.nextTick(function () {
        if (_this8.resetValidating) {
          _this8.needResetField = true;
        } else {
          _this8.resetHandler();
        }
      });
    },
    resetHandler: function resetHandler() {
      this.needResetField = false;
      this.errorList = [];
      this.successList = [];
      this.verifyStatus = "not"
      /* TO_BE_VALIDATED */
      ;
    }
  },
  render: function render() {
    var h = arguments[0];
    var helpNode = renderLNodeJSX(this, "help");
    return h("div", {
      "class": this.classes
    }, [this.getLabel(), h("div", {
      "class": this.contentClasses,
      "style": this.contentStyle
    }, [h("div", {
      "class": "".concat(this.componentName, "__controls-content")
    }, [this.$slots["default"], this.getSuffixIcon()]), helpNode && h("div", {
      "class": "".concat(this.classPrefix, "-input__help")
    }, [helpNode]), this.extraNode])]);
  }
});

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