<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";

import { useRouter, useRoute } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { setAuthen, authenticated, tokenParsed } from "@/plugins/auth";

/** importType*/
import type { QTableProps } from "quasar";
import type { Roles } from "@/modules/02_users/interface/response/Main";

/** importComponents*/
import DialogAddRoleUser from "@/modules/02_users/components/Users/DialogRoleUser.vue";

/** use*/
const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const roleSuper = ref<boolean>(false);
const { dialogRemove, messageError, showLoader, hideLoader, success } =
  useCounterMixin();

const userId = ref<string>(route.params.id.toString()); // id ผู้ใช้งาน

// Table
const rows = ref<Roles[]>([]); //ข้อมูลรายการสิทธิ์
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "description",
    align: "left",
    label: "คำอธิบาย",
    sortable: true,
    field: "description",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["no", "name", "description"]);

const modalDialogAdd = ref<boolean>(false); // เพิ่มสิทธิ์

/**
 * ฟังก์ชันดึงข้อมูลรายการสิทธิ์ที่มีตามผู้ใช้งาน
 */
async function fetchListRoleUser() {
  showLoader();
  http
    .get(config.API.managementUser + `/role/${userId.value}`)
    .then(async (res) => {
      const item = roleSuper.value
        ? ["STAFF", "SUPER_ADMIN", "ADMIN", "USER"]
        : ["STAFF", "USER"];

      rows.value = await res.data.filter((e: Roles) => item.includes(e.name));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันลบข้อมูลสิทธิ์ออกจากผู้ใช้งาน
 * @param id สิทธิ์
 *
 * ลบข้อมูลเสร็จโหลดข้อมูลรายการสิทธิ์ที่ใหม่
 */
function onDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.management + `/${userId.value}/role/${id}`)
      .then(async () => {
        await fetchListRoleUser();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ฟังก์เพิ่มสิทธิ์
 */
function openDialog() {
  modalDialogAdd.value = true;
}

/**
 * hook ทำงานเมื่อมีการเรียกใช้ components
 *
 * โหลดข้อมูลรายการสิทธิ์ที่มี
 */
onMounted(async () => {
  const checkToken: any = await tokenParsed();
  roleSuper.value = await checkToken.role.includes("SUPER_ADMIN");
  await fetchListRoleUser();
});
</script>

<template>
  <div class="toptitle col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.go(-1)"
    />
    จัดการสิทธิ์
  </div>

  <q-card flast bordered class="q-pa-md">
    <div class="items-center col-12 row q-col-gutter-sm q-mb-sm">
      <q-btn flat round dense color="primary" icon="add" @click="openDialog">
        <q-tooltip>เพิ่มสิทธิ์ </q-tooltip>
      </q-btn>
      <q-space />

      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        style="min-width: 140px"
      />
    </div>
    <div class="col-12 q-pt-sm">
      <d-table
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        :paging="true"
        dense
        :rows-per-page-options="[10, 25, 50, 100]"
        :visible-columns="visibleColumns"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
            <q-th auto-width></q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name === 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div v-else>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
            <q-td>
              <q-btn
                flat
                round
                color="red"
                icon="delete"
                @click="onDelete(props.row.id)"
              >
                <q-tooltip>ลบ</q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogAddRoleUser
    :fetchlist="fetchListRoleUser"
    v-model:modal="modalDialogAdd"
    :userId="userId"
    :roles="rows"
    v-model:role-super="roleSuper"
  />
</template>

<style scoped></style>
