<template>
  <div>
      <div class="field is-horizontal mt-6 pt-4">
  <div class="field-body">
    <div class="field is-narrow">
      <label class="label">Code <span class="has-text-danger"> * </span> </label>
      <p class="control">
        <input class="input" type="text" placeholder="" v-model="record.code" id="code">
      </p>
    </div>
    <div class="field is-narrow">
      <label class="label">Name <span class="has-text-danger"> * </span> </label>
      <p class="control">
        <input class="input" type="text" placeholder="" v-model="record.name" id="code">
      </p>
    </div>
    </div>
  </div>
  <div class="columns mx-0">
    <div class="column is-8">
  <div class="mt-5 mb-3">
    <Caption v-bind="{title: 'Required documents', type: 'has-text-primary'}"></Caption>
  </div>
  <div class="field is-grouped" v-for="(v,i) in array">
      <div class="control">   
      <SearchBox v-bind="{api:'documenttype', field:'name', column:['name'], first:true, optionid:v.doctype, position: 'is-top-left'}" 
    @option="documentSelected('_doctype', $event, v)"></SearchBox>
  </div>
  <div class="control pl-5">
     <a class="mr-4" @click="add()">
        <SvgIcon v-bind="{name: 'add1.png', type: 'dark', size: 20}"></SvgIcon>
      </a>
      <a @click="remove(v, i)">
        <SvgIcon v-bind="{name: 'bin1.svg', type: 'dark', size: 20}"></SvgIcon>
      </a>
    </div>
  </div>
    </div>
  </div>
  <div class="mt-5">
    <button class="button is-primary has-text-white" @click="update()">Save</button>
  </div>
</div>
</template>
<script setup>
  import { onMounted } from 'vue'
  const { $getdata, $copy,  $resetNull, $insertrow, $updaterow, $snackbar, $remove, $deleteapi} = useNuxtApp()
  var props = defineProps({
    api: String,
    pagename: String,
    row: Object,
    prefix: String
  })
  const emit = defineEmits(['close', 'modalevent'])
  var array = ref([{}])
  var record = $copy( props.row || {})
  if(props.row) {
    let arr = await $getdata('phasedoctype', {phase: props.row.id})
    if(arr.length>0) array.value = arr
  }
  async function update() {
    let data = $resetNull(record)
    let rs = data.id? await $updaterow(props.api, data, undefined, props.pagename)
    : await $insertrow(props.api, data, undefined, props.pagename)
    if(rs==='error') return $snackbar(rs)
    let arr = array.value.filter(v=>v.doctype)
    arr.map(v=>v.phase = rs.id)
    await $insertrow('phasedoctype', arr)
    emit('modalevent', {name: 'dataevent', data: rs})
    emit('close')
  }
  function documentSelected(attr, obj, v) {
    v[attr] = obj
    if(obj) v.doctype = obj.id
  }
  function add() {
    array.value.push({})
  }
  async function remove(v, i) {
    if(v.id) await $deleteapi('phasedoctype', v.id)
    $remove(array.value, i)
    if(array.value.length===0) array.value = [{}]
  }
  onMounted(()=> {
    document.getElementById('code').focus()
  })
</script>