/**
 * tdesign v0.39.1-alpha.1
 * (c) 2022 tdesign
 * @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 get from 'lodash/get';
import set from 'lodash/set';
import isNil from 'lodash/isNil';
import { CheckCircleFilledIcon, CloseCircleFilledIcon, ErrorCircleFilledIcon } from 'tdesign-icons-vue';
import lodashTemplate from 'lodash/template';
import { prefix } from '../config.js';
import { validate } from './form-model.js';
import props from './form-item-props.js';
import { CLASS_NAMES, FORM_ITEM_CLASS_PREFIX } from './const.js';
import mixins from '../utils/mixins.js';
import getConfigReceiverMixins from '../config-provider/config-receiver.js';
import '@babel/runtime/helpers/typeof';
import '../_chunks/dep-8526eb74.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 '../config-provider/context.js';
import 'lodash/merge';
import '../_common/js/global-config/default-config.js';
import '../_common/js/global-config/locale/zh_CN.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 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")).extend({
  name: "TFormItem",
  props: _objectSpread({}, props),
  inject: {
    form: {
      "default": void 0
    }
  },
  data: function data() {
    return {
      errorList: [],
      successList: [],
      verifyStatus: "not"
      /* TO_BE_VALIDATED */
      ,
      resetValidating: false,
      needResetField: false,
      initialValue: void 0
    };
  },
  computed: {
    needErrorMessage: function needErrorMessage() {
      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 [CLASS_NAMES.formItem, FORM_ITEM_CLASS_PREFIX + this.name, (_ref = {}, _defineProperty(_ref, CLASS_NAMES.formItemWithHelp, this.help), _defineProperty(_ref, CLASS_NAMES.formItemWithExtra, this.renderTipsInfo()), _ref)];
    },
    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 [CLASS_NAMES.label, (_ref2 = {}, _defineProperty(_ref2, "".concat(prefix, "-form__label--required"), this.needRequiredMark), _defineProperty(_ref2, "".concat(prefix, "-form__label--colon"), this.hasColon), _defineProperty(_ref2, "".concat(prefix, "-form__label--top"), labelAlign === "top" || !labelWidth), _defineProperty(_ref2, "".concat(prefix, "-form__label--left"), labelAlign === "left" && labelWidth), _defineProperty(_ref2, "".concat(prefix, "-form__label--right"), labelAlign === "right" && labelWidth), _ref2)];
    },
    errorClasses: function errorClasses() {
      if (!this.needErrorMessage) return "";

      if (this.verifyStatus === "success"
      /* SUCCESS */
      ) {
        return this.successBorder ? [CLASS_NAMES.success, CLASS_NAMES.successBorder].join(" ") : CLASS_NAMES.success;
      }

      var list = this.errorList;
      if (!list.length) return;
      var type = list[0].type || "error";
      return type === "error" ? CLASS_NAMES.error : CLASS_NAMES.warning;
    },
    disabled: function disabled() {
      return this.form.disabled;
    },
    contentClasses: function contentClasses() {
      var getErrorClass = this.errorClasses;
      return [CLASS_NAMES.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 (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 && get(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 = this.name.lastIndexOf(".") || -1;
      var pRuleName = this.name.slice(index + 1);
      return get(parent === null || parent === void 0 ? void 0 : parent.rules, this.name) || get(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$1(trigger) {
      var _this3 = this;

      return _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var rules, r, errorList;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this3.resetValidating = true;
                rules = trigger === "all" ? _this3.innerRules : _this3.innerRules.filter(function (item) {
                  return (item.trigger || "change") === trigger;
                });
                _context.next = 4;
                return validate(_this3.value, rules);

              case 4:
                r = _context.sent;
                errorList = r.filter(function (item) {
                  return item.result !== true;
                }).map(function (item) {
                  Object.keys(item).forEach(function (key) {
                    if (typeof item.message === "undefined" && _this3.errorMessages[key]) {
                      var compiled = lodashTemplate(_this3.errorMessages[key]);
                      item.message = compiled({
                        name: _this3.label,
                        validate: item[key]
                      });
                    }
                  });
                  return item;
                });
                _this3.errorList = errorList;
                _this3.successList = r.filter(function (item) {
                  return item.result === true && item.message && item.type === "success";
                });

                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 : r));

              case 12:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }))();
    },
    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()])]);
    },
    renderTipsInfo: function renderTipsInfo() {
      var h = this.$createElement;
      var helpVNode;

      if (this.help) {
        helpVNode = h("div", {
          "class": CLASS_NAMES.help
        }, [this.help]);
      }

      var list = this.errorList;

      if (this.needErrorMessage && list && list[0] && list[0].message) {
        return h("p", {
          "class": CLASS_NAMES.extra
        }, [list[0].message]);
      }

      if (this.successList.length) {
        return h("p", {
          "class": CLASS_NAMES.extra
        }, [this.successList[0].message]);
      }

      return helpVNode;
    },
    getDefaultIcon: function getDefaultIcon() {
      var h = this.$createElement;

      var resultIcon = function resultIcon(Icon) {
        return h("span", {
          "class": CLASS_NAMES.status
        }, [h(Icon)]);
      };

      var list = this.errorList;

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

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

      return null;
    },
    getIcon: function getIcon(statusIcon, slotStatusIcon, props2) {
      var h = this.$createElement;

      var resultIcon = function resultIcon(otherContent) {
        return h("span", {
          "class": CLASS_NAMES.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(get(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 _this4 = this;

      var parent = this.form;

      if (!this.name) {
        return;
      }

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

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

      Vue.nextTick(function () {
        if (_this4.resetValidating) {
          _this4.needResetField = true;
        } else {
          _this4.resetHandler();
        }
      });
    },
    resetHandler: function resetHandler() {
      this.needResetField = false;
      this.errorList = [];
      this.successList = [];
      this.verifyStatus = "not"
      /* TO_BE_VALIDATED */
      ;
    }
  },
  render: function render() {
    var h = arguments[0];
    return h("div", {
      "class": this.classes
    }, [this.getLabel(), h("div", {
      "class": this.contentClasses,
      "style": this.contentStyle
    }, [h("div", {
      "class": CLASS_NAMES.controlsContent
    }, [this.$slots["default"], this.getSuffixIcon()]), this.renderTipsInfo()])]);
  }
});

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