<template>
  <el-form-item v-bind="$attrs" v-on="$listeners" :label="label">
    <slot v-if="title" name="label">
      <div class="label">
        <div>
          <i
            v-if="(firstStarMark || startMark) && !lastStarMark"
            class="first-star-mark"
          >
            *
          </i>
          {{ title }}
          <i v-if="lastStarMark" class="last-star-mark">*</i>
        </div>

        <slot name="title"></slot>
      </div>
    </slot>
    <slot />
  </el-form-item>
</template>

<script>
export default {
  name: 'AdbFormItem',
  provide() {
    return {
      elFormItem: this,
    };
  },
  inject: ['elForm'],
  props: {
    title: {
      type: String,
      default: '',
    },
    lastStarMark: {
      type: Boolean,
      default: false,
    },
    startMark: {
      type: Boolean,
      default: false,
    },
    label: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      firstStarMark: false,
      elForm: null,
    };
  },
  created() {
    if (this.title && this.$attrs.prop) {
      const prop = this.elForm.rules[this.$attrs.prop];
      if (!prop) return;
      if (Array.isArray(prop)) {
        for (const item of prop) {
          if (item.required) {
            this.firstStarMark = true;
            return;
          }
        }
      } else if (prop.required) this.firstStarMark = true;
    }
  },
};
</script>

<style lang="scss" scoped>
.first-star-mark {
  color: #f47367;
  margin-right: 4px;
}

.last-star-mark {
  color: #f47367;
  margin-left: 4px;
}

.el-form-item.is-required:not(.is-no-asterisk)
  /deep/
  .el-form-item__label::before {
  content: '*' !important;
  color: #f47367 !important;
  margin-right: 4px !important;
}
</style>
