<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-tooltip>ส่งรายชื่อไปออกคำสั่ง</q-tooltip>
      </q-btn>
      <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">
      <d-table
        :rows="rows"
        :columns="columns"
        :visible-columns="visibleColumnsEmployeeTemp"
        :filter="filter"
        row-key="id"
      >
        <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.row.status)"
            >
              {{ props.rowIndex + 1 }}
            </q-td>
            <q-td
              key="fullname"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.fullname }}
            </q-td>
            <q-td
              key="newAgency"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              <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"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              <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="positionEmployeePosition"
              :props="props"
              @click="redirectToPage(props.row.id,props.row.status)"
            >
              {{ props.row.positionEmployeePosition }}
            </q-td>
            <q-td
              key="positionEmployeePositionSide"
              :props="props"
              @click="redirectToPage(props.row.id,props.row.status)"
            >
              {{ props.row.positionEmployeePositionSide }}
            </q-td>
            <q-td
              key="positionLine"
              :props="props"
              @click="redirectToPage(props.row.id,props.row.status)"
            >
              {{ props.row.positionLine }}
            </q-td>
            <q-td
              key="positionEmployeeGroup"
              :props="props"
              @click="redirectToPage(props.row.id,props.row.status)"
            >
              {{ props.row.positionEmployeeGroup }}
            </q-td>
            <q-td key="oc" :props="props" @click="redirectToPage(props.row.id,props.row.status)">
              {{ props.row.oc }}
            </q-td> -->
            <q-td
              key="amount"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.amount }}
            </q-td>
            <q-td
              key="govAge"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.govAge }}
            </q-td>
            <q-td
              key="dateAppoint"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.dateAppoint }}
            </q-td>
            <q-td
              key="dateStart"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.dateStart }}
            </q-td>
            <q-td
              key="salaryDate"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.salaryDate }}
            </q-td>
            <q-td
              key="refSalary"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.refSalary }}
            </q-td>
            <q-td
              key="age"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.age }}
            </q-td>
            <q-td
              key="fullnameOld"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.fullnameOld }}
            </q-td>
            <q-td
              key="createdAt"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.createdAt }}
            </q-td>
            <q-td
              key="isLeave"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.isLeave }}
            </q-td>

            <q-td
              key="leaveDateOrder"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.leaveDateOrder }}
            </q-td>
            <q-td
              key="statustext"
              :props="props"
              @click="redirectToPage(props.row.id, props.row.status)"
            >
              {{ props.row.statustext }}
            </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)"
                      :disable="
                        props.row.status == 'REPORT' ||
                        props.row.status == 'DONE'
                      "
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon
                          :color="
                            props.row.status == 'REPORT' ||
                            props.row.status == 'DONE'
                              ? 'grey'
                              : '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)"
                      :disable="
                        props.row.status == 'REPORT' ||
                        props.row.status == 'DONE'
                      "
                    >
                      <q-item-section
                        style="min-width: 0px"
                        avatar
                        class="q-py-sm"
                      >
                        <q-icon
                          :color="
                            props.row.status == 'REPORT' ||
                            props.row.status == 'DONE'
                              ? 'grey'
                              : 'red-7'
                          "
                          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>
      </d-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="multiple"
          v-model:selected="selectedToOrder"
        >
          <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="checkSaveOrder" color="public" />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } 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,
  dialogRemove,
  dialogConfirm,
  dialogMessageNotify,
} = 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 visibleColumnsOrder = ref<String[]>([
  "no",
  "fullname",
  "fullnameOld",
  "oc",
  "positionEmployeePosition",
  "positionEmployeePositionSide",
  "positionLine",
  "govAge",
  "positionEmployeeGroup",
  "dateAppoint",
  "refSalary",
  "dateStart",
  "createdAt",
  "salaryDate",
  "age",
  "amount",
  "statustext",
  "leaveDateOrder",
  "newAgency",
  "currentAgency",
]);

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

// "isLeave",
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: "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: "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" }),
  },
  {
    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",
      }),
  },
]);
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: "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: "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" }),
  },
  {
    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",
      }),
  },
]);
const rowsOrder = ref<FormRegistryEmployee[]>([]);
const filters = 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;
      modal.value = true;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const clickAddOrder = () => {
  modaladdOrder.value = true;
  const row = filters.value.filter(
    (r: FormRegistryEmployee) => r.status == "PENDING"
  );

  rowsOrder.value = row;
};

