<template>
  <div class="q-pa-md">
    <div class="q-gutter-sm row items-start">
        <q-breadcrumbs>
          <q-breadcrumbs-el icon="widgets" label="アプリ" />
        </q-breadcrumbs>
    </div>
    <q-table :rows="rows" :columns="columns" row-key="id" :filter="filter" :loading="loading" :pagination="pagination">

      <template v-slot:top>
        <q-btn color="primary" :disable="loading" label="新規" @click="showAddAppDialog" />
        <q-space />
        <q-input borderless dense filled debounce="300" v-model="filter" placeholder="検索">
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
      </template>
      <template v-slot:body-cell-name="prop">
        <q-td :props="prop">
          <q-btn flat dense :label="prop.row.name" @click="toEditFlowPage(prop.row)" ></q-btn>
        </q-td>
      </template>
      <template v-slot:body-cell-url="prop">
        <q-td :props="prop">
          <a :href="prop.row.url" target="_blank" :title="prop.row.name" >
            {{ prop.row.url  }}
          </a>
        </q-td>
      </template>
      <template v-slot:body-cell-version="p">
        <q-td :props="p">
          <div class="flex justify-between full-width" >
            <span v-if="p.row.version == 0"></span>
            <span v-else class="ellipsis" :title="p.row.versionName">{{ p.row.versionName }}</span>
            <q-badge v-if="isVersionEditing(p.row)" color="orange-7">変更あり</q-badge>
          </div>
        </q-td>
      </template>
      <template v-slot:body-cell-updateUser="p">
        <q-td auto-width :props="p">
          <q-badge v-if="p.row.updateUser.id == Number(authStore.userId)" color="purple">自分</q-badge>
          <span v-else>{{ p.row.updateUser.fullName }}</span>
        </q-td>
      </template>
      <template v-slot:body-cell-actions="p">
        <q-td auto-width :props="p">
          <table-action-menu :row="p.row" minWidth="180px" max-width="200px" :actions="actionList" />
        </q-td>
      </template>
    </q-table>

    <show-dialog v-model:visible="showSelectApp" name="アプリ選択" @close="closeSelectAppDialog" min-width="50vw" min-height="50vh" :ok-btn-auto-close="false" :ok-btn-loading="isAdding">
      <template v-slot:toolbar>
        <q-input dense debounce="300" v-model="dgFilter" placeholder="検索" clearable>
          <template v-slot:before>
            <q-icon name="search" />
          </template>
        </q-input>
      </template>
      <app-select-box ref="appDialog" name="アプリ" type="single" :filter="dgFilter" :filterInitRowsFunc="filterInitRows" />
    </show-dialog>

    <q-dialog v-model="deleteDialog" persistent>
      <q-card>
        <q-card-section class="row items-center">
          <q-icon name="warning" color="warning" size="2em" />
          <span class="q-ml-sm">削除してもよろしいですか？</span>
        </q-card-section>

        <q-card-actions align="right">
          <q-btn flat label="Cancel" color="primary" v-close-popup />
          <q-btn flat label="OK" color="primary" :loading="deleteUserLoading" @click="deleteApp" />
        </q-card-actions>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useAppStore } from 'stores/useAppStore';
import { useAuthStore } from 'stores/useAuthStore';
import { useFlowEditorStore } from 'stores/flowEditor';
import { router } from 'src/router';
import { IAppDisplay } from 'src/types/AppTypes';
import ShowDialog from 'src/components/ShowDialog.vue';
import AppSelectBox from 'src/components/AppSelectBox.vue';
import TableActionMenu from 'components/TableActionMenu.vue';

const appStore = useAppStore();
const authStore = useAuthStore();
const numberStringSorting = (a: string, b: string) => parseInt(a, 10) - parseInt(b, 10);

const columns = [
  { name: 'id', label: 'アプリID', field: 'id', align: 'left', sortable: true, sort: numberStringSorting },
  { name: 'name', label: 'アプリ名', field: 'name', align: 'left', sortable: true },
  { name: 'url', label: 'URL', field: 'url', align: 'left', sortable: true },
  { name: 'updateUser', label: '最後更新者', field: '', align: 'left', sortable: true},
  { name: 'updateTime', label: '最後更新日', field: 'updateTime', align: 'left', sortable: true},
  { name: 'version', label: 'バージョン', field: '', align: 'left', sortable: true, style: 'max-width: 200px;',sort: numberStringSorting },
  { name: 'actions', label: '', field: 'actions' }
];

const pagination = ref({ sortBy: 'id', descending: true, rowsPerPage: 20 });
const loading = ref(false);
const filter = ref('');
const dgFilter = ref('');
const rows = computed(() => appStore.apps);
const targetRow = ref<IAppDisplay>();

const store = useFlowEditorStore();
const appDialog = ref();
const showSelectApp=ref(false);
const isAdding = ref(false);
const deleteDialog = ref(false);
const deleteUserLoading = ref(false);

const actionList =  [
  { label: 'フローの編集', icon: 'account_tree', action: toEditFlowPage },
  { label: 'バージョンの管理', icon: 'history', action: toVersionHistoryPage },
  { separator: true },
  { label: '削除', icon: 'delete_outline', class: 'text-red', action: removeRow },
];

const getApps = async () => {
  loading.value = true;
  await appStore.loadApps();
  loading.value = false;
}

function isVersionEditing(app: IAppDisplay) {
  return !!app.versionChanged;
};

onMounted(async () => {
  await getApps();
});

const filterInitRows = (row: {id: string}) => {
  return !appStore.rowIds.has(row.id);
}

const showAddAppDialog = () => {
  showSelectApp.value = true;
  dgFilter.value = ''
}

const closeSelectAppDialog = async (val: 'OK'|'Cancel') => {
  showSelectApp.value = true;
  if (val == 'OK' && appDialog.value.selected[0]) {
      isAdding.value = true;
      toEditFlowPage(appDialog.value.selected[0]);
  }
  showSelectApp.value = false;
  isAdding.value = false;
}

function removeRow(app:IAppDisplay) {
  targetRow.value = app;
  deleteDialog.value = true;
}

const deleteApp = async () => {
  if (targetRow.value?.id) {
    deleteUserLoading.value = true;
    await appStore.deleteApp(targetRow.value)
    await getApps();
    deleteUserLoading.value = false;
    deleteDialog.value = false;
  }
}

async function toVersionHistoryPage(app:IAppDisplay) {
  await router.push('/app/version/' + app.id).catch(err => {
    console.error(err);
  });
}

async function toEditFlowPage(app:IAppDisplay) {
  store.setApp({
    appId: app.id,
    name: app.name
  });
  store.selectFlow(undefined);
  await router.push('/FlowChart/' + app.id).catch(err => {
    console.error(err);
  });
};
</script>
