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

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

import type { QTableProps } from "quasar";

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

const $q = useQuasar();
const route = useRoute();
const { showLoader, hideLoader, messageError } = useCounterMixin();

const modal = defineModel<boolean>("modal", { required: true }); //popup เลือกผู้บังคับบัญชา/ผู้มีอำนาจออกคำสั่ง

const emit = defineEmits(["update-authority"]);

const personalId = ref<string>(route.params.personalId.toString());

const selected = ref<any[]>([]);
const isAct = ref<boolean>(false);
const search = ref<string>("");
const rows = ref<any[]>([]); //รายชื่อผู้บังคับบัญชา/ผู้มีอำนาจออกคำสั่ง
const page = ref<number>(1);
const pageSize = ref<number>(10);
const maxPaeg = ref<number>(1);
const total = ref<number>(0);
const columns = ref<QTableProps["columns"]>([
  // {
  //   name: "citizenId",
  //   align: "left",
  //   label: "เลขประจำตัวประชาชน",
  //   sortable: true,
  //   field: "citizenId",
  //   headerStyle: "font-size: 14px",
  //   style: "font-size: 14px",
  // },
  {
    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: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "posType",
    format(val, row) {
      return `${row.posType} ${row.posLevel ? `(${row.posLevel})` : ""}   `;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const columnsAct = ref<QTableProps["columns"]>([
  {
    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: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionSign",
    align: "left",
    label: "ตำแหน่งใต้ลายเซ็น",
    sortable: true,
    field: "positionSign",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function onCloseDialog() {
  modal.value = false;
  isAct.value = false;
  rows.value = [];
  selected.value = [];
  search.value = "";
  page.value = 1;
  pageSize.value = 10;
  maxPaeg.value = 1;
  total.value = 0;
}

function fetchList() {
  showLoader();
  http
    .post(config.API.probationCommanderDirector, {
      isDirector: true, // fix ค่านี้เป็น true
      isAct: isAct.value,
      keyword: search.value.trim(),
      page: page.value,
      pageSize: pageSize.value,
      profileId: personalId.value,
    })
    .then((res) => {
      const data = res.data.result;
      rows.value = data.data;
      maxPaeg.value = Math.ceil(data.total / pageSize.value);
      total.value = data.total;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onAct() {
  onSearchData();
}

function onSearchData() {
  page.value = 1;
  fetchList();
}

function updatePagination(newPagination: any) {
  pageSize.value = newPagination.rowsPerPage;
}

function onSelectAuthority() {
  emit("update-authority", selected.value[0]);
  onCloseDialog();
}

watch(modal, (val) => {
  if (val) {
    fetchList();
  }
});
</script>

<template>
  <!-- ผู้มีอำนาจออกคำสั่ง -->
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 70%">
      <DialogHeader
        :tittle="'เลือกผู้มีอำนาจออกคำสั่ง'"
        :close="onCloseDialog"
      />
      <q-separator />

      <q-card-section>
        <div class="col-12 q-col-gutter-sm">
          <div class="col-12 row q-col-gutter-md items-start">
            <div class="col-12 col-sm-4 col-md-4">
              <q-input
                v-model="search"
                outlined
                hide-bottom-space
                dense
                label="คำค้น"
              />
            </div>
            <q-checkbox
              keep-color
              v-model="isAct"
              label="แสดงเฉพาะรักษาการแทน"
              color="primary"
              @update:model-value="onAct"
            >
              <q-tooltip>แสดงเฉพาะรักษาการแทน </q-tooltip>
            </q-checkbox>
            <q-space />

            <div class="col-12 col-sm-6 col-md-3">
              <q-btn
                color="primary"
                icon="search"
                label="ค้นหา"
                class="full-width q-pa-sm"
                outline
                @click.prevent="onSearchData"
              >
              </q-btn>
            </div>
          </div>

          <div class="col-12">
            <d-table
              flat
              :columns="isAct ? columnsAct : columns"
              :rows="rows"
              row-key="key"
              dense
              selection="single"
              v-model:selected="selected"
              :rows-per-page-options="[10, 25, 50, 100]"
              @update:pagination="updatePagination"
            >
              <template v-slot:header-selection="scope">
                <q-checkbox
                  keep-color
                  color="primary"
                  dense
                  v-model="scope.checkBox"
                />
              </template>
              <template v-slot:header="props">
                <q-tr :props="props">
                  <q-th class="text-center"> </q-th>

                  <q-th
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <span class="text-weight-medium">
                      {{ getColumnLabel(col, isAct) }}</span
                    >
                  </q-th>
                </q-tr>
              </template>
              <template v-slot:body="props">
                <q-tr :props="props">
                  <q-td class="text-center">
                    <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>
              <template v-slot:pagination="scope">
                ทั้งหมด {{ total.toLocaleString() }} รายการ
                <q-pagination
                  v-model="page"
                  active-color="primary"
                  color="dark"
                  :max="Number(maxPaeg)"
                  size="sm"
                  boundary-links
                  direction-links
                  :max-pages="5"
                  @update:model-value="fetchList"
                ></q-pagination>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          :disable="selected.length === 0"
          label="เลือกผู้มีอำนาจออกคำสั่ง"
          color="public"
          @click="onSelectAuthority"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
