<template>
  <detail-field-table
    detailField="description"
    :name="name"
    :type="type"
    :filter="filter"
    :columns="columns"
    :fetchData="fetchUsers"
    @update:selected="(item) => { selected = item }">

    <template v-slot:body-cell-status="props">
      <div class="row">
        <div v-if="props.row.isActive">
          <q-chip square color="positive" text-color="white" icon="done" label="使用可能" size="sm" />
        </div>
        <div v-else>
          <q-chip square color="negative" text-color="white" icon="block" label="使用不可" size="sm" />
        </div>

        <q-chip v-if="props.row.isSuperuser" square color="accent" text-color="white" icon="admin_panel_settings"
          label="システム管理者" size="sm" />
      </div>
    </template>
    
  </detail-field-table>
</template>

<script lang="ts">
import { ref, PropType } from 'vue';
import { IUser } from 'src/types/UserTypes';
import { api } from 'boot/axios';
import DetailFieldTable from './DetailFieldTable.vue';

export default {
  name: 'UserSelectBox',
  components: {
    DetailFieldTable
  },
  props: {
    name: String,
    type: String,
    filter: String,
    filterInitRowsFunc: {
      type: Function as PropType<(user: IUser) => boolean>,
    }
  },
  setup(props) {
    const selected = ref<IUser[]>([]);
    const columns = [
      { name: 'id', label: 'ID', field: 'id', align: 'left', sortable: true },
      { name: 'lastName', label: '氏名', field: 'lastName', align: 'left', sortable: true },
      { name: 'firstName', label: '苗字', field: 'firstName', align: 'left', sortable: true },
      { name: 'email', label: '電子メール', field: 'email', align: 'left', sortable: true },
      { name: 'status', label: '状況', field: 'status', align: 'left' }
    ];

    const fetchUsers = async () => {
      const result = await api.get('api/v1/users');
      return result.data.data.map((item: any) => {
        return { id: item.id, firstName: item.first_name, lastName: item.last_name, email: item.email, isSuperuser: item.is_superuser, isActive: item.is_active, roles: item.roles.map(role => role.id) }
      }).filter(user => !props.filterInitRowsFunc || props.filterInitRowsFunc(user));
    };

    return {
      columns,
      fetchUsers,
      selected
    };
  }
};
</script>