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

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

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

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

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

/** Table*/
const rows = ref<Users[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: (row) => rows.value.indexOf(row) + 1,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "username",
    align: "left",
    label: "ชื่อผู้ใช้งาน",
    sortable: true,
    field: "username",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "email",
    align: "left",
    label: "Email",
    sortable: true,
    field: "email",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "firstName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "lastName",
    align: "left",
    label: "นามสกุล",
    sortable: true,
    field: "lastName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "username",
  "email",
  "firstName",
  "lastName",
]);
const keyword = ref<string>("");

const modalDialogAdd = ref<boolean>(false);
const isStatusEdit = ref<boolean>(false);
const userId = ref<string>("");

/** List Mune*/
const itemMenu = ref<ItemsMenu[]>([
  {
    label: "แก้ไข",
    icon: "edit",
    color: "edit",
    type: "edit",
  },
  {
    label: "ลบ",
    icon: "delete",
    color: "red",
    type: "delete",
  },
]);

/** function fetch รายชื่อผู้ใช้งาน*/
function fetchListUsers() {
  showLoader();
  http
    .get(config.API.managementUser)
    .then((res) => {
      const data = res.data;
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 *
 * @param type ประเภท
 * @param data ข้อมูลรายการผู้ใช้งาน
 */
function onClickAction(type: string, data: Users) {
  if (type === "edit") {
    modalDialogAdd.value = true;
    isStatusEdit.value = true;
    userId.value = data.id;
  } else if (type === "delete") {
    onDeleteUser(data.id);
  }
}

function openDialog() {
  modalDialogAdd.value = true;
  isStatusEdit.value = false;
  userId.value = "";
}

/**
 * function ยืนยันการลบข้อมูลรายการผู้ใช้งาน
 * @param id รายการผู้ใช้งาน
 */
function onDeleteUser(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.managementUser + `/${id}`)
      .then(() => {
        success($q, "ลบข้อมูลสำเร็จ");
        fetchListUsers();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

onMounted(() => {
  fetchListUsers();
});
</script>

<template>
  <div class="row items-center">
    <div class="toptitle text-dark row items-center q-py-xs">
      จัดการผู้ใช้งาน
    </div>
  </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-input
        borderless
        dense
        debounce="300"
        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"
        options-cover
      />
    </div>

    <div class="col-12 q-pt-sm">
      <d-table
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        :filter="keyword"
        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>
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
            <q-td>
              <q-btn
                flat
                dense
                icon="mdi-dots-vertical"
                class="q-pa-none q-ml-xs"
                color="grey-13"
                size="12px"
              >
                <q-menu>
                  <q-list dense style="min-width: 200px">
                    <q-item
                      v-for="(item, index) in itemMenu"
                      :key="index"
                      clickable
                      v-close-popup
                      @click.stop="onClickAction(item.type, props.row)"
                    >
                      <q-item-section>
                        <div class="row items-center">
                          <q-icon
                            :color="item.color"
                            size="17px"
                            :name="item.icon"
                          />
                          <div class="q-pl-md">{{ item.label }}</div>
                        </div>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogAddUser
    :fetchlist="fetchListUsers"
    v-model:modal="modalDialogAdd"
    v-model:isStatusEdit="isStatusEdit"
    :userId="userId"
  />
</template>

<style scoped></style>
