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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRoute } from "vue-router";
import { usePagination } from "@/composables/usePagination";
import { useCounterMixin } from "@/stores/mixin";

import type { DataOption } from "@/modules/18_command/interface/index/Main";
import type { DataProfile} from  "@/modules/18_command/interface/response/Main";

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

const $q = useQuasar();
const route = useRoute();
const {
  dialogConfirm,
  showLoader,
  success,
  messageError,
  hideLoader,
  dialogMessageNotify,
} = useCounterMixin();
const { pagination, params, onRequest } = usePagination("", () =>
  fetchDataPerson()
);

const modal = defineModel<boolean>("modal", { required: true });
const commandId = defineModel<string>("commandId", { required: true });
const props = defineProps<{
  fetchListCommand: () => Promise<void>;
}>();

const keyword = ref<string>("");
const type = ref<string>("citizenId");
const rows = ref<DataProfile[]>([]);
const selected = ref<DataProfile[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    field: "no",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "citizenId",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    field: "fullName",
    sortable: true,
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
    {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    field: "posNo",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
      {
    name: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    field: "position",
    sortable: true,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
   {
    name: "positionType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    field: "positionType",
    sortable: false,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.posTypeName
        ? `${row.posTypeName} ${row.positionLevelName ? `(${row.positionLevelName})` : ""}`
        : "-";
    },
  },
]);
const visibleColumns = ref<string[]>(
  columns.value ? columns.value.map((col) => col.name) : []
);

const searchTypeOption = ref<DataOption[]>([
  { id: "citizenId", name: "เลขประจำตัวประชาชน" },
  { id: "fullName", name: "ชื่อ-นามสกุล" },
]);

/** ฟังก์ชันเรียกรายชื่อคน*/
async function fetchDataPerson() {
  showLoader();
  try {
    const res = await http.post(
      config.API.orgSearchPersonal(),
      {
        fieldName: type.value,
        keyword: keyword.value.trim(),
        system: (route.meta?.Key as string) || 'COMMAND',
      },
      {
        params: params.value,
      }
    );
    const result = res.data.result;
    pagination.value.rowsNumber = result.total;
    rows.value = result.data;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

function onSubmit() {
  if (selected.value.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกบุคคลที่ต้องการหมอบหมายคำสั่ง");
    return;
  }
  dialogConfirm($q, async () => {
    const assingId = selected.value[0].keycloak;
    try {
      await http.put(config.API.commandAssign(commandId.value), {
        assignId: assingId,
      });
      await props.fetchListCommand();
      handleClose();
      success($q, "หมอบหมายคำสั่งสำเร็จ");
    } catch (error) {
      messageError($q, error);
    } finally {
      hideLoader();
    }
  });
}

function onSearch() {
  pagination.value.page = 1;
  fetchDataPerson();
}

function handleClose() {
  modal.value = false;
  rows.value = [];
  selected.value = [];
  keyword.value = "";
  type.value = "citizenId";
}

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

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 50vw; max-width: 50vw">
      <DialogHeader tittle="หมอบหมายคำสั่ง" :close="handleClose" />
      <q-separator />
      <q-card-section style="max-height: 60vh">
        <div class="row q-col-gutter-md">
          <div class="col-12">
            <div class="row q-col-gutter-sm">
              <q-select
                label="ค้นหาจาก"
                v-model="type"
                :options="searchTypeOption"
                outlined
                emit-value
                dense
                emit-option
                option-label="name"
                option-value="id"
                map-options
              />
              <q-space />
              <q-input
                dense
                outlined
                v-model="keyword"
                label="ค้นหา"
                @keydown.enter.prevent="onSearch"
              >
                <template v-slot:append> <q-icon name="search" /> </template>
              </q-input>

              <q-select
                dense
                multiple
                outlined
                emit-value
                map-options
                options-dense
                option-value="name"
                style="min-width: 140px"
                v-model="visibleColumns"
                :options="columns"
                :display-value="$q.lang.table.columns"
              />
            </div>
          </div>
          <div class="col-12">
            <p-table
              :rows="rows"
              :columns="columns"
              row-key="id"
              :selection="'single'"
              v-model:selected="selected"
              v-model:pagination="pagination"
              @request="onRequest"
              :visible-columns="visibleColumns"
            >
              <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"
                  >
                    <div v-if="col.name == 'no'">
                      {{ props.rowIndex + 1 }}
                    </div>
                    <div v-else>
                      {{ col.value ? col.value : "-" }}
                    </div>
                  </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"> </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
