<template>
  <div id="add">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="form" size="small" @submit.native.prevent :style="styles">
      <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 === `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">
                </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'}`"
                >
                </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 === '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-if="item.type === 'select'">
                <el-select v-model="form[item.model]" v-bind="item.options" filterable>
                  <slot name="options" v-bind="{ item, form, fieldChange }"></slot>
                </el-select>
              </template>
              <template v-else-if="item.type === 'textarea'">
                <el-input 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 === 'text'">
                {{ form[item.model] }}
              </template>
              <template v-else>
                <el-input
                  v-model="form[item.model]"
                  :type="getField('type', item)"
                  :placeholder="getField('placeholder', item)"
                  v-bind="item.options"
                ></el-input>
              </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">
        <el-row type="flex" align="middle" justify="space-around">
          <el-col :span="6">
            <el-button type="primary" @click="save">保存</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 '@frame/components/wang-editor';
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 },
  },
  components: {
    wangEditor,
  },
  data: () => ({
    form: {},
    show: false,
    dateShow: false,
    loading: true,
  }),
  created() {},
  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)) });
          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;
  background: #fff;
  border-radius: 20px;
}
</style>
