<script setup lang="ts">
import { ref, watch } from "vue";
import type { FormRegistryEmployee } from "../interface/request/Main";
import { useQuasar, type QTableProps, QInput } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";

const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  success,
  messageError,
  showLoader,
  hideLoader,
  dialogConfirm,
  dialogMessageNotify,
} = mixin; //ฟังก์ชันกลางที่ใช้ในหน้านี้

const $q = useQuasar();

const props = defineProps({
  modal: {
    type: Boolean,
    default: false,
  },
  rows: {
    type: Object,
    default: [],
  },
  fetchNewList: {
    type: Function,
    default: () => {
      /* ฟังก์ชั่น get รายการข้อมูลในหน้าหลักใหม่ */
    },
  },
  closeDialog: {
    type: Function,
    default: () => {
      /* ฟังก์ชั่นปิด dialog ส่งไปออกคำสั่ง */
    },
  },
});

const filter = ref<string>("");
const filterRef = ref<QInput>();
// visible columns ตารางใน dialog ส่งไปออกคำสั่ง
const visibleColumnsOrder = ref<string[]>([
  "no",
  "fullname",
  "fullnameOld",
  "oc",
  "positionEmployeePosition",
  "positionEmployeePositionSide",
  "positionLine",
  "govAge",
  "positionEmployeeGroup",
  "dateAppoint",
  "refSalary",
  "dateStart",
  "createdAt",
  "salaryDate",
  "age",
  "amount",
  "statustext",
  "leaveDateOrder",
  "newAgency",
  "currentAgency",
]);

// คอลัมน์ในตาราง
const columnsOrder = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "newAgency",
    align: "left",
    label: "หน่วยงานที่รับการบรรจุ",
    sortable: true,
    field: "newAgency",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "currentAgency",
    align: "left",
    label: "หน่วยงานปัจจุบัน",
    sortable: true,
    field: "currentAgency",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "amount",
    align: "left",
    label: "ค่าจ้าง",
    sortable: true,
    field: "amount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "govAge",
    align: "left",
    label: "อายุราชการ(ปี)",
    sortable: true,
    field: "govAge",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "dateAppoint",
    align: "left",
    label: "วันที่จ้าง",
    sortable: true,
    field: "dateAppoint",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateStart",
    align: "left",
    label: "วันที่เริ่มปฎิบัติราชการ",
    sortable: true,
    field: "dateStart",
    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: "refSalary",
    align: "left",
    label: "เอกสารอ้างอิง",
    sortable: true,
    field: "refSalary",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "age",
    align: "left",
    label: "อายุ",
    sortable: true,
    field: "age",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "fullnameOld",
    align: "left",
    label: "ชื่อ-สกุล(เดิม)",
    sortable: true,
    field: "fullnameOld",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่สร้าง",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "leaveDateOrder",
    align: "left",
    label: "วันที่พ้นราชการ",
    sortable: true,
    field: "leaveDateOrder",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "statustext",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "statustext",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
]);

// checkbox เลือกคนไปออกคำสั่ง
const selected = ref<any>([]);
const save = () => {
  if (selected.value.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกคนออกคำสั่ง");
  } else dialogConfirm($q, () => sendToCommand());
};

// post ส่งไปออกคำสั่ง
const sendToCommand = async () => {
  let pId: string[] = [];
  selected.value.forEach((e: any) => {
    pId.push(e.id);
  });
  let data = {
    id: pId,
  };
  showLoader();
  await http
    .post(config.API.organizationEmployeeSendOrder, data)
    .then((res: any) => {
      success($q, "บันทึกสำเร็จ");
    })
    .catch((e: any) => {
      messageError($q, e);
    })
    .finally(async () => {
      props.fetchNewList();
      props.closeDialog();
      selected.value = [];
      hideLoader();
    });
};

// เลือกรายการเฉพาะคนที่มีสถานะ PENDING (เลือกตำแหน่งแล้ว)
const rowsOrder = ref<FormRegistryEmployee[]>([]);
const filterRowData = () => {
  rowsOrder.value = props.rows.filter(
    (r: FormRegistryEmployee) => r.status == "PENDING"
  );
};

