<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

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

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

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

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

/**  props*/
const modal = defineModel<boolean>("modal", { required: true });
const userId = defineModel<string>("userId", { required: true });
const roles = defineModel<Roles[]>("roles", {});

const props = defineProps({
  fetchlist: {
    type: Function,
    required: true,
  },
});

const rows = ref<Roles[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    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[]>(["name", "description"]);

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

/** function fetc รายการ role*/
function fetchlistRole() {
  showLoader();
  http
    .get(config.API.managementRole)
    .then((res) => {
      const rolesIds = roles.value?.map((e) => e.id);
      rows.value = res.data.filter((v: Roles) => !rolesIds?.includes(v.id));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmit() {
  if (selected.value.length === 0) {
    dialogMessageNotify($q, "กรุณาเลือก role อย่างน้อง 1 role");
  } else {
    dialogConfirm($q, () => {
      showLoader();
      const body = { role: selected.value.map((e: { id: string }) => e.id) };
      http
        .post(config.API.management + `/${userId.value}/role`, body)
        .then(() => {
          props.fetchlist?.();
          closeDialog();
          success($q, "บันทึกข้อมูลสำเร็จ");
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    });
  }
}

/** function ปิด Dialog */
function closeDialog() {
  modal.value = false;
  selected.value = [];
}

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      fetchlistRole();
    }
  }
);
</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="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"
            selection="multiple"
            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>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn label="บันทึก" color="secondary" @click="onSubmit"
          ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
        >
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
