/**
 * tdesign v0.32.0
 * (c) 2021 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 { 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-1db5c91c.js';
import 'lodash/isEmpty';
import '../utils/helper.js';
import '@babel/runtime/helpers/objectWithoutProperties';
import '@babel/runtime/helpers/slicedToArray';
import 'lodash/camelCase';
import '../config-provider/zh_CN_config.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;

(function (VALIDATE_STATUS2) {
  VALIDATE_STATUS2["TO_BE_VALIDATED"] = "not";
  VALIDATE_STATUS2["SUCCESS"] = "success";
  VALIDATE_STATUS2["FAIL"] = "fail";
})(VALIDATE_STATUS || (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: VALIDATE_STATUS.TO_BE_VALIDATED,
      resetValidating: false,
      needResetField: false,
      initialValue: void 0
    };
  },
  computed: {
    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() {
      var parent = this.form;
      if (!parent.showErrorMessage) return "";

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

      if (!this.errorList.length) return;
      var type = this.errorList[0].type || "error";
      return type === "error" ? CLASS_NAMES.error : CLASS_NAMES.warning;
    },
    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 parent = this.form;
      return get(parent === null || parent === void 0 ? void 0 : parent.rules, this.name) || this.rules || [];
    }
  },
  watch: {
    value: function value() {
      this.validate("change");
    }
  },
  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: {
    validate: function validate$1(trigger) {
      var _this = 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:
                _this.resetValidating = true;
                rules = trigger === "all" ? _this.innerRules : _this.innerRules.filter(function (item) {
                  return (item.trigger || "change") === trigger;
                });
                _context.next = 4;
                return validate(_this.value, rules);

              case 4:
                r = _context.sent;
                errorList = r.filter(function (item) {
                  return item.result !== true;
                });
                _this.errorList = errorList;
                _this.successList = r.filter(function (item) {
                  return item.result === true && item.message && item.type === "success";
                });

                if (rules.length) {
                  _this.verifyStatus = errorList.length ? VALIDATE_STATUS.FAIL : VALIDATE_STATUS.SUCCESS;
                } else {
                  _this.verifyStatus = VALIDATE_STATUS.TO_BE_VALIDATED;
                }

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

                _this.resetValidating = false;
                return _context.abrupt("return", _defineProperty({}, _this.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 parent = this.form;
      var helpVNode;

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

      var list = this.errorList;

      if (parent.showErrorMessage && 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, {
          "attrs": {
            "size": "20px"
          }
        })]);
      };

      var list = this.errorList;

      if (this.verifyStatus === VALIDATE_STATUS.SUCCESS) {
        return resultIcon(CheckCircleFilledIcon);
      }

      if (list && list[0]) {
        var type = this.errorList[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]);
      };

      var withoutIcon = function withoutIcon() {
        return h("span", {
          "class": [CLASS_NAMES.status, "".concat(CLASS_NAMES.status, "-without-icon")]
        });
      };

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

      if (statusIcon === false) {
        return withoutIcon();
      }

      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;
      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 Array]") {
        emptyValue = [];
      }

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

      return emptyValue;
    },
    resetField: function resetField() {
      var _this2 = 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 (_this2.resetValidating) {
          _this2.needResetField = true;
        } else {
          _this2.resetHandler();
        }
      });
    },
    resetHandler: function resetHandler() {
      this.needResetField = false;
      this.errorList = [];
      this.successList = [];
      this.verifyStatus = VALIDATE_STATUS.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
