<template>
  <div id="vForm">
    <van-form @submit="onSubmit">
      <template v-for="(f, fi) in fields">
        <template v-if="!f.type || f.type === 'input'">
          <van-field
            :key="`${fi}.${f.model}`"
            v-model="value[f.model]"
            :label="f.label"
            :placeholder="`${f.label}`"
            :rules="f.rules ? f.rules : []"
            :required="f.required"
          />
        </template>
        <template v-if="f.type === 'date'">
          <v-date :key="`${fi}.${f.model}`" v-model="value[f.model]" :label="f.label" :required="f.required"></v-date>
        </template>
        <template v-if="f.type === 'select'">
          <v-select
            :key="`${fi}.${f.model}`"
            v-model="value[f.model]"
            :label="f.label"
            :list="getSelectList(f.model)"
            :labelKey="f.selectKey"
            :prop="f.selectProp"
            :required="f.required"
          ></v-select>
        </template>
        <template v-if="f.type === 'textarea'">
          <van-field
            :key="`${fi}.${f.model}`"
            v-model="value[f.model]"
            :label="f.label"
            rows="2"
            autosize
            type="textarea"
            :placeholder="`请输入${f.label}`"
            :required="f.required"
          />
        </template>
      </template>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
const _ = require('lodash');
import vDate from '@/components/vdate.vue';
import vSelect from '@/components/vselect.vue';
import { mapState, createNamespacedHelpers } from 'vuex';
export default {
  name: 'vForm',
  props: {
    value: { type: Object, required: true },
    fields: { type: Array, default: () => [] },
  },

  components: { vDate, vSelect },
  data: function () {
    return {};
  },
  created() {},
  methods: {
    onSubmit() {
      // 进入submit后,只能说明,有rules的是按要求输入的,其余的select,date还未验证,需要此处验证
      const needCheck = this.fields.filter((f) => f.required);
      const checkResult = this.checkRequired(needCheck);
      if (!checkResult) return;
      this.$emit('submit', _.cloneDeep(this.value));
    },
    checkRequired(checkList) {
      let res = true;
      for (const field of checkList) {
        const { model, label } = field;
        if (!this.value[model]) {
          this.$toast({ type: 'fail', message: `请完善${label}项` });
          res = false;
          break;
        }
      }
      return res;
    },
    getSelectList(model) {
      const selectList = _.get(this.$attrs, `${model}List`, []);
      return selectList;
    },
  },
  computed: {
    ...mapState(['user']),
    pageTitle() {
      return `${this.$route.meta.title}`;
    },
  },
  metaInfo() {
    return { title: this.$route.meta.title };
  },
};
</script>

<style lang="less" scoped></style>
