<script setup lang="ts">
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";

/** importComponents*/
import DialogHeader from "@/components/DialogHeader.vue";

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

/** use*/
const $q = useQuasar();
const {
  showLoader,
  hideLoader,
  dialogConfirm,
  messageError,
  success,
  dialogMessageNotify,
  onSearchDataTable,
} = useCounterMixin();

/**  props*/
const modal = defineModel<boolean>("modal", { required: true });
const reqMaster = defineModel<FilterReqMaster>("reqMaster", { required: true });

const props = defineProps({
  fetchDataTable: {
    type: Function,
    required: true,
  },
  dataPosMaster: {
    type: Object,
    required: true,
  },
});

const rows = ref<Roles[]>([]);
const rowsMain = ref<Roles[]>([]);
const keyword = ref<string>("");
const columns = ref<QTableProps["columns"]>([
  {
    name: "roleName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "roleName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "roleDescription",
    align: "left",
    label: "คำอธิบาย",
    sortable: true,
    field: "roleDescription",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["roleName", "roleDescription"]);

const selected = ref<Roles[]>([]);
const roleUser = ref<string[]>([]);

function closeDialog() {
  modal.value = false;
  selected.value = [];
  keyword.value = "";
}

async function fetchListRoles() {
  showLoader();
  const isCheckRole = roleUser.value.includes("SUPER_ADMIN") ? true : false;

  const param: { params?: { isAdminVisibled: string } } = {};
  if (!isCheckRole) {
    param.params = {
      isAdminVisibled: "true",
    };
  }

  await http
    .get(config.API.managementAuth + `/list`, param)
    .then((res) => {
      const data = res.data.result;
      rows.value = data;
      rowsMain.value = data;
      const findRole = data.find(
        (e: Roles) => e.id === props.dataPosMaster.authRoleId
      );
      if (findRole) {
        selected.value.push(findRole);
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmit() {
  if (selected.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือกสิทธิ์อย่างน้อง 1 สิทธิ์");
  } else {
    dialogConfirm($q, () => {
      showLoader();
      const arrayId = selected.value.map((e: Roles) => e.id);
      http
        .post(config.API.managementPermission, {
          authRoleId: arrayId[0],
          posMasterId: props.dataPosMaster.id,
        })
        .then(async () => {
          await props.fetchDataTable(
            reqMaster.value.id,
            reqMaster.value.revisionId,
            reqMaster.value.type
          );
          closeDialog();
          await success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

watch(
  () => modal.value,
  async () => {
    if (modal.value) {
      const token = await tokenParsed();
      roleUser.value = token?.role || [];
      await fetchListRoles();
    }
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 50%">
      <DialogHeader tittle="จัดการสิทธิ์" :close="closeDialog" />
      <q-separator />
      <q-card-section>
        <div class="row q-col-gutter-sm">
          <div class="col-12">
            <q-input
              outlined
              dense
              v-model="keyword"
              label="ค้นหา"
              @keydown.enter.prevent="serchDataTable"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>
          </div>
          <div class="col-12">
            <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"
              selection="single"
              v-model:selected="selected"
            >
              <template v-slot:body="props">
                <q-tr :props="props" class="cursor-pointer">
                  <q-td>
                    <q-checkbox
                      keep-color
                      color="primary"
                      dense
                      v-model="props.selected"
                    />
                  </q-td>
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>

      <q-separator />
      <q-card-actions align="right">
        <q-btn label="บันทึก" color="secondary" type="submit" @click="onSubmit"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
