<template>
  <div class="q-pa-md">
    <q-table :loading="loading" :title="name+'一覧'" :selection="type" v-model:selected="selected" :columns="columns" :rows="rows">
      <template v-slot:body-cell-name="p">
        <q-td class="content-box flex justify-between items-center" :props="p">
          {{ p.row.name }}
          <q-badge v-if="!p.row.domainActive" color="grey">未启用</q-badge>
          <q-badge v-if="p.row.id == currentDomainId" color="primary">現在</q-badge>
        </q-td>
      </template>
    </q-table>
  </div>
</template>
<script>
import { ref,onMounted,reactive, computed } from 'vue'
import { api } from 'boot/axios';
import { useAuthStore } from 'src/stores/useAuthStore';

export default {
  name: 'DomainSelect',
  props: {
    name: String,
    type: String,
    filterInitRowsFunc: {
      type: Function,
    },
  },
  setup(props) {
    const authStore = useAuthStore();
    const currentDomainId = computed(() => authStore.currentDomain.id);
    const loading = ref(true);
    const inactiveRowClass = (row) => row.domainActive ? '' : 'inactive-row';

    const columns = [
      { name: 'id', label: 'ID', field: 'id', align: 'left', sortable: true, classes: inactiveRowClass },
      { name: 'name', align: 'left', label: 'ドメイン', field: 'name', sortable: true, classes: inactiveRowClass },
      { name: 'url', label: 'URL', field: 'url',align: 'left', sortable: true, classes: inactiveRowClass },
      { name: 'user', label: 'アカウント', field: 'user',align: 'left', classes: inactiveRowClass },
      { name: 'owner', label: '所有者', field: row => row.owner.fullName, align: 'left', classes: inactiveRowClass },
    ]
    const rows = reactive([]);

    onMounted(() => {
      loading.value = true;
      api.get('api/domains').then(res =>{
         res.data.data.forEach((data) => {
          const item = {
            id: data.id,
            tenantid: data.tenantid,
            domainActive: data.is_active,
            name: data.name,
            url: data.url,
            user: data.kintoneuser,
            owner: {
              id: data.owner.id,
              firstName: data.owner.first_name,
              lastName: data.owner.last_name,
              fullNameSearch: (data.owner.last_name + data.owner.first_name).toLowerCase(),
              fullName: data.owner.last_name + ' ' + data.owner.first_name,
              email: data.owner.email,
              isActive: data.owner.is_active,
              isSuperuser: data.owner.is_superuser,
            }
          }
          if (props.filterInitRowsFunc && !props.filterInitRowsFunc(item)) {
            return;
          }
          rows.push(item);
        })
        loading.value = false;
      });
    });
    return {
      loading,
      currentDomainId,
      columns,
      rows,
      selected: ref([]),
    }
  },

}
</script>
<style lang="scss">
.q-table td.inactive-row {
  color: #aaa;
}
.q-table .content-box {
  box-sizing: content-box;
}
</style>