<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";

/** 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,
} = 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 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 keyword = ref<string>("");
const selected = ref<Roles[]>([]);

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

function fetchListRoles() {
  showLoader();
  http
    .get(config.API.managementAuth + `/list`)
    .then((res) => {
      const data = res.data.result;
      rows.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();
        });
    });
  }
}

watch(
  () => modal.value,
  () => {
    modal.value && 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="ค้นหา">
              <template v-slot:append>
                <q-icon name="search" color="grey-5" />
              </template>
            </q-input>
          </div>
          <div class="col-12">
            <d-table
              ref="table"
              :columns="columns"
              :rows="rows"
              :filter="keyword"
              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:header-selection="scope">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="scope.selected"
                  />
                </template> -->

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