<template>
  <div class="q-pa-md">
    <q-table flat bordered :loading="!isLoaded" row-key="name" :selection="type" :selected="modelValue"
      @update:selected="$emit('update:modelValue', $event)" :filter="filter" :columns="columns" :rows="rows" />
  </div>
</template>
<script lang="ts">
import { useAsyncState } from '@vueuse/core';
import { api } from 'boot/axios';
import { computed } from 'vue';

export default {
  name: 'FieldList',
  props: {
    fields: Array,
    name: String,
    type: String,
    appId: Number,
    modelValue: Array,
    filter: String
  },
  emits: [
    'update:modelValue'
  ],
  setup(props) {
    // const rows = ref([]);
    // const isLoaded = ref(false);
    const columns = [
      { name: 'name', required: true, label: 'フィールド名', align: 'left', field: 'name', sortable: true },
      { name: 'code', label: 'フィールドコード', align: 'left', field: 'code', sortable: true },
      { name: 'type', label: 'フィールドタイプ', align: 'left', field: 'type', sortable: true }
    ]

    const { state : rows, isReady: isLoaded, isLoading } = useAsyncState((args) => {
      if (props.fields) {
        return props.fields.map(f => ({ name: f.label, objectType: 'field', ...f }));
      } else {
        return api.get('api/v1/appfields', {
          params: {
            app: props.appId
          }
        }).then(res => {
          console.log(res);
          return Object.values(res.data.properties).map(f => ({ name: f.label, objectType: 'field', ...f }));
        });
      }
    }, [{ name: '', objectType: '', type: '', code: '', label: '' }])
   
    return {
      columns,
      rows,
      // selected: ref([]),
      isLoaded
    }
  },

}
</script>
