<script setup lang="ts">
/** importComponents*/
import DialogHeader from "@/components/DialogHeader.vue";
import { ref, watch } from "vue";
import { useQuasar } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { 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 roleSuper = ref<boolean>(false);
const { dialogRemove, messageError, showLoader, hideLoader, success } =
  useCounterMixin();

const modal = defineModel<boolean>("modelValue", {
  required: true,
});
const userId = defineModel<string>("userId", {
  required: true,
});
const props = defineProps({
  fetchList: {
    type: Function,
    required: true,
  },
});

// Table
const rows = ref<Roles[]>([]); //ข้อมูลรายการสิทธิ์
const keyword = ref<string>(""); // ค้นหา
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); // เพิ่มสิทธิ์
const isUpdate = 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, "ลบข้อมูลสำเร็จ");
        isUpdate.value = true;
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

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

async function closeDialog() {
  isUpdate.value && (await props.fetchList?.());
  modal.value = false;
}

/**
 * hook ทำงานเมื่อมีการเรียกใช้ components
 *
 * โหลดข้อมูลรายการสิทธิ์ที่มี
 */

watch(
  () => modal.value,
  async (newVal) => {
    if (newVal) {
      const checkToken: any = await tokenParsed();
      roleSuper.value = await checkToken.role.includes("SUPER_ADMIN");
      await fetchListRoleUser();
      isUpdate.value = false;
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 55vw">
      <DialogHeader :tittle="'จัดการสิทธิ์'" :close="closeDialog" />
      <q-separator />
      <q-card-section>
        <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-input
            borderless
            dense
            outlined
            v-model="keyword"
            placeholder="ค้นหา"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>

          <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"
            :filter="keyword"
          >
            <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-section>
    </q-card>
  </q-dialog>

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

<style scoped></style>
