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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useRegistryEmp } from "@/modules/08_registryEmployee/stores/registry-employee";

/** importType*/
import type { QTableProps } from "quasar";
import type { DataEmployee } from "@/modules/08_registryEmployee/interface/response/Employee";

/** importComponents*/
import DialogHeader from "@/components/DialogHeader.vue";
import DialogCreateCommand from "@/modules/18_command/components/DialogCreateCommand.vue";

const $q = useQuasar();
const {
  onSearchDataTable,
  messageError,
  showLoader,
  hideLoader,
  date2Thai,
  dialogConfirm,
  dialogMessageNotify,
} = useCounterMixin();
const { statusText } = useRegistryEmp();

/**props*/
const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  fetchData: {
    type: Function,
    require: true,
  },
});

const filter = ref<string>(""); //ค้นหารายชื่อไปออกคำสั่ง
const rows = ref<DataEmployee[]>([]); //รายชื่อไปออกคำสั่ง
const rowsMain = ref<DataEmployee[]>([]); //รายชื่อไปออกคำสั่ง
const selected = ref<DataEmployee[]>([]); //รายชื่อที่เลือกไปออกคำสั่ง
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: (row) => rows.value.indexOf(row) + 1,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px; min-width: 200px",
    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; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "draftOrganizationOrganization",
    align: "left",
    label: "หน่วยงานที่รับการบรรจุ",
    sortable: true,
    field: "draftOrganizationOrganization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "govAge",
    align: "left",
    label: "อายุราชการ(ปี)",
    sortable: true,
    field: "govAge",
    format(val) {
      return val;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateEmployment",
    align: "left",
    label: "วันที่จ้าง",
    sortable: true,
    field: "dateEmployment",
    format: (val) => date2Thai(val),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },

  {
    name: "salaryDate",
    align: "left",
    label: "วันที่แต่งตั้ง",
    sortable: true,
    field: "salaryDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "age",
    align: "left",
    label: "อายุ",
    sortable: true,
    field: "age",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่สร้าง",
    sortable: true,
    field: "createdAt",
    format(val) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateRetireLaw",
    align: "left",
    label: "วันที่พ้นราชการ",
    sortable: true,
    field: "dateRetireLaw",
    format(val) {
      return date2Thai(val);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "statustext",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "statustext",
    format(val, row) {
      return statusText(row.draftOrgEmployeeStatus);
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<String[]>([
  "no",
  "citizenId",
  "fullname",
  "draftOrganizationOrganization",
  "govAge",
  "dateEmployment",
  "age",
  "createdAt",
  "dateRetireLaw",
  "statustext",
]);

const modalCommand = ref<boolean>(false); //สร้างคำสั่ง

/** ฟังก์ชันยืนยันการส่งออกคำสั่ง*/
function onClickSendOrder() {
  if (selected.value.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกคนออกคำสั่ง");
  } else {
    dialogConfirm(
      $q,
      () => {
        modalCommand.value = true;
        closeDialog();
      },
      "ยื่นยันการส่งรายชื่อไปออกคำสั่ง",
      "ต้องการยืนยันการส่งรายชื่อไปออกคำสั่งนี้หรือไม่ ?"
    );
  }
}

/** ฟังก์ชันดึงข้อมูลราชชื่อส่งออกคำสั่ง*/
function fetchList() {
  selected.value = [];
  showLoader();
  http
    .get(config.API.registryNew("-employee") + `/temp`)
    .then((res) => {
      rows.value = res.data.result.data.map((e: DataEmployee) => ({
        ...e,
        profileId: e.id,
      }));

      rowsMain.value = rows.value;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ฟังก์ชันปิด Popup*/
function closeDialog() {
  modal.value = false;
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/**
 * ทำเมื่อ modal เป็น true
 * ทำการเรียก fetchList  เพื่อข้อมูลราชชื่อส่งออกคำสั่ง
 */
watch(
  () => modal.value,
  () => {
    modal.value && fetchList();
  }
);
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 70%">
      <DialogHeader tittle="ส่งรายชื่อไปออกคำสั่ง" :close="closeDialog" />
      <q-separator />
      <q-card-section class="q-pt-none">
        <div class="row">
          <div class="col-12">
            <q-toolbar style="padding: 0">
              <q-space />
              <q-input
                borderless
                outlined
                dense
                v-model="filter"
                ref="filterRef"
                placeholder="ค้นหา"
                @keydown.enter.pervent="serchDataTable"
                style="max-width: auto"
              >
                <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"
                style="min-width: 140px"
                class="gt-xs q-ml-sm"
              />
            </q-toolbar>
          </div>
          <div class="col-12">
            <d-table
              :rows="rows"
              :columns="columns"
              :visible-columns="visibleColumns"
              row-key="id"
              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 !== null && col.value !== "" ? col.value : "-"
                      }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </d-table>
          </div>
        </div>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn
          label="ส่งไปออกคำสั่ง"
          @click="onClickSendOrder"
          color="public"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- dialog สร้างคำสั่ง -->
  <DialogCreateCommand
    v-model:modal="modalCommand"
    :command-type-code="'C-PM-21'"
    :persons="selected"
  />
</template>

<style scoped></style>