const clickCloseSendModal = () => {
  modaladdOrder.value = false;
};
const checkSave = () => {
  dialogConfirm($q, async () => await saveData());
};
const saveData = async () => {
  if (selectedPosition.value.length == 0) {
    dialogMessageNotify(
      $q,
      "ไม่สามารถบันทึกข้อมูลได้ กรุณาเลือกตำแหน่ง"
      // "กรุณาเลือกตำแหน่ง",
      // "warning",
      // undefined,
      // "orange",
      // undefined,
      // undefined,
      // true
    );
    return;
  } else {
    await savePosition();
  }
};
const checkSaveOrder = () => {
  if (selectedToOrder.value.length == 0) {
    dialogMessageNotify($q, "กรุณาเลือกคนออกคำสั่ง");
  } else dialogConfirm($q, () => SaveOrder());
};
const SaveOrder = async () => {
  // ส่งไปออกคำสั่ง
  let pId: string[] = [];
  selectedToOrder.value.forEach((e: any) => {
    pId.push(e.id);
  });
  let data = {
    id: pId,
  };
  showLoader();
  await http
    .post(config.API.organizationEmployeeSendOrder, data)
    .then((res: any) => {
      // console.log(res);
      success($q, "บันทึกสำเร็จ");
    })
    .catch((e: any) => {
      // console.log(e);
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      modaladdOrder.value = false;
      await showEmployeeTemp();
      selectedToOrder.value = [];
    });
};

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 modalOpenClose = () => {
  modal.value = !modal.value;
  if (!modal.value) {
    selectedPosition.value = [];
    rowsPosition.value = [];
    id.value = "";
  }
};

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

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 clickAdd = () => {
  //   modal.value = true;

  router.push(`/registry-employee/add`);
  //   router.push(`/placement/detail`);
};

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

const clickDelete = (id: string) => {
  dialogRemove($q, async () => await deleteData(id));
};

const deleteData = async (id: string) => {
  showLoader();
  await http
    .delete(config.API.profileInforId(id))
    .then((res) => {
      success($q, "ลบข้อมูลสำเร็จ");
      showEmployeeTemp();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

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 () => {
  showLoader();

  let cirteria = [];

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

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

  if (selected.value == null) return;
  await http
    .post(config.API.searchProfileTemp("all"), {
      criterias: cirteria,
    })
    .then((res) => {
      const data = res.data.result;
      rows.value = [];
      filters.value = [];
      let list: FormRegistryEmployee[] = [];
      data.map((e: ResponseEmployeeTemp) => {
        list.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)),
          newAgency: "",
          currentAgency: "",
          draftPositionEmployee: e.draftPositionEmployee,
          draftOrganizationOrganization: e.draftOrganizationOrganization,
          status: e.draftOrgEmployeeStatus ?? "",
          statustext: statusText(e.draftOrgEmployeeStatus ?? ""),
        });
      });
      rows.value = list;
      filters.value = list;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const statusText = (val: String) => {
  switch (val) {
    case "WAITTING":
      return "รอดำเนินการ";
    case "PENDING":
      return "เลือกตำแหน่งแล้ว";
    case "APPROVE":
      return "อนุมัติ";
    case "REJECT":
      return "ไม่อนุมัติ";
    case "REPORT":
      return "ส่งรายชื่อไปออกคำสั่ง";
    case "DONE":
      return "ออกคำสั่งเสร็จแล้ว";

    default:
      return "-";
  }
};

// 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)),
//           newAgency: "",
//           currentAgency: "",
//           draftPositionEmployee: e.draftPositionEmployee,
//           draftOrganizationOrganization: e.draftOrganizationOrganization,
//         });
//       });
//     })
//     .catch((e) => {
//       messageError($q, e);
//     })
//     .finally(() => {
//       hideLoader();
//       //   console.log(rowsOrder);
//     });
// };

const onSelected = async (id: string) => {
  //   await fetchPositionNumber(id);
};
</script>
<style lang="scss"></style>
