<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar, type QTableProps } from "quasar";
import { usePagination } from "@/composables/usePagination";

import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { DataOperators } from "@/modules/18_command/interface/response/Main";
import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const { dialogConfirm, showLoader, messageError, hideLoader, success } =
  useCounterMixin();
const { pagination, params, onRequest } = usePagination("", fetchListOperator);

const modal = defineModel<boolean>("modal", { required: true });

const props = defineProps<{
  commandId: string;
  createdUserId: string;
  refreshData: Function;
}>();

const selected = ref<DataOperators[]>([]);
const keyword = ref<string>("");
const isAct = ref<boolean>(false);
const rows = ref<DataOperators[]>([]);
const visibleColumns = ref<string[]>([
  "posNo",
  "fullName",
  "posExecutiveName",
  "actFullName",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posExecutiveName",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "posExecutiveName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "actFullName",
    align: "left",
    label: "รักษาการแทน",
    field: "actFullName",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const roleName = ref<string>("");
const roleNameList = ref<string[]>([
  "เจ้าหน้าที่ดำเนินการ",
  "ผอ.สกจ.",
  "รักษาการฯ ผอ.สกจ.",
  "ผอ.",
  "รักษาการฯ ผอ.",
  "ผอ.ส่วน",
  "หน.กลุ่มงาน",
  "หน.ฝ่าย",
]);
const roleNameOption = ref<string[]>(roleNameList.value);

/** ฟังก์ชันบันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm($q, async () => {
    try {
      showLoader();
      const data = selected.value[0];
      const playload = {
        profileId: data.id,
        prefix: data.prefix ?? "",
        firstName: data.firstName ?? "",
        lastName: data.lastName ?? "",
        posNo: data.posNo ?? "",
        posType: data.posType ?? "",
        posLevel: data.posLevel ?? "",
        position: data.position ?? "",
        positionExecutive: data.posExecutiveName ?? "",
        roleName: roleName.value.trim(),
      };
      showLoader();
      await http.post(
        config.API.commandOperator + `/${props.commandId}`,
        playload
      );
      await props.refreshData();
      success($q, "บันทึกข้อมูลสำเร็จ");
      onClose();
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ฟังก์ชันปิด Popup และรีเซ็ตข้อมูล */
function onClose() {
  modal.value = false;
  rows.value = [];
  selected.value = [];
  keyword.value = "";
  pagination.value.rowsNumber = 0;
  roleName.value = "";
}

/** ฟังก์ชันดึงข้อมูลรายชื่อเจ้าหน้าที่ดำเนินการ */
async function fetchListOperator() {
  try {
    showLoader();
    selected.value = [];
    const res = await http.put(config.API.workflowCommanderOperate, {
      ...params.value,
      keyword: keyword.value,
      isAct: isAct.value,
      keycloakId: props.createdUserId,
      type: "officer",
    });
    const data = res.data.result;
    pagination.value.rowsNumber = data.total;
    rows.value = data.data;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

/** ฟังก์ชันรีเซ็ตหน้าและดึงข้อมูลรายชื่อเจ้าหน้าที่ดำเนินการใหม่ */
function fetchNewListOperator() {
  pagination.value.page = 1;
  fetchListOperator();
}

/**
 * ฟังก์ชันกรองรายการบทบาท
 * @param val ค่าที่กรอก
 * @param update ฟังก์ชันอัพเดตรายการ
 */
function filterOptionFnRoleName(val: string, update: Function) {
  update(() => {
    if (val === "") {
      roleNameOption.value = roleNameList.value;
    } else {
      const needle = val.toLowerCase();
      roleNameOption.value = roleNameList.value.filter((item: string) =>
        item.toLowerCase().includes(needle)
      );
    }
  });
}

/**
 * ฟังก์ชันกำหนดค่าบทบาท
 * @param val ค่าที่เลือก
 */
function setModel(val: string) {
  roleName.value = val;
}

watch(modal, (newVal) => {
  if (newVal) {
    fetchListOperator();
  }
});
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 50vw; max-width: 50vw">
      <DialogHeader
        tittle="เพิ่มรายชื่อลงนามในแนบท้ายคำสั่ง"
        :close="onClose"
      />
      <q-separator />
      <q-card-section>
        <div class="col-12 row q-col-gutter-sm">
          <div class="col-12">
            <div class="row q-gutter-x-xs">
              <!-- input suggestion  -->
              <div class="col-xs-12 col-md-3">
                <q-select
                  borderless
                  outlined
                  dense
                  lazy-rules
                  v-model="roleName"
                  :label="`${'บทบาท'}`"
                  :options="roleNameOption"
                  use-input
                  fill-input
                  input-debounce="0"
                  @filter="filterOptionFnRoleName"
                  @input-value="setModel"
                  hide-selected
                  hide-dropdown-icon
                  hide-bottom-space
                />
              </div>

              <q-space />

              <div class="row col-xs-12 col-md-6 q-col-gutter-sm">
                <div class="col-xs-12 col-md-6">
                  <q-checkbox
                    keep-color
                    v-model="isAct"
                    label="แสดงเฉพาะรักษาการแทน"
                    color="primary"
                    @update:model-value="fetchNewListOperator"
                  />
                </div>

                <div class="col-xs-12 col-md-6">
                  <q-input
                    dense
                    outlined
                    label="ค้นหา"
                    v-model="keyword"
                    @keyup.enter="fetchNewListOperator"
                  >
                    <template v-slot:append>
                      <q-icon name="search"></q-icon>
                    </template>
                  </q-input>
                </div>
              </div>
            </div>
          </div>
          <div class="col-12">
            <p-table
              ref="table"
              :columns="columns"
              :rows="rows"
              row-key="key"
              flat
              bordered
              :paging="false"
              dense
              :rows-per-page-options="[10, 25, 50, 100]"
              class="custom-header-table"
              :visible-columns="visibleColumns"
              @request="onRequest"
              v-model:pagination="pagination"
              :selection="'single'"
              v-model:selected="selected"
            >
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th auto-width />

                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <span class="text-weight-medium">{{ col.label }}</span>
                  </q-th>
                </q-tr>
              </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"
                  >
                    {{ col.value ?? "-" }}
                  </q-td>
                </q-tr>
              </template>
            </p-table>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          label="บันทึก"
          color="public"
          @click="onSubmit"
          :disable="!roleName || selected.length === 0"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
