<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"
      :pagination="pagination"
      style="max-height: 55vh;"/>
  </div>
</template>
<script lang="ts">
import { useAsyncState } from '@vueuse/core';
import { api } from 'boot/axios';
import { computed ,Prop,PropType,ref} from 'vue';
import {IField} from 'src/types/ComponentTypes';

export default {
  name: 'FieldList',
  props: {
    fields: Array as PropType<IField[]>,
    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 && Object.keys(props.fields).length > 0) {
        return props.fields.map(f => ({ name: f.label,  ...f ,objectType: 'field'}));
      } else {
        return api.get('api/v1/appfields', {
          params: {
            app: props.appId
          }
        }).then(res => {
          const fields = res.data.properties;
          return Object.values(fields).map((f:any) => ({ name: f.label, objectType: 'field', ...f }));
        });
      }
    }, [{ name: '', objectType: '', type: '', code: '', label: '' }])
    return {
      columns,
      rows,
      // selected: ref([]),
      isLoaded,
      pagination: ref({
        rowsPerPage: 25,
        sortBy: 'name',
        descending: false,
        page: 1,
      })
    }
  },

}
</script>