// เช็ค props modal ทำการ filter เมื่อคลิก icon ส่งไปออกคำสั่ง
watch(props, () => {
  if (props.modal === true && props.rows) {
    filterRowData();
    visibleColumnsOrder.value = [
      "no",
      "fullname",
      "fullnameOld",
      "oc",
      "positionEmployeePosition",
      "positionEmployeePositionSide",
      "positionLine",
      "govAge",
      "positionEmployeeGroup",
      "dateAppoint",
      "refSalary",
      "dateStart",
      "createdAt",
      "salaryDate",
      "age",
      "amount",
      "statustext",
      "leaveDateOrder",
      "newAgency",
      "currentAgency",
    ];
  }
});
</script>

<template>
  <q-dialog v-model="props.modal">
    <q-card style="width: 900px; max-width: 80vw">
      <DialogHeader tittle="ส่งรายชื่อไปออกคำสั่ง" :close="props.closeDialog" />
      <q-separator />
      <q-card-section class="q-pt-none">
        <div class="row justify-end">
          <div class="col-5">
            <q-toolbar style="padding: 0">
              <q-input
                borderless
                outlined
                dense
                debounce="300"
                v-model="filter"
                ref="filterRef"
                placeholder="ค้นหา"
                style="width: 850px; max-width: auto"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
              <q-select
                v-model="visibleColumnsOrder"
                multiple
                outlined
                dense
                options-dense
                :display-value="$q.lang.table.columns"
                emit-value
                map-options
                :options="columnsOrder"
                option-value="name"
                options-cover
                style="min-width: 150px"
                class="gt-xs q-ml-sm"
              />
            </q-toolbar>
          </div>
        </div>

        <d-table
          :rows="rowsOrder"
          :columns="columnsOrder"
          :visible-columns="visibleColumnsOrder"
          :filter="filter"
          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 key="no" :props="props">
                {{ props.rowIndex + 1 }}
              </q-td>
              <q-td key="fullname" :props="props">
                {{ props.row.fullname }}
              </q-td>
              <q-td key="newAgency" :props="props">
                <div
                  class="col-12"
                  v-if="
                    props.row.draftOrganizationOrganization == null &&
                    props.row.draftPositionEmployee == null
                  "
                >
                  <div class="text-weight-medium">
                    {{ "-" }}
                  </div>
                </div>
                <div class="col-12" v-else>
                  <div class="text-weight-medium">
                    {{ props.row.draftOrganizationOrganization ?? "-" }}
                  </div>
                  <div class="text-weight-light">
                    {{ props.row.draftPositionEmployee ?? "-" }}
                  </div>
                </div>
              </q-td>
              <q-td key="currentAgency" :props="props">
                <div
                  class="col-12"
                  v-if="props.row.oc == null && props.row.position == null"
                >
                  <div class="text-weight-medium">
                    {{ "-" }}
                  </div>
                </div>
                <div class="col-12" v-else>
                  <div class="text-weight-medium">
                    {{ props.row.oc ?? "-" }}
                  </div>
                  <div class="text-weight-light">
                    {{ props.row.position ?? "-" }}
                  </div>
                </div>
              </q-td>

              <q-td key="amount" :props="props">
                {{ props.row.amount }}
              </q-td>
              <q-td key="govAge" :props="props">
                {{ props.row.govAge }}
              </q-td>
              <q-td key="dateAppoint" :props="props">
                {{ props.row.dateAppoint }}
              </q-td>
              <q-td key="dateStart" :props="props">
                {{ props.row.dateStart }}
              </q-td>
              <q-td key="salaryDate" :props="props">
                {{ props.row.salaryDate }}
              </q-td>
              <q-td key="refSalary" :props="props">
                {{ props.row.refSalary }}
              </q-td>
              <q-td key="age" :props="props">
                {{ props.row.age }}
              </q-td>
              <q-td key="fullnameOld" :props="props">
                {{ props.row.fullnameOld }}
              </q-td>
              <q-td key="createdAt" :props="props">
                {{ props.row.createdAt }}
              </q-td>
              <q-td key="isLeave" :props="props">
                {{ props.row.isLeave }}
              </q-td>

              <q-td key="leaveDateOrder" :props="props">
                {{ props.row.leaveDateOrder }}
              </q-td>
              <q-td key="statustext" :props="props">
                {{ props.row.statustext }}
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn label="ส่งไปออกคำสั่ง" @click="save" color="public" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>
