<template>
<!-- <el-form-item :prop="model" :label="label" :rules="rules"> -->
<div class="honjo-form-render-table">
<div v-for="(data, i) in value" :key="data._seq_key || (data._seq_key = genKey())" class="honjo-form-render-table__row">
  <template  v-for="row in def.controls">
    <form-control :key="row.key" :def="row" :row-form="data" :prop="model + '.' + i" v-if="exists(row, data)"></form-control>
  </template>
  <span class="honjo-form-render-table__remove" @click="onRemove(i)" v-if="!disabled && removable"><i class="el-icon-remove"></i></span>
</div>
<el-button type="primary" plain size="small" @click="onAdd" class="honjo-form-render-table__add" v-if="!disabled && !exceed">{{addBtnText}}</el-button>
</div>
<!-- </el-form-item> -->
</template>

<script lang="ts">

import { Vue, Component, Prop, Ref, Inject } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import { FormDef, FormOptions, TableDef, TableOptions } from '../../type'
import FieldMixins from './FieldMixins'

let index = 1

@Component({
  components: {
    'form-control': () => import('../index.vue')
  }
})
export default class TableControl extends mixins(FieldMixins) {
  @Inject() exists!: (row: any, rowForm?: Record<string, any>) => boolean

  get addBtnText () {
    return this.options?.addBtnText || '新 增'
  }

  get options () {
    return Object.assign(new TableOptions(), this.def?.options)
  }

  get exceed () {
    return this.options?.limit && Array.isArray(this.value) && this.options.limit <= this.value.length
  }

  get removable () {
    const min = Number(this.options?.min || 0)
    return (this.value || []).length > min
  }

  onAdd () {
    // eslint-disable-next-line
    this.value.push({ _seq_key: this.genKey() })
  }

  onRemove (i: number) {
    this.value.splice(i, 1)
  }

  genKey () {
    return Date.now() + '_' + index++
  }

  def!: TableDef
}
</script>
