<template>
  <div>
    <template v-if="keys.length>0">
    <div class="field is-horizontal" v-for="(v,i) in keys" :key="i">
    <div class="field-body">
      <div class="field is-narrow">
    <div class="control">
      <input class="input fs-14" type="text" placeholder="" v-model="keys[i]">
    </div>
  </div>
      <div class="field">
      <div class="control">
        <input class="input fs-14" type="text" placeholder="" v-model="values[i]">
      </div>
      </div>
      <div class="field is-narrow">
      <p class="control">
      <a @click="addAttr()">
        <SvgIcon v-bind="{name: 'add1.png', type: 'gray', size: 18}"></SvgIcon>
      </a>
      <a class="ml-2"  @click="remove(i)">
        <SvgIcon v-bind="{name: 'bin1.svg', type: 'gray', size: 18}"></SvgIcon>
      </a>
      <a class="ml-2" @click="jsonData(v, i)">
        <SvgIcon v-bind="{name: 'apps.svg', type: 'gray', size: 18}"></SvgIcon>
      </a>
    </p>
    </div>    
    </div>
    </div>
    </template>
    <div class="mb-6" v-else>
      <button class="button is-primary has-text-white" @click="addAttr()">Thêm thuộc tính</button>
    </div>
    <div class="buttons mt-5">
      <a class="button is-primary has-text-white" @click="update()">Cập nhật</a>
    </div>
    <Modal @close="comp=undefined" @update="doUpdate"
      v-bind="{component: comp, width: '40%', height: '300px', vbind: vbind}" v-if="comp"></Modal>
  </div>
  </template>
  <script>
  export default {
    props: ['field', 'close'],
    data() {
      return {
        keys: [],
        values: [],
        comp: undefined,
        vbind: undefined,
        current: undefined
      }
    },
    created() {
      Object.keys(this.field).map(v=>{
        this.keys.push(v)
        this.values.push(this.field[v])
      })
    },
    methods: {
      doUpdate(v) {
        this.values[this.current.i] = v
      },
      jsonData(v, i) {
        this.current = {v: v, i: i}
        this.vbind =  {field: this.$empty(this.values[i]) || typeof this.values[i] === 'string'? {} : this.values[i], close: true}
        this.comp = 'datatable/FieldAttribute'
      },
      addAttr() {
        this.keys.push(undefined)
        this.values.push(undefined)
      },
      remove(i) {
        this.$remove(this.keys, i)
        this.$remove(this.values, i)
      },
      update() {
        let obj = {}
        this.keys.map((v,i)=>{
          if(!this.$empty(v)) obj[v] = v.indexOf('__in')>0? this.values[i].split(',') : this.values[i]
        })
        this.$emit('update', obj)
        this.$emit('modalevent', {name: 'update', data: obj})
        if(this.close) this.$emit('close')
      }
    }
  }
  </script>