<template>
  <div id="add">
    <el-form ref="form" :model="form" :label-width="labelWidth" class="form" size="small" @submit.native.prevent :style="styles" :inline="inline">
      <template v-for="(item, index) in fields">
        <el-form-item
          v-if="display(item)"
          :key="'form-field-' + index"
          :label="getField('label', item)"
          :prop="item.model"
          :required="item.required"
          :rules="getRules(item)"
        >
          <template v-if="!item.custom">
            <template v-if="item.type !== 'text'">
              <el-tooltip class="item" effect="dark" :content="item.remark" placement="top-start" :disabled="!item.remark">
                <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${item.type == 'datetime' ? ' HH:mm:ss' : ''}`"
                    :value-format="`yyyy-MM-dd${item.type == 'datetime' ? ' HH:mm:ss' : ''}`"
                    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 === 'number'">
                  <el-input-number v-model="form[item.model]" placeholder="" controls-position="right" style="width:200px"></el-input-number>
                </template>
                <template v-else-if="item.type === 'time'">
                  <el-time-picker v-model="form[item.model]" placeholder="请选择时间" format="HH:mm" value-format="HH:mm"></el-time-picker>
                </template>
                <template v-else-if="item.type === 'radio'">
                  <el-radio-group v-model="form[item.model]" size="mini" v-bind="item.options">
                    <template v-if="item.list">
                      <el-radio v-for="(i, iIndex) in item.list" :key="`radio-${iIndex}`" :label="i.value">{{ i.label }}</el-radio>
                    </template>
                    <template v-else>
                      <slot name="radios" v-bind="{ item, form, fieldChange }"></slot>
                    </template>
                  </el-radio-group>
                </template>
                <template v-else-if="item.type === 'checkbox'">
                  <el-checkbox-group v-model="form[item.model]" v-bind="item.options">
                    <template v-if="item.list">
                      <el-checkbox v-for="(i, iIndex) in item.list" :key="`checkbox-${iIndex}`" :label="i.value">{{ i.label }}</el-checkbox>
                    </template>
                    <template v-else>
                      <slot name="checkboxs" v-bind="{ item, form, fieldChange }"></slot>
                    </template>
                  </el-checkbox-group>
                </template>
                <template v-else-if="item.type === 'select'">
                  <el-select
                    v-model="form[item.model]"
                    v-bind="item.options"
                    filterable
                    clearable
                    @change="data => filterReturn(data, item)"
                    default-first-option
                  >
                    <template v-if="item.list">
                      <el-option v-for="(i, iIndex) in item.list" :key="`checkbox-${iIndex}`" :label="i.label" :value="i.value"></el-option>
                    </template>
                    <template v-else>
                      <slot name="options" v-bind="{ item, form, fieldChange }"> </slot>
                    </template>
                  </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>
                  <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>
              <template v-if="item.format">
                {{ item.format(form[item.model]) }}
              </template>
              <template v-else>
                {{ form[item.model] }}
              </template>
            </template>
          </template>
          <template v-else>
            <slot name="custom" v-bind="{ item, form, fieldChange }"></slot>
          </template>
        </el-form-item>
      </template>
      <el-form-item label="" v-if="needSave" class="btn">
        <el-row type="flex" align="middle" justify="start">
          <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 '@common/src/components/frame/wang-editor.vue';
export default {
  name: 'vform',
  model: {
    prop: 'form',
    event: 'change',
  },
  props: {
    fields: { type: Array, default: () => [] },
    rules: { type: Object, default: () => ({}) },
    isNew: { type: Boolean, default: true },
    form: { type: Object, default: () => {} },
    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: {},
    const _this = this;
    return {
      show: false,
      dateShow: false,
    };
  },
  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,
      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}`, []);
        }
      }
    },
    getRules(data) {
      let rules = [];
      const { model, required, label } = data;
      if (this.rules && _.get(this.rules, model)) {
        const r = _.get(this.rules, model);
        let has_required = false;
        if (_.isArray(r)) {
          for (const rule of r) {
            if (_.get(rule, 'required')) {
              has_required = true;
              break;
            }
          }
          rules = r;
        } else {
          if (_.get(rule, 'required')) has_required = true;
          rules.push(r);
        }
        if (!has_required) rules.push({ required: true, message: `请填写${label}`, trigger: 'blur' });
      } else {
        if (required) {
          let obj = { required: true, message: `请填写${label}`, trigger: 'blur' };
          rules.push(obj);
        }
      }
      return rules;
    },
    display(field) {
      // 添加noform属性,与列表fields共用
      let noform = _.get(field, `noform`);
      if (noform) return false;
      let dis = _.get(field, `display`);
      if (!_.isFunction(dis)) return true;
      else return dis(field, this.form);
    },
    filterReturn(data, item) {
      let { model, filterReturn } = item;
      if (filterReturn) this.$emit('filterReturn', { data, model });
    },
  },
};
</script>

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