<template>
  <div class="q-pa-md">
    <q-table
      flat
      bordered
      ref="tableRef"
      title="Responsibles"
      title-class="text-bold text-blue-9"
      :no-data-label="$t('noDataAvailable')"
      :loading-label="$t('loading')"
      :rows-per-page-label="$t('recordsPerPage')"
      :selected-rows-label="(val) => val + ' ' + $t('recordSelected')"
      :rows="responsibleMember"
      :columns="columns"
      row-key="id"
      v-model:pagination="pagination"
      :loading="loading"
      :filter="filter"
      :selection="selectOption ? 'multiple' : 'none'"
      v-model:selected="selected"
      binary-state-sort
      dense
      class="bigger-table-text"
    >
      <template v-slot:top-left>
        <TopButtonGroup
          :permit-add="user.isPermittedTo('responsible', 'write')"
          v-on:add="openResponsibleDialog"
          :tool-tip-add="$t('addNewResponsible')"
          :permit-select="
            user.isPermittedTo('responsible', 'write') ||
            user.isPermittedTo('responsible', 'delete')
          "
          v-model:select-option="selectOption"
          :tool-tip-select="$t('selectResponsibleOptions')"
        />
        <div v-if="selectOption && selected.length > 0">
          <q-btn flat dense icon="more_vert" @click="openSubmenu = true" />
          <q-menu v-if="openSubmenu" anchor="bottom middle" self="top middle">
            <q-item
              v-if="user.isPermittedTo('responsible', 'delete')"
              clickable
              v-close-popup
              @click="openRemoveDialog(...selected)"
              class="text-negative"
              >{{ $t('delete') }}</q-item
            >
          </q-menu>
        </div>
        <div v-if="selectOption && selected.length > 0" class="text-weight-bold">
          {{ $t('selected') }}: {{ selected.length }}
        </div>
      </template>

      <!-- top right of table-->

      <template v-slot:top-right>
        <SearchableInput v-model="filter" :placeholder="$t('search')" />
      </template>

      <!-- table body content-->
      <template v-slot:body-cell="props">
        <component :td-props="props" :is="props.col.component" :value="props.value" />
      </template>

      <template v-slot:body-cell-option="props">
        <component
          :is="props.col.component"
          :td-props="props"
          :permitDelete="user.isPermittedTo('responsible', 'delete')"
          :removeFunction="() => openRemoveDialog(props.row)"
        >
        </component>
      </template>
    </q-table>
  </div>
  <DialogFrame
    ref="responsibleDialog"
    :header-title="$t('addNewResponsible')"
    :height="600"
    :width="500"
  >
    <MembersTable
      add-responsible
      :compare-members="responsibleMember"
      v-on:update-event="updateResponsibles"
    />
  </DialogFrame>
  <OkDialog
    ref="okDialog"
    :dialog-label="$t('delete')"
    :text="$t('doYouWantToDelete') + ' ' + deleteText"
    label-color="red"
    :button-cancel-label="$t('cancel')"
    :button-ok-label="$t('confirm')"
    :button-ok-flat="false"
    button-ok-color="red"
    v-on:update-confirm="(val) => removeResponsible(...val)"
  ></OkDialog>
</template>

<script setup lang="ts">
import { appApi } from 'src/boot/axios';
import { ref, onMounted } from 'vue';
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import MembersTable from '../members/MembersTable.vue';
import type { Members } from 'src/vueLib/models/member';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useResponsibleTable } from './ResponsibleTable';
import { databaseName } from 'src/vueLib/models/settings';
import { useUserStore } from 'src/vueLib/login/userStore';
import { i18n } from 'src/boot/lang';
import type { Responsible, Responsibles } from 'src/vueLib/models/responsible';
import SearchableInput from '../components/SearchableInput.vue';
import TopButtonGroup from '../components/TopButtonGroup.vue';

const { NotifyResponse } = useNotify();
const responsibleDialog = ref();
const okDialog = ref();
const deleteText = ref('');
const selectOption = ref(false);
const selected = ref<Members>([]);
const openSubmenu = ref(false);
const filter = ref('');
const user = useUserStore();

const { responsibleMember, pagination, loading, columns, updateResponsibles } =
  useResponsibleTable();

//load on mounting page
onMounted(() => {
  loading.value = true;

  appApi
    .post('database/open', { dbPath: databaseName.value, create: true })
    .then(() => {
      updateResponsibles().catch((err) => {
        NotifyResponse(err, 'error');
      });
    })
    .catch((err) => NotifyResponse(err, 'error'))

    .finally(() => {
      loading.value = false;
    });
});

//opens dialog for one value
function openResponsibleDialog() {
  responsibleDialog.value?.open();
}

//opens remove dialog
function openRemoveDialog(...Responsibles: Members) {
  if (Responsibles.length === 1) {
    deleteText.value = "'";
    if (Responsibles[0]?.firstName !== undefined) {
      deleteText.value += Responsibles[0]?.firstName + ' ';
    }
    if (Responsibles[0]?.lastName !== undefined) {
      deleteText.value += Responsibles[0]?.lastName;
    }
    deleteText.value += "'";
  } else {
    deleteText.value = String(Responsibles.length) + ' ' + i18n.global.t('responsibles');
  }
  okDialog.value?.open(Responsibles);
}

//remove Responsible from database
async function removeResponsible(...removeResponsibles: Responsibles) {
  const ResponsibleIds: number[] = [];

  removeResponsibles.forEach((Responsible: Responsible) => {
    if (Responsible.id) ResponsibleIds.push(Responsible.id);
  });

  await appApi
    .post('responsible/delete', { ids: ResponsibleIds })
    .then(() => {
      updateResponsibles().catch((err) => {
        NotifyResponse(err, 'error');
      });
      selected.value = [];
    })
    .catch((err) => NotifyResponse(err, 'error'))
    .finally(() => {
      loading.value = false;
    });
  await updateResponsibles();
}
</script>

<style>
.bigger-table-text .q-table__middle td {
  font-size: 14px;
}

.bigger-table-text .q-table__top,
.bigger-table-text .q-table__bottom,
.bigger-table-text th {
  font-size: 14px;
}
</style>
