<!--
常规表单组件 - 供新增编辑使用
@Author: linqian
@Date: 2021-05-28 14:43
-->
<template>
  <div>
    <dg-row>
      <el-form :model="form" ref="form" label-suffix=":" :label-width="labelWidth">
        <dg-col v-for="(item, index) in formConfig" :key="index" :span="item.span || 12">
          <el-form-item :label="item.label" :prop="item.prop" :rules="item.rules">
            <!-- 通用 -->
            <template v-if="!item.custom">
              <component
                :is="item.component"
                v-model="form[item.prop]"
                :placeholder="setPlaceHolder(item)"
                v-bind="item.attr"
                clearable
              />
            </template>
            <!-- 自定义 -->
            <template v-else>
              <slot :name="item.prop" :value="form[item.prop]" :item="item"></slot>
            </template>
          </el-form-item>
        </dg-col>
      </el-form>
    </dg-row>
    <div v-footer>
      <dg-button @click="handleClose">取消</dg-button>
      <dg-button type="primary" @click="handleSave">保存</dg-button>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
export default {
  props: {
    config: {
      type: Array,
      default: () => []
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    // 类型，add || update
    type: String,
    // 详情
    detailInfo: {
      type: Object,
      default: () => {}
    }
  },
  components: {},
  data() {
    return {
      formConfig: this.config,
      form: {}
    };
  },
  computed: {},
  methods: {
    setPlaceHolder(item) {
      const { component, label } = item;
      const inputType = ['ElInput, DgInput'];
      const selectType = ['ElSelect', 'DgSelect', 'DgDatePicker'];
      let prefix;
      if (inputType.includes(component)) {
        prefix = '请输入';
      } else if (selectType.includes(component)) {
        prefix = '请选择';
      } else {
        prefix = '请输入';
      }

      return prefix + label;
    },
    handleClose() {
      this.$emit('close');
    },
    handleSave() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$emit('success', this.form, this.type);
        }
      });
    }
  },
  created() {
    // 编辑，字段回填
    if (Object.keys(this.detailInfo).length > 0) {
      this.form = _.cloneDeep(this.detailInfo);
    } else {
      for (let j = 0; j < this.formConfig.length; j++) {
        let { prop, value } = this.formConfig[j];
        this.$set(this.form, prop, value);
      }
    }
  },
  mounted() {}
};
</script>

<style lang='scss'>
</style>