<template>
  <div id="add">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :label-width="labelWidth"
      class="form"
      size="small"
      @submit.native.prevent
      :style="styles"
      :inline="inline"
    >
      <template v-for="(item, index) in fields">
        <template v-if="!loading">
          <el-form-item v-if="display(item)" :key="'form-field-' + index" :label="getField('label', item)" :prop="item.model" :required="item.required">
            <template v-if="!item.custom">
              <template v-if="item.type !== 'text'">
                <!-- <el-tooltip class="item" effect="dark" :content="item.tip" placement="top-start" :disabled="!item.tip"> -->
                <template v-if="item.type === `date` || item.type === `datetime`">
                  <el-date-picker
                    v-model="form[item.model]"
                    :type="item.type"
                    placeholder="选择择"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    v-bind="item.options"
                  >
                  </el-date-picker>
                </template>
                <template v-else-if="item.type === `year` || item.type === `week` || item.type === `day`">
                  <el-date-picker
                    v-model="form[item.model]"
                    :type="item.type"
                    placeholder="选择择"
                    :format="`${item.type === 'year' ? 'yyyy' : item.type === 'week' ? 'MM' : 'dd'}`"
                    :value-format="`${item.type === 'year' ? 'yyyy' : item.type === 'week' ? 'MM' : 'dd'}`"
                    v-bind="item.options"
                  >
                  </el-date-picker>
                </template>
                <template v-else-if="item.type === 'radio'">
                  <el-radio-group v-model="form[item.model]" size="mini" v-bind="item.options">
                    <slot name="radios" v-bind="{ item, form, fieldChange }"></slot>
                  </el-radio-group>
                </template>
                <template v-else-if="item.type === 'select'">
                  <el-select v-model="form[item.model]" v-bind="item.options" filterable clearable>
                    <slot name="options" v-bind="{ item, form, fieldChange }"></slot>
                  </el-select>
                </template>
                <template v-else-if="item.type === 'textarea'">
                  <el-input clearable v-model="form[item.model]" type="textarea" :autosize="{ minRows: 3, maxRows: 5 }"></el-input>
                </template>
                <template v-else-if="item.type === 'editor'">
                  <wang-editor v-model="form[item.model]"></wang-editor>
                </template>
                <template v-else-if="item.type === 'checkbox'">
                  <el-checkbox-group v-model="form[item.model]" v-bind="item.options">
                    <slot name="checkboxs" v-bind="{ item, form, fieldChange }"></slot>
                  </el-checkbox-group>
                </template>
                <template v-else>
                  <el-input
                    clearable
                    v-model="form[item.model]"
                    :type="getField('type', item)"
                    :placeholder="getField('placeholder', item)"
                    :show-password="getField('type', item) === 'password'"
                    v-bind="item.options"
                  ></el-input>
                </template>
                <!-- </el-tooltip> -->
              </template>
              <template v-else>
                {{ form[item.model] }}
              </template>
            </template>
            <template v-else>
              <slot name="custom" v-bind="{ item, form, fieldChange }"></slot>
            </template>
          </el-form-item>
        </template>
      </template>
      <el-form-item v-if="needSave" class="btn">
        <el-row type="flex" align="middle" justify="space-around">
          <el-col :span="6">
            <el-button type="primary" @click="save">{{ submitText }}</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item v-else>
        <slot name="submit"></slot>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import _ from 'lodash';
import wangEditor from './wang-editor.vue';
export default {
  name: 'add',
  props: {
    fields: { type: Array, default: () => [] },
    rules: { type: Object, default: () => {} },
    isNew: { type: Boolean, default: true },
    data: null,
    styles: { type: Object, default: () => {} },
    needSave: { type: Boolean, default: true },
    labelWidth: { type: String, default: '120px' },
    useEnter: { type: Boolean, default: true },
    submitText: { type: String, default: '保存' },
    inline: { type: Boolean, default: false },
    reset: { type: Boolean, default: true },
  },
  components: {
    wangEditor,
  },
  data: () => ({
    form: {},
    show: false,
    dateShow: false,
    loading: true,
  }),
  created() {
    if (this.useEnter) {
      document.onkeydown = () => {
        let key = window.event.keyCode;
        if (key == 13) {
          this.save();
        }
      };
    }
  },
  computed: {},
  mounted() {},
  watch: {
    fields: {
      handler(val) {
        this.checkType();
      },
      immediate: true,
    },
    data: {
      handler(val) {
        this.loading = true;
        if (val) this.$set(this, `form`, this.data);
        this.loading = false;
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    getField(item, data) {
      let res = _.get(data, item, null);
      if (item === 'type') res = res === null ? `text` : res;
      if (item === 'placeholder') res = res === null ? `请输入${data.label}` : res;
      if (item === 'required') res = res === null ? false : res;
      if (item === `error`) res = res === null ? `${data.label}错误` : res;
      return res;
    },
    save() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit(`save`, { isNew: this.isNew, data: JSON.parse(JSON.stringify(this.form)) });
          if (this.reset) this.$refs.form.resetFields();
        } else {
          console.warn('form validate error!!!');
        }
      });
    },
    fieldChange({ model, value }) {
      this.$set(this.form, model, value);
    },
    checkType() {
      let arr = this.fields.filter(fil => fil.type === 'checkbox');
      if (arr.length > 0 && this.isNew) {
        for (const item of arr) {
          this.$set(this.form, `${item.model}`, []);
        }
      }
    },
    display(field) {
      let dis = _.get(field, `display`);
      if (!_.isFunction(dis)) return true;
      else return dis(field, this.form);
    },
  },
};
</script>

<style lang="less" scoped>
.form {
  padding: 2rem 1rem;
  background: #fff;
  border-radius: 20px;
}
/deep/.btn .el-form-item__content {
  margin-left: 0 !important;
}
</style>
