<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="responsibles"
      :columns="columns"
      row-key="id"
      v-model:pagination="pagination"
      :loading="loading"
      :filter="filter"
      :selection="selectOption ? 'multiple' : 'none'"
      v-model:selected="selected"
      binary-state-sort
      class="bigger-table-text"
    >
      <template v-slot:top-left>
        <q-btn-group push flat style="color: grey">
          <q-btn
            v-if="user.isPermittedTo('responsible', 'write')"
            dense
            flat
            icon="add"
            @click="openAllValueDialog(null)"
          >
            <q-tooltip>{{ $t('addNewResponsible') }}</q-tooltip>
          </q-btn>
          <q-btn
            v-if="
              user.isPermittedTo('responsible', 'write') ||
              user.isPermittedTo('responsible', 'delete')
            "
            dense
            flat
            style="color: grey"
            :icon="selectOption ? 'check_box' : 'check_box_outline_blank'"
            @click="selectOption = !selectOption"
          >
            <q-tooltip>{{ $t('selectResponsibleOptions') }}</q-tooltip>
          </q-btn>
        </q-btn-group>
        <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 clickable v-close-popup @click="addToEvent" class="text-primary">{{
              $t('addToEvent')
            }}</q-item>
            <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>
      <template v-slot:top-right>
        <q-input filled dense debounce="300" v-model="filter" :placeholder="$t('search')">
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
      </template>
      <template v-slot:body-cell="props">
        <q-td
          :props="props"
          :style="user.isPermittedTo('responsible', 'write') ? 'cursor: pointer' : ''"
          @click="
            user.isPermittedTo('responsible', 'write') &&
            openSingleValueDialog(props.col.label, props.col.name, props.row)
          "
        >
          {{ props.value }}
        </q-td>
      </template>
      <template v-slot:body-cell-option="props">
        <q-td :props="props">
          <q-btn
            v-if="
              user.isPermittedTo('responsible', 'write') ||
              user.isPermittedTo('responsible', 'delete')
            "
            flat
            dense
            icon="more_vert"
            @click="openSubmenu = true"
          />
          <q-menu v-if="openSubmenu" anchor="top right" self="top left">
            <q-item
              v-if="user.isPermittedTo('responsible', 'write')"
              clickable
              v-close-popup
              @click="openAllValueDialog(props.row)"
              class="text-primary"
              >{{ $t('edit') }}</q-item
            >
            <q-item
              v-if="user.isPermittedTo('responsible', 'delete')"
              clickable
              v-close-popup
              @click="openRemoveDialog(props.row)"
              class="text-negative"
              title="zu"
              >{{ $t('delete') }}</q-item
            >
          </q-menu>
        </q-td>
      </template>
    </q-table>
  </div>
  <EditOneDialog
    ref="editOneDialog"
    endpoint="Responsibles/edit"
    query-id
    v-on:update="updateResponsibles"
  ></EditOneDialog>
  <EditAllDialog ref="editAllDialog" v-on:updated="updateResponsibles"></EditAllDialog>
  <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 type { Member, Members } from 'src/vueLib/models/member';
import EditOneDialog from 'src/components/EditOneDialog.vue';
import EditAllDialog from 'src/components/ResponsibleEditAllDialog.vue';
import OkDialog from 'src/components/dialog/OkDialog.vue';
import { useNotify } from 'src/vueLib/general/useNotify';
import { useResponsibleTable } from './ResponsibleTable';
import { databaseName } from '../members/MembersTable';
import { useUserStore } from 'src/vueLib/login/userStore';
import { i18n } from 'src/boot/lang';

export interface ResponsibleDialog {
  getSelected: () => Members;
}

const { NotifyResponse } = useNotify();
const editOneDialog = ref();
const editAllDialog = ref();
const addToEventDialog = 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 { responsibles, 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 all Responsible values
function openSingleValueDialog(label: string, field: string, Responsible: Member) {
  editOneDialog.value?.open(label, field, Responsible);
}

//opens dialog for one value
function openAllValueDialog(Responsible: Member | null) {
  editAllDialog.value?.open(Responsible);
}

//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) + ' Responsibles';
  }
  okDialog.value?.open(Responsibles);
}

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

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

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

function addToEvent() {
  addToEventDialog.value?.open(i18n.global.t('addToEvent'), selected.value);
}
</script>

<style>
@keyframes blink-yellow {
  0%,
  100% {
    background-color: yellow;
  }
  50% {
    background-color: transparent;
  }
}

.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>
