<template>
  <el-form
    class="ui-form"
    :class="{'is-padding': innerPadding, 'is-viewable': !editable}"
    ref="form"
    :rules="innerRules"
    :model="model"
    :label-width="labelWidth"
    :label-position="labelPosition"
    @submit.native.prevent
  >
    <div class="ui-form__body">
      <slot></slot>
    </div>
    <div class="ui-form__toolbar" v-if="$slots.toolbar">
      <slot name="toolbar"></slot>
    </div>
  </el-form>
</template>
<script>
import Form from 'element-ui/lib/form'
import 'element-ui/lib/theme-chalk/form.css'

export default {
  name: 'UiForm',
  components: {
    ElForm: Form
  },
  inject: {
    UiDialog: {
      default: null
    }
  },
  props: {
    model: {
      type: Object,
      default: () => ({})
    },
    rules: {
      type: Object,
      default: () => ({})
    },
    editable: {
      type: Boolean,
      default: true
    },
    padding: {
      type: [String, Boolean]
    },
    labelWidth: {
      type: String,
      default: '60px'
    },
    labelPosition: {
      type: String,
      default: 'left'
    }
  },
  computed: {
    innerRules() {
      if (this.editable) {
        return this.rules
      }
      return {}
    },
    innerPadding() {
      if (typeof this.padding !== 'undefined') {
        return !!this.padding
      }
      if (this.UiDialog) {
        return true
      }
      return false
    }
  },
  methods: {
    validate() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((result) => {
          result ? resolve() : reject()
        })
      })
    },
    clearValidate() {
      this.$refs.form.clearValidate()
    },
    resetFields() {
      this.$refs.form.resetFields()
    }
  }
}
</script>
<style lang="less">
.ui-dialog {
  .el-dialog__body > .ui-form {
    .ui-form__body{
      padding: 20px;
    }
    .ui-form__toolbar{
      padding: 12px 20px;
      border-top: 1px solid #eee;
    }
  }
}
.ui-drawer {
  .ui-drawer__body > .ui-form {
    .ui-form__body{
      padding: 0 24px;
    }
    .ui-form__toolbar{
      padding: 0 24px 24px;
    }
  }
}
.ui-form {
  &.el-form--label-top .el-form-item__label {
    padding-bottom: 0;
  }
  &.el-form--label-top .el-form-item.is-required {
    .el-form-item__label{
      &:before{
        display: none;
      }
      &:after{
        content: '*';
        color: #F56C6C;
        margin-left: 4px;
      }
    }
  }
  &.is-viewable{
    .el-form-item{
      margin-bottom: 6px;
    }
  }
}
</style>
