<template>
  <div class="kole-formmodal-mask" v-if="visible" @click.self="$emit('cancel')">
    <div class="kole-formmodal">
      <div class="kole-formmodal-head">
        <span>{{ title }}</span>
        <button class="kole-formmodal-close" @click="$emit('cancel')">×</button>
      </div>
      <div class="kole-formmodal-body">
        <div class="kole-form-row" v-for="f in fields" :key="f.key">
          <label class="kole-form-label"><span class="req" v-if="f.required">*</span>{{ f.label }}</label>
          <input
            class="kole-form-input"
            :class="{ 'is-error': errors[f.key] }"
            :value="form[f.key]"
            :placeholder="f.placeholder"
            @input="onInput(f.key, $event)"
          />
          <div class="kole-form-err" v-if="errors[f.key]">{{ errors[f.key] }}</div>
        </div>
      </div>
      <div class="kole-formmodal-foot">
        <button class="kole-btn" @click="$emit('cancel')">取消</button>
        <button class="kole-btn kole-btn--primary" @click="submit">提交</button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'KoleFormModal',
  props: {
    visible: { type: Boolean, default: false },
    title: { type: String, default: '表单' },
    fields: {
      type: Array,
      default: () => [
        { key: 'name', label: '姓名', required: true, placeholder: '请输入姓名' },
        { key: 'email', label: '邮箱', required: true, placeholder: 'name@example.com' },
        { key: 'role', label: '角色', placeholder: '如：管理员' }
      ]
    },
    value: { type: Object, default: () => ({}) }
  },
  data() {
    return { form: Object.assign({}, this.value), errors: {} };
  },
  watch: {
    visible(v) { if (v) { this.form = Object.assign({}, this.value); this.errors = {}; } }
  },
  methods: {
    onInput(key, e) {
      this.$set(this.form, key, e.target.value);
      if (this.errors[key]) this.$delete(this.errors, key);
    },
    submit() {
      var errors = {};
      this.fields.forEach(function (f) {
        var v = (this.form[f.key] || '').trim();
        if (f.required && !v) errors[f.key] = f.label + '不能为空';
        if (f.key === 'email' && v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) errors[f.key] = '邮箱格式不正确';
      }, this);
      if (Object.keys(errors).length) { this.errors = errors; return; }
      this.$emit('submit', Object.assign({}, this.form));
      this.$emit('cancel');
    }
  }
};
</script>

<style src="./FormModal.css"></style>
