<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายชื่อลูกจ้างชั่วคราว
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="col-12 row items-center">
      <q-btn flat round color="primary" @click="clickAdd" icon="mdi-plus">
        <q-tooltip>เพิ่มข้อมูล</q-tooltip>
      </q-btn>
      <q-btn
        flat
        round
        color="primary"
        icon="mdi-account-arrow-right"
        @click="clickAddOrder"
      />
      <q-space />
      <div class="items-center" style="display: flex">
        <!-- ค้นหาข้อความใน table -->
        <q-input
          standout
          dense
          v-model="filter"
          ref="filterRef"
          outlined
          debounce="300"
          placeholder="ค้นหา"
          style="max-width: 200px"
          class="q-ml-sm"
        >
          <template v-slot:append>
            <q-icon v-if="filter == ''" name="search" />
            <q-icon
              v-if="filter !== ''"
              name="clear"
              class="cursor-pointer"
              @click="resetFilter"
            />
          </template>
        </q-input>
        <!-- แสดงคอลัมน์ใน table -->
        <q-select
          v-model="visibleColumnsEmployeeTemp"
          :display-value="$q.lang.table.columns"
          multiple
          outlined
          dense
          :options="columns"
          options-dense
          option-value="name"
          map-options
          emit-value
          style="min-width: 150px"
          class="gt-xs q-ml-sm"
        />
      </div>
    </div>
    <div class="col-12 q-pt-sm">
      <q-table
        flat
        bordered
        dense
        :rows="rows"
        :columns="columns"
        :visible-columns="visibleColumnsEmployeeTemp"
        :filter="filter"
        row-key="id"
        class="custom-header-table"
        :pagination-label="paginationLabel"
        v-model:pagination="pagination"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
            <q-th auto-width />
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props" class="cursor-pointer">
            <q-td key="no" :props="props" @click="redirectToPage(props.row.id)">
              {{ props.rowIndex + 1 }}
            </q-td>
            <q-td
              key="fullname"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.fullname }}
            </q-td>
            <q-td
              key="positionEmployeePosition"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.positionEmployeePosition }}
            </q-td>
            <q-td
              key="positionEmployeePositionSide"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.positionEmployeePositionSide }}
            </q-td>
            <q-td
              key="positionLine"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.positionLine }}
            </q-td>
            <q-td
              key="positionEmployeeGroup"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.positionEmployeeGroup }}
            </q-td>
            <q-td key="oc" :props="props" @click="redirectToPage(props.row.id)">
              {{ props.row.oc }}
            </q-td>
            <q-td
              key="amount"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.amount }}
            </q-td>
            <q-td
              key="govAge"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.govAge }}
            </q-td>
            <q-td
              key="dateAppoint"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.dateAppoint }}
            </q-td>
            <q-td
              key="dateStart"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.dateStart }}
            </q-td>
            <q-td
              key="salaryDate"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.salaryDate }}
            </q-td>
            <q-td
              key="refSalary"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.refSalary }}
            </q-td>
            <q-td
              key="age"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.age }}
            </q-td>
            <q-td
              key="fullnameOld"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.fullnameOld }}
            </q-td>
            <q-td
              key="createdAt"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.createdAt }}
            </q-td>
            <q-td
              key="isLeave"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.isLeave }}
            </q-td>
            <q-td
              key="leaveDateOrder"
              :props="props"
              @click="redirectToPage(props.row.id)"
            >
              {{ props.row.leaveDateOrder }}
            </q-td>

            <q-td auto-width>
              <q-btn
                icon="mdi-dots-vertical"
                size="12px"
                color="grey-7"
                flat
                round
                dense
              >
                <q-menu transition-show="jump-down" transition-hide="jump-up">
                  <q-list dense style="min-width: 160px">
                    <q-item
                      clickable
                      v-close-popup
                      @click="editDetail(props.row)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon
                          color="blue"
                          size="xs"
                          name="mdi-account-settings"
                        />
                      </q-item-section>
                      <q-item-section>กำหนดตำแหน่ง</q-item-section>
                    </q-item>
                    <q-separator />
                    <q-item
                      clickable
                      v-close-popup
                      @click="clickDelete(props.row.id)"
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon color="red" size="xs" name="mdi-delete" />
                      </q-item-section>
                      <q-item-section>ลบ</q-item-section>
                    </q-item>

                    <q-separator />
                  </q-list>
                </q-menu>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          <q-pagination
            v-model="pagination.page"
            active-color="primary"
            color="dark"
            :max="scope.pagesNumber"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
          ></q-pagination>
        </template>
      </q-table>
    </div>
  </q-card>
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 70vw; max-width: 70vw">
      <DialogHeader tittle="กำหนดตำแหน่ง" :close="modalOpenClose" />
      <q-separator />
      <q-card-section class="q-pa-sm">
        <d-table
          :rows="rowsPosition"
          :columns="columnsPosition"
          row-key="id"
          selection="single"
          v-model:selected="selectedPosition"
          :visible-columns="visibleColumnsPosition"
        >
          <template v-slot:body-selection="scope">
            <q-checkbox
              keep-color
              color="primary"
              dense
              v-model="scope.selected"
            />
          </template>
        </d-table>
      </q-card-section>
      <q-separator />
      <q-card-actions align="right">
        <q-btn
          dense
          unelevated
          label="บันทึก"
          color="public"
          @click="checkSave"
          class="q-px-md"
          ><!-- icon="mdi-content-save-outline"
        <q-tooltip>บันทึก</q-tooltip> -->
        </q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>

  <!-- dialog ส่งรายชื่อไปออกคำสั่ง -->
  <q-dialog v-model="modaladdOrder">
    <q-card style="width: 900px; max-width: 80vw">
      <DialogHeader
        tittle="ส่งรายชื่อไปออกคำสั่ง"
        :close="clickCloseSendModal"
      />
      <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"
                placeholder="ค้นหา"
                style="width: 850px; max-width: auto"
              >
                <template v-slot:append>
                  <q-icon name="search" />
                </template>
              </q-input>
            </q-toolbar>
          </div>
        </div>

        <d-table
          :rows="rowsOrder"
          :columns="columnsOrder"
          :visible-columns="visibleColumnsOrder"
          :filter="filter"
          row-key="id"
          selection="single"
          v-model:selected="selectedToOrder"
        >
          <template v-slot:body-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="positionEmployeePosition" :props="props">
                {{ props.row.positionEmployeePosition }}
              </q-td>
              <q-td key="positionEmployeePositionSide" :props="props">
                {{ props.row.positionEmployeePositionSide }}
              </q-td>
              <q-td key="positionLine" :props="props">
                {{ props.row.positionLine }}
              </q-td>
              <q-td key="positionEmployeeGroup" :props="props">
                {{ props.row.positionEmployeeGroup }}
              </q-td>
              <q-td key="oc" :props="props">
                {{ props.row.oc }}
              </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-tr>
          </template>
          <template v-slot:pagination="scope">
            <q-pagination
              v-model="pagination.page"
              active-color="primary"
              color="dark"
              :max="scope.pagesNumber"
              :max-pages="5"
              size="sm"
              boundary-links
              direction-links
            ></q-pagination>
          </template>
        </d-table>
      </q-card-section>

      <q-card-actions align="right" class="bg-white text-teal">
        <q-btn label="บันทึก" @click="checkSaveOrder" color="public" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, useAttrs } from "vue";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import type { QInput, QForm, QTableProps } from "quasar";
import { useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import type { treeTab } from "@/modules/05_placement/interface/index/Main";
import type {
  FormRegistryEmployee,
  ResponseEmployeeTemp,
} from "@/modules/08_registryEmployee/request/Main.ts";
import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";

const props = defineProps({
  next: {
    type: Function,
    default: () => console.log("not function"),
  },
  previous: {
    type: Function,
    default: () => console.log("not function"),
  },
});

const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const {
  typeRetire,
  success,
  messageError,
  showLoader,
  hideLoader,
  date2Thai,
  dialogMessage,
} = mixin;

const modaladdOrder = ref<boolean>(false);
const router = useRouter();
const myForm = ref<QForm>();
const filterRef = ref<QInput>();
const filter = ref<string>("");
const modal = ref<boolean>(false);
const id = ref<string>("");
const visibleColumnsModal = ref<String[]>(["no", "positionNum", "name"]);
const columnsModal = [
  { name: "no", align: "left", label: "ลำดับ", field: "no", sortable: true },
  {
    name: "positionNum",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    field: "positionNum",
    sortable: true,
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-สกุล",
    field: "name",
    sortable: true,
  },
];

const pagination = ref({
  sortBy: "desc",
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

const visibleColumnsOrder = ref<String[]>([
  "no",
  "fullname",
  "fullnameOld",
  "oc",
  "positionEmployeePosition",
  "positionEmployeePositionSide",
  "positionLine",
  "govAge",
  "positionEmployeeGroup",
  "dateAppoint",
  "refSalary",
  "dateStart",
  "createdAt",
  "salaryDate",
  "age",
  "amount",
  "isLeave",
  "leaveDateOrder",
]);

const visibleColumnsEmployeeTemp = ref<String[]>([]);
visibleColumnsEmployeeTemp.value = [
  "no",
  "fullname",
  "fullnameOld",
  "oc",
  "positionEmployeePosition",
  "positionEmployeePositionSide",
  "positionLine",
  "govAge",
  "positionEmployeeGroup",
  "dateAppoint",
  "refSalary",
  "dateStart",
  "createdAt",
  "salaryDate",
  "age",
  "amount",
  "isLeave",
  "leaveDateOrder",
];
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-สกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },

  {
    name: "positionEmployeePosition",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionEmployeePosition",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "positionEmployeePositionSide",
    align: "left",
    label: "ด้านของตำแหน่ง",
    sortable: true,
    field: "positionEmployeePositionSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "positionLine",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionLine",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },

  {
    name: "positionEmployeeGroup",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "positionEmployeeGroup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "oc",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "oc",
    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",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateStart",
    align: "left",
    label: "วันที่เริ่มปฎิบัติราชการ",
    sortable: true,
    field: "dateStart",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "salaryDate",
    align: "left",
    label: "วันที่แต่งตั้ง",
    sortable: true,
    field: "salaryDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "isLeave",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "isLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "leaveDateOrder",
    align: "left",
    label: "วันที่พ้นราชการ",
    sortable: true,
    field: "leaveDateOrder",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const rows = ref<FormRegistryEmployee[]>([]);

const selectedPosition = ref<any[]>([]);
const selectedToOrder = ref<any[]>([]);
const visibleColumnsPosition = ref<String[]>([
  "organizationOrganizationName",
  "organizationAgencyName",
  "organizationGovernmentAgencyName",
  "organizationShortNameName",
  "organizationTypeName",
  "organizationLevelName",
  "positionEmployeeLineName",
  "positionEmployeePositionName",
  "posNo",
]);

const columnsPosition = ref<QTableProps["columns"]>([
  {
    name: "organizationOrganizationName",
    align: "left",
    label: "หน่วยงาน",
    sortable: true,
    field: "organizationOrganizationName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organizationAgencyName",
    align: "left",
    label: "รหัสหน่วยงาน",
    sortable: true,
    field: "organizationAgencyName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organizationGovernmentAgencyName",
    align: "left",
    label: "รหัสส่วนราชการ",
    sortable: true,
    field: "organizationGovernmentAgencyName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organizationShortNameName",
    align: "left",
    label: "ชื่อย่อหน่วยงาน",
    sortable: true,
    field: "organizationShortNameName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organizationTypeName",
    align: "left",
    label: "ประเภทหน่วยงาน",
    sortable: true,
    field: "organizationTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "organizationLevelName",
    align: "left",
    label: "ระดับหน่วยงาน",
    sortable: true,
    field: "organizationLevelName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionEmployeeLineName",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionEmployeeLineName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionEmployeePositionName",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionEmployeePositionName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const rowsPosition = ref<any>([]);
const columnsOrder = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-สกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px; min-width: 200px",
    style: "font-size: 14px; ",
  },

  {
    name: "positionEmployeePosition",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionEmployeePosition",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "positionEmployeePositionSide",
    align: "left",
    label: "ด้านของตำแหน่ง",
    sortable: true,
    field: "positionEmployeePositionSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "positionLine",
    align: "left",
    label: "สายงาน",
    sortable: true,
    field: "positionLine",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },

  {
    name: "positionEmployeeGroup",
    align: "left",
    label: "กลุ่มงาน",
    sortable: true,
    field: "positionEmployeeGroup",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, {
        numeric: true,
        sensitivity: "base",
      }),
  },
  {
    name: "oc",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "oc",
    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",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateStart",
    align: "left",
    label: "วันที่เริ่มปฎิบัติราชการ",
    sortable: true,
    field: "dateStart",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "salaryDate",
    align: "left",
    label: "วันที่แต่งตั้ง",
    sortable: true,
    field: "salaryDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "isLeave",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "isLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "leaveDateOrder",
    align: "left",
    label: "วันที่พ้นราชการ",
    sortable: true,
    field: "leaveDateOrder",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    // sort: (a: string, b: string) =>
    //   a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const rowsOrder = ref<FormRegistryEmployee[]>([]);
const selected = ref([]);
onMounted(async () => {
  await nodeTree();
});

const checkNull = (text: string) =>
  text == null
    ? ""
    : text == "00000000-0000-0000-0000-000000000000"
    ? ""
    : text;

const getPosition = async (id: string) => {
  showLoader();
  await http
    .get(config.API.organizationEmployeePositionId(id))
    .then((res) => {
      const { result } = res.data;
      let data: any[] = [];
      result.map((r: any) => {
        data.push({
          id: checkNull(r.id),
          agency: checkNull(r.agency),
          conditionNote: checkNull(r.conditionNote),
          department: checkNull(r.department),
          government: checkNull(r.government),
          isActive: r.isActive,
          isCondition: r.isCondition,
          isDirector: r.isDirector,
          organizationUserNote: checkNull(r.organizationUserNote),
          qualification: checkNull(r.qualification),
          pile: checkNull(r.pile),
          posNo: checkNull(r.posNo),
          positionCondition: checkNull(r.positionCondition),
          positionMasterUserNote: checkNull(r.positionMasterUserNote),
          organizationOrder: checkNull(r.organizationOrder),
          organizationFaxId: checkNull(r.organizationFaxId),
          organizationLevelId: checkNull(r.organizationLevelId),
          organizationOrganizationId: checkNull(r.organizationOrganizationId),
          organizationTelExternalId: checkNull(r.organizationTelExternalId),
          organizationTelInternalId: checkNull(r.organizationTelInternalId),
          organizationTypeId: checkNull(r.organizationTypeId),
          positionEmployeeStatusId: checkNull(r.positionEmployeeStatusId),
          positionEmployeeLineId: checkNull(r.positionEmployeeLineId),
          positionEmployeePositionId: checkNull(r.positionEmployeePositionId),
          organizationAgencyId: checkNull(r.organizationAgencyId),
          organizationGovernmentAgencyId: checkNull(
            r.organizationGovernmentAgencyId
          ),
          organizationShortNameId: checkNull(r.organizationShortNameId),
          organizationFaxName: checkNull(r.organizationFaxName),
          organizationLevelName: checkNull(r.organizationLevelName),
          organizationOrganizationName: checkNull(
            r.organizationOrganizationName
          ),
          organizationTelExternalName: checkNull(r.organizationTelExternalName),
          organizationTelInternalName: checkNull(r.organizationTelInternalName),
          organizationTypeName: checkNull(r.organizationTypeName),
          positionEmployeeStatusName: checkNull(r.positionEmployeeStatusName),
          positionEmployeeLineName: checkNull(r.positionEmployeeLineName),
          positionEmployeePositionName: checkNull(
            r.positionEmployeePositionName
          ),
          organizationAgencyName: checkNull(r.organizationAgencyName),
          organizationGovernmentAgencyName: checkNull(
            r.organizationGovernmentAgencyName
          ),
          organizationShortNameName: checkNull(r.organizationShortNameName),
          positionEmployeeLevels: r.positionEmployeeLevels,
          positionEmployeePositionSides: r.positionEmployeePositionSides,
          use: r.use,
        });
      });

      const index = data.findIndex((r: any) => r.use == true);
      if (index >= 0) {
        selectedPosition.value = [data[index]];
      }

      rowsPosition.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};
const attrs = ref<any>(useAttrs());

const clickAddOrder = () => {
  modaladdOrder.value = true;
  const filteredRows = rowsOrder.value.filter(
    (row) => row.positionEmployeePosition !== null
  );
  rowsOrder.value = filteredRows;
};

const clickCloseSendModal = () => {
  modaladdOrder.value = false;
};

const checkSave = async () => {
  if (selectedPosition.value.length == 0) {
    dialogMessage(
      $q,
      "ไม่สามารถบันทึกข้อมูลได้",
      "กรุณาเลือกตำแหน่ง",
      "warning",
      undefined,
      "orange",
      undefined,
      undefined,
      true
    );
    return;
  } else {
    await savePosition();
  }
};

const checkSaveOrder = async () => {
  if (selectedToOrder.value.length == 0) {
    dialogMessage(
      $q,
      "ไม่สามารถบันทึกข้อมูลได้",
      "กรุณาเลือกตำแหน่ง",
      "warning",
      undefined,
      "orange",
      undefined,
      undefined,
      true
    );
    return;
  } else {
    await saveOrder();
  }
};

const savePosition = async () => {
  showLoader();
  const data = {
    organizationEmployeeId: selectedPosition.value[0].id,
  };
  await http
    .put(config.API.organizationEmployeePositionId(id.value), data)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await nodeTree();
      modalOpenClose();
    });
};

const saveOrder = async () => {
  //   showLoader();
  //   const data = {
  //     organizationEmployeeId: selectedPosition.value[0].id,
  //   };
  //   await http
  //     .put(config.API.organizationEmployeePositionId(id.value), data)
  //     .then((res) => {
  //       success($q, "บันทึกข้อมูลสำเร็จ");
  //     })
  //     .catch((e) => {
  //       messageError($q, e);
  //     })
  //     .finally(async () => {
  //       await nodeTree();
  //       modalOpenClose();
  //     });
};

const modalOpenClose = () => {
  modal.value = !modal.value;
  if (!modal.value) {
    selectedPosition.value = [];
    rowsPosition.value = [];
    id.value = "";
  }
};

const next = (id: string) => {
  router.push(`/registryEmployee/${id}`);
};

const paginationLabel = (start: number, end: number, total: number) => {
  //   if (props.paging == true)
  //     return " " + start + " ใน " + end + " จากจำนวน " + total + " รายการ";
  //   else
  return start + "-" + end + " ใน " + total;
};

const resetFilter = () => {
  // reset ค่าที่ค้นหาเมื่อกดปุ่ม X ในกล่องค้นหา
  filter.value = "";
  filterRef.value!.focus();
};

const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};

const clickClose = async () => {
  //   if (editRow.value == true) {
  //   dialogMessage(
  //     $q,
  //     "ข้อมูลมีการแก้ไข",
  //     "ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?",
  //     "mdi-help-circle-outline",
  //     "ตกลง",
  //     "orange",
  //     () => (modal.value = false),
  //     undefined
  //   );
  //   } else {
  modal.value = false;
  //     next.value = false;
  //     previous.value = false;
  //   }
};

const clickAdd = () => {
  //   modal.value = true;

  router.push(`/registryEmployee/add`);
  //   router.push(`/placement/detail`);
};

// ดูรายการแก้ไขรายชื่อ
const redirectToPage = (id?: string) => {
  router.push(`/registry/${id}`);
};
const editDetail = async (row: any) => {
  await getPosition(row.id);
  console.log(row);
  id.value = row.id;
  modal.value = true;
};

const clickDelete = (id: string) => {
  $q.dialog({
    title: "ยืนยันการลบข้อมูล",
    message: "ต้องการลบข้อมูลนี้ใช่หรือไม่?",
    cancel: {
      flat: true,
      color: "negative",
    },
    persistent: true,
  })
    .onOk(async () => {
      showLoader();
      await http
        .delete(config.API.profileInforId(id))
        .then((res) => {
          success($q, "ลบข้อมูลการสอบสำเร็จ");
          showEmployeeTemp();
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    })
    .onCancel(() => {})
    .onDismiss(() => {});
};

const nodeTree = async () => {
  showLoader();
  await http
    .get(config.API.profileOrganizRoot)
    .then((res: any) => {
      const data = res.data.result;
      if (data.length > 0) {
        selected.value = data[0].id;
      }
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      await showEmployeeTemp();
      await showEmployeeTempOrder();
    });
};

const showEmployeeTemp = async () => {
  let cirteria = [];

  cirteria.push({
    criteriaType: "employee_class",
    criteriaValue: "temp",
  });

  cirteria.push({
    criteriaType: "is_retire",
    criteriaValue: "false",
  });

  if (selected.value == null || selected.value == "") return;
  showLoader();
  await http
    .post(config.API.searchProfileTemp("all"), {
      criterias: cirteria,
    })
    .then((res) => {
      let data = res.data.result;
      rows.value = [];
      data.map((e: ResponseEmployeeTemp) => {
        rows.value.push({
          id: e.id,
          fullname: e.fullname,
          fullnameOld: e.fullnameOld,
          position: e.position,
          positionPathSide: e.positionPathSide,
          positionLine: e.positionLine,
          govAge: e.govAge,
          positionEmployeePosition: e.positionEmployeePosition,
          positionEmployeePositionSide: e.positionEmployeePositionSide,
          positionEmployeeGroup: e.positionEmployeeGroup,
          oc: e.oc,
          age: e.age,
          amount: e.amount == null ? "" : e.amount.toLocaleString(),
          refSalary: e.refSalary,
          dateAppoint:
            e.dateAppoint == null ? null : date2Thai(new Date(e.dateAppoint)),
          dateStart:
            e.dateStart == null ? null : date2Thai(new Date(e.dateStart)),
          createdAt:
            e.createdAt == null ? null : date2Thai(new Date(e.createdAt)),
          isLeave: e.isLeave == false ? "ครอง" : `${typeRetire(e.leaveReason)}`,
          leaveDateOrder:
            e.leaveDateOrder == null
              ? null
              : date2Thai(new Date(e.leaveDateOrder)),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const showEmployeeTempOrder = async () => {
  let cirteria = [];

  cirteria.push({
    criteriaType: "employee_class",
    criteriaValue: "temp",
  });

  cirteria.push({
    criteriaType: "is_retire",
    criteriaValue: "false",
  });

  if (selected.value == null || selected.value == "") return;
  showLoader();
  await http
    .post(config.API.searchProfileTemp("all"), {
      criterias: cirteria,
    })
    .then((res) => {
      let data = res.data.result;
      rowsOrder.value = [];
      data.map((e: ResponseEmployeeTemp) => {
        rowsOrder.value.push({
          id: e.id,
          fullname: e.fullname,
          fullnameOld: e.fullnameOld,
          position: e.position,
          positionPathSide: e.positionPathSide,
          positionLine: e.positionLine,
          govAge: e.govAge,
          positionEmployeePosition: e.positionEmployeePosition,
          positionEmployeePositionSide: e.positionEmployeePositionSide,
          positionEmployeeGroup: e.positionEmployeeGroup,
          oc: e.oc,
          age: e.age,
          amount: e.amount == null ? "" : e.amount.toLocaleString(),
          refSalary: e.refSalary,
          dateAppoint:
            e.dateAppoint == null ? null : date2Thai(new Date(e.dateAppoint)),
          dateStart:
            e.dateStart == null ? null : date2Thai(new Date(e.dateStart)),
          createdAt:
            e.createdAt == null ? null : date2Thai(new Date(e.createdAt)),
          isLeave: e.isLeave == false ? "ครอง" : `${typeRetire(e.leaveReason)}`,
          leaveDateOrder:
            e.leaveDateOrder == null
              ? null
              : date2Thai(new Date(e.leaveDateOrder)),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      console.log(rowsOrder);
    });
};

const onSelected = async (id: string) => {
  //   await fetchPositionNumber(id);
};

const deleteData = async (id: string) => {};
</script>
<style lang="scss">
.icon-color {
  color: #4154b3;
}
.custom-header-table {
  max-height: 64vh;
  .q-table tr:nth-child(odd) td {
    background: white;
  }
  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
    z-index: 1;
  }
  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }
  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
