import {Component, Prop, Watch, Vue } from 'vue-property-decorator';

import ComponentSelect from '../ComponentSelect/index.vue';
import Upload from '../Upload/index.vue';
import ColorSelector from '../ColorSelector/index.vue';
import SwitchBtn from '../SwitchBtn/index.vue';
import BaseSelect from '../BaseSelect/index.vue';

@Component({ name: 'formListMixin', components: { ComponentSelect, Upload, ColorSelector, SwitchBtn, BaseSelect } })
export default class DynamicFormMixin extends Vue {
  @Prop({ type: Array, default: () => [] }) value;
  @Prop({ type: Array, default: () => [] }) formControl;
  @Prop({ type: Object, default: () => ({}) }) formDefault;
  @Prop(String) name;

  list: object[] = [];

  @Watch('list')
  onListChange(val) {
    this.$emit('input', val);
  }
  @Watch('value', { immediate: true })
  onValueChange(val) {
    this.list = val;
  }

  getComponent(type) {
    let result = type;
    switch (type) {
    case 'text':
      result = 'Input';
      break;
    case 'select':
      result = 'BaseSelect';
      break;
    case 'checkbox':
      result = 'Checkbox';
      break;
    case 'textarea':
      result = 'Textarea';
      break;
    case 'number' :
      result = 'Number';
      break;
    case 'switch':
      result = 'SwitchBtn';
      break;
    }
    return result;
  }
  add() {
    const object = this.formControl.reduce((pre, cur) => {
      pre[cur.key] = this.formDefault[cur.key] || '';
      return pre;
    }, {});
    this.list.push(object);
  }
  del(index) {
    this.list.splice(index, 1);
  }
}