<template>
  <div class="q-px-xs">
    <div v-if="!isLoaded" class="spinner flex flex-center">
      <q-spinner color="primary" size="3em" />
    </div>
    <q-table v-else class="app-table" :selection="type" row-key="id" v-model:selected="selected" flat bordered
      virtual-scroll :columns="columns" :rows="rows" :pagination="pagination" :rows-per-page-options="[0]"
      :filter="filter" style="max-height: 65vh;">
      <template v-slot:body-cell-description="props">
        <q-td :props="props">
          <q-scroll-area class="description-cell">
            <div v-html="props.row.description"></div>
          </q-scroll-area>
        </q-td>
      </template>
    </q-table>
  </div>
</template>
<script lang="ts">
import { ref, onMounted, reactive, watchEffect } from 'vue'
import { api } from 'boot/axios';

export default {
  name: 'AppSelect',
  props: {
    name: String,
    type: String,
    filter: String,
    updateExternalSelectAppInfo: {
      type: Function
    }
  },
  setup(props) {
    const columns = [
      { name: 'id', required: true, label: 'ID', align: 'left', field: 'id', sortable: true },
      { name: 'name', label: 'アプリ名', field: 'name', sortable: true, align: 'left' },
      { name: 'description', label: '概要', field: 'description', align: 'left', sortable: false },
      { name: 'createdate', label: '作成日時', field: 'createdate', align: 'left' }
    ]
    const isLoaded = ref(false);
    const rows: any[] = reactive([]);
    const selected = ref([])

    watchEffect(()=>{
      if (selected.value && selected.value[0] && props.updateExternalSelectAppInfo) {
        props.updateExternalSelectAppInfo(selected.value[0])
      }
    });
    onMounted(() => {
      api.get('api/v1/allapps').then(res => {
        res.data.apps.forEach((item: any) => {
          rows.push({
            id: item.appId,
            name: item.name,
            description: item.description,
            createdate: dateFormat(item.createdAt)
          });
        });
        isLoaded.value = true;
      });
    });

    const dateFormat = (dateStr: string) => {
      const date = new Date(dateStr);
      const pad = (num: number) => num.toString().padStart(2, '0');
      const year = date.getFullYear();
      const month = pad(date.getMonth() + 1);
      const day = pad(date.getDate());
      const hours = pad(date.getHours());
      const minutes = pad(date.getMinutes());
      const seconds = pad(date.getSeconds());
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    }
    return {
      columns,
      rows,
      selected,
      isLoaded,
      pagination: ref({
        rowsPerPage: 10
      })
    }
  },

}
</script>
<style lang="scss">
.description-cell {
  height: 60px;
  width: 300px;
  max-height: 60px;
  max-width: 300px;
  white-space: break-spaces;
}

.spinner {
  min-height: 300px;
  min-width: 400px;
}
</style>
