<template>
  <div class="q-px-md" style=" min-width: 50vw; max-width: 85vw;">
    <div v-if="!isLoaded" class="spinner flex flex-center">
      <q-spinner color="primary" size="3em" />
    </div>
    <q-table  flat bordered v-else row-key="name" :selection="type" v-model:selected="selected" :columns="columns"
      :rows="rows" :pagination="pageSetting" :filter="filter" style="max-height: 55vh;"/>
  </div>
</template>
<script>
import { ref, onMounted, reactive, watchEffect } from 'vue'
import { api } from 'boot/axios';

export default {
  name: 'fieldSelect',
  props: {
    name: String,
    type: {
      type: String,
      default: 'single'
    },
    appId: Number,
    not_page: {
      type: Boolean,
      default: false,
    },
    selectedFields:{
      type:Array,
      default:()=>[]
    },
    updateSelects: {
      type: Function
    },
    filter: String,
  },
  setup(props) {
    const isLoaded = ref(false);
    const columns = [
      { name: 'name', required: true, label: 'フィールド名', align: 'left', field: row => row.name, sortable: true },
      { name: 'code', label: 'フィールドコード', align: 'left', field: 'code', sortable: true },
      { name: 'type', label: 'フィールドタイプ', align: 'left', field: 'type', sortable: true }
    ]
    const pageSetting = ref({
      sortBy: 'desc',
      descending: false,
      page: 2,
      rowsPerPage: props.not_page ? 0 : 5
      // rowsNumber: xx if getting data from a server
    });
    const rows = reactive([]);
    const selected = ref(props.selectedFields && props.selectedFields.length>0?props.selectedFields:[]);

    watchEffect(() => {
        props.updateSelects(selected);
    });

    onMounted(async () => {
      const res = await api.get('api/v1/appfields', {
        params: {
          app: props.appId
        }
      });
      let fields = res.data.properties;
      console.log(fields);
      Object.keys(fields).forEach((key) => {
        const fld = fields[key];
        // rows.push({name:fields[key].label,code:fields[key].code,type:fields[key].type});
        rows.push({ name: fld.label, ...fld });
      });
      isLoaded.value = true;
    });

    return {
      columns,
      rows,
      selected,
      isLoaded,
      pageSetting
    }
  },

}
</script>
