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

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

interface IAppDisplay {
  id: string;
  name: string;
  description: string;
  createdate: string;
}

export default {
  name: 'AppSelectBox',
  components: {
    DetailFieldTable
  },
  props: {
    name: String,
    type: String,
    filter: String,
    filterInitRowsFunc: {
      type: Function as PropType<(app: IAppDisplay) => boolean>,
    }
  },
  setup(props) {
    const selected = ref<IAppDisplay[]>([]);
    const columns = [
      { name: 'id', required: true, label: 'ID', align: 'left', field: 'id', sortable: true, sort: (a: string, b: string) => parseInt(a, 10) - parseInt(b, 10) },
      { 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 fetchApps = async () => {
      const res = await api.get('api/v1/allapps');
      return res.data.apps.map((item: any) => ({
        id: item.appId,
        name: item.name,
        description: item.description,
        createdate: dateFormat(item.createdAt)
      })).filter(app => !props.filterInitRowsFunc || props.filterInitRowsFunc(app));
    };

    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,
      fetchApps,
      selected
    };
  }
};
</script>