<!-- =============================== -->
<!-- หน้าตำแหน่งประเภท สายงาน -->
<!-- component เพิ่มตำแหน่งในดรอบดาวน์ ของ โครงสร้างอัตรากำลัง -->
<!-- เพื่อให้มาเลือกในหน้า Mapping -->
<template>
  <q-form ref="myForm">
    <Table
      :rows="rows"
      :columns="columns"
      :filter="filter"
      :visible-columns="visibleColumns"
      v-model:inputfilter="filter"
      v-model:inputvisible="visibleColumns"
      v-model:editvisible="editvisible"
      :add="clickAdd"
      :deleted="clickDelete"
      :cancel="clickCancel"
      :publish="clickPublish"
      :publicData="version === 'published'"
      :history="true"
      :boss="true"
      :saveNoDraft="true"
    >
      <template #columns="props">
        <q-tr :props="props">
          <q-td auto-width>
            <q-icon
              class="q-mr-sm"
              size="15px"
              color="primary"
              name="mdi-bookmark"
              v-if="props.row.isDirector"
            ></q-icon>
          </q-td>
          <q-td
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            @click="selectData(props.row)"
            class="cursor-pointer"
          >
            <!-- <div v-if="col.name == 'isDirector'" class="table_ellipsis">
              <q-icon
                class="q-mr-sm"
                size="15px"
                color="primary"
                name="mdi-bookmark"
                v-if="props.row.isDirector"
              ></q-icon>
            </div> -->
            <div v-if="col.name == 'isActive'" class="table_ellipsis">
              <div v-if="!editvisible">
                <q-icon
                  v-if="col.value == false"
                  name="mdi-close"
                  color="red"
                  class="text-h5"
                />
                <q-icon
                  v-else
                  name="mdi-check"
                  color="positive"
                  class="text-h5"
                />
              </div>
              <q-toggle
                v-else
                v-model="props.row.isActive"
                dense
                color="green"
                @update:model-value="
                  clickIsActive(props.row.id, props.row.isActive)
                "
              />
            </div>
            <div v-else class="table_ellipsis">
              {{ col.value }}
            </div>
            <!-- <div class="">
              {{ col.value }}
            </div> -->
          </q-td>
          <q-td auto-width>
            <q-btn
              color="info"
              flat
              dense
              round
              size="14px"
              icon="mdi-history"
              @click="clickHistory(props.row)"
            />
          </q-td>
        </q-tr>
      </template>
    </Table>
  </q-form>
  <!-- popup Edit window-->
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 700px">
      <q-form ref="myForm">
        <DialogHeader
          :tittle="`${modalEdit ? 'แก้ไข' : 'สร้าง'}โครงสร้างและกรอบอัตรากำลัง`"
          :close="clickClose"
        />
        <q-separator />
        <q-card-section class="q-p-sm">
          <div
            class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs"
          >
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionTypeId"
                :rules="[(val:any) => !!val || `${'กรุณาเลือกตำแหน่งประเภท'}`]"
                :label="`${'ตำแหน่งประเภท'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="positionTypeOptions"
                option-value="id"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                @filter="positionTypeFilterFn"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionLineId"
                :rules="[(val:any) => !!val || `${'กรุณาเลือกสายงาน'}`]"
                :label="`${'สายงาน'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="positionLineOptions"
                option-value="id"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                @filter="positionLineFilterFn"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionPathId"
                :rules="[(val:any) => !!val || `${'กรุณาเลือกตำแหน่ง'}`]"
                :label="`${'ตำแหน่ง'}`"
                @update:modelValue="clickEditRowPositionPath(positionPathId)"
                emit-value
                map-options
                option-label="name"
                :options="positionPathOptions"
                option-value="id"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                @filter="positionPathFilterFn"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                multiple
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionPathSideId"
                :label="`${'ด้าน/สาขา'}`"
                @update:modelValue="clickEditRow"
                option-label="name"
                :options="positionPathSideOptions"
                option-value="id"
                use-input
                use-chips
                input-debounce="0"
                @filter="positionPathSideFilterFn"
                color="primary"
              />
              <!-- :rules="[(val) => !!val || `${'กรุณาเลือกด้าน/สาขา'}`]" -->
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionExecutiveId"
                :label="`${'ตำแหน่งทางการบริหาร'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="positionExecutiveOptions"
                option-value="id"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                @filter="positionExecutiveFilterFn"
                color="primary"
              />
              <!-- :rules="[
                  (val) => !!val || `${'กรุณาเลือกตำแหน่งทางการบริหาร'}`,
                ]" -->
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                multiple
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionExecutiveSideId"
                :label="`${'ด้านทางการบริหาร'}`"
                @update:modelValue="clickEditRow"
                option-label="name"
                :options="positionExecutiveSideOptions"
                option-value="id"
                use-input
                use-chips
                input-debounce="0"
                @filter="positionExecutiveSideFilterFn"
                color="primary"
              />
              <!-- :rules="[(val) => !!val || `${'กรุณาเลือกด้านทางการบริหาร'}`]" -->
            </div>
            <div class="col-xs-8 col-sm-8 col-md-8">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                multiple
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionLevelId"
                :rules="[(val:any) => !!val || `${'กรุณาเลือกระดับ'}`,(val:any) => val.length > 0 || `${'กรุณาเลือกระดับ'}`]"
                :label="`${'ระดับ'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="positionLevelOptions"
                option-value="id"
                use-input
                use-chips
                input-debounce="0"
                @filter="positionLevelFilterFn"
                color="primary"
              />
            </div>
            <div class="col-xs-4 col-sm-4 col-md-4">
              <selector
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionStatusId"
                :label="`${'สถานภาพของตำแหน่ง'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="positionStatusOptions"
                option-value="id"
                use-input
                hide-selected
                fill-input
                input-debounce="0"
                @filter="positionStatusFilterFn"
                :rules="[(val:any) => !!val || `${'กรุณาเลือกสถานภาพของตำแหน่ง'}`]"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="qualification"
                :label="`${'คุณวุฒิ'}`"
                @update:modelValue="clickEditRow"
                type="textarea"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionCondition"
                :label="`${'เงื่อนไขตำแหน่ง'}`"
                @update:modelValue="clickEditRow"
                type="textarea"
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                :class="getClass(edit)"
                hide-bottom-space
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="positionMasterUserNote"
                :label="`${'หมายเหตุ'}`"
                @update:modelValue="clickEditRow"
                type="textarea"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6 text-grey-9">
              <q-checkbox v-model="isDirector" label="หัวหน้า" />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <DialogFooter
          :save="clickSave"
          :validate="validateData"
          v-model:editvisible="edit"
          v-model:modalEdit="modalEdit"
        />
      </q-form>
    </q-card>
  </q-dialog>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    :boss="true"
    v-model:modal="modalHistory"
    v-model:inputfilter="filterHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td auto-width>
          <q-icon
            class="q-mr-sm"
            size="15px"
            color="primary"
            name="mdi-bookmark"
            v-if="props.row.isDirector"
          ></q-icon>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name == 'isActive'" class="">
            <q-icon
              v-if="col.value == false"
              name="mdi-close"
              color="red"
              class="text-h5"
            />
            <q-icon v-else name="mdi-check" color="positive" class="text-h5" />
          </div>
          <div v-else-if="col.name == 'lastUpdatedAt'" class="">
            {{ date2Thai(col.value) }}
          </div>
          <div v-else class="">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useCounterMixin } from "@/stores/mixin";
import { useOrganizationalDataStore } from "@/modules/02_organizational/store";
import Table from "@/components/TableView.vue";
import DialogHeader from "@/modules/02_organizational/components/DialogHeader.vue";
import DialogFooter from "@/modules/02_organizational/components/DialogFooter.vue";
import { useQuasar, QForm } from "quasar";
import type {
  RequestItemsObject,
  RequestItemsPublishHistoryObject,
  Columns,
} from "@/modules/02_organizational/interface/request/Mapping";
import type { ResponseObject } from "@/modules/02_organizational/interface/response/Mapping";
import type { DataOption } from "@/modules/02_organizational/interface/index/Main";
import HistoryTable from "@/components/TableHistory.vue";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";

const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();
const {
  success,
  modalConfirm,
  modalError,
  modalDelete,
  showLoader,
  hideLoader,
} = mixin;
const { date2Thai } = mixin;
const store = useOrganizationalDataStore();
const { organizationalData, changeOrganizationalColumns } = store;
const version = ref<string>("published");
const id = ref<string>();
const positionType = ref<string>();
const positionLine = ref<string>();
const positionPath = ref<string>();
const positionPathSide = ref<string>();
const positionExecutive = ref<string>();
const positionExecutiveSide = ref<string>();
const positionStatus = ref<string>();
const positionLevel = ref<string>();
const positionTypeId = ref<string>();
const positionMasterId = ref<string>("");
const positionLineId = ref<string>();
const positionPathId = ref<string>("");
const positionPathSideId = ref<any>();
const positionExecutiveId = ref<string>();
const positionExecutiveSideId = ref<any>();
const positionStatusId = ref<string>();
const positionLevelId = ref<string[]>([]);
const positionCondition = ref<string>();
const qualification = ref<string>();
const positionMasterUserNote = ref<string>();
const positionTypeOptions = ref<DataOption[]>([]);
const positionLineOptions = ref<DataOption[]>([]);
const positionPathOptions = ref<DataOption[]>([]);
const positionPathSideOptions = ref<DataOption[]>([]);
const positionExecutiveOptions = ref<DataOption[]>([]);
const positionExecutiveSideOptions = ref<DataOption[]>([]);
const positionStatusOptions = ref<DataOption[]>([]);
const positionLevelOptions = ref<DataOption[]>([]);
const positionTypeOptionsRaw = ref<DataOption[]>([]);
const positionLineOptionsRaw = ref<DataOption[]>([]);
const positionPathOptionsRaw = ref<DataOption[]>([]);
const positionPathSideOptionsRaw = ref<DataOption[]>([]);
const positionExecutiveOptionsRaw = ref<DataOption[]>([]);
const positionExecutiveSideOptionsRaw = ref<DataOption[]>([]);
const positionStatusOptionsRaw = ref<DataOption[]>([]);
const positionLevelOptionsRaw = ref<DataOption[]>([]);
const isDirector = ref<boolean>();
const rowsHistory = ref<RequestItemsObject[]>([]); //select data history
const rawHistory = ref<RequestItemsObject[]>([]); //raw data history
const tittleHistory = ref<string>("ประวัติแก้ไขโครงสร้างและกรอบอัตรากำลัง"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล

const isActive = ref<boolean>();
const myForm = ref<QForm | null>(null); //form data input
const edit = ref<boolean>(false); //เช็คการกดปุ่มแก้ไขใน dialog
const modal = ref<boolean>(false); //modal add detail
const modalEdit = ref<boolean>(false); //modal ที่แสดงใช้สำหรับแก้ไขหรือไม่
const editRow = ref<boolean>(false); //เช็คมีการแก้ไขข้อมูล
// const modalError = ref<boolean>(false); // modal สำหรับแจ้งเตือนerror
// const modalErrorTittle = ref<string>(""); // tittle modal error
// const modalErrorDetail = ref<string>(""); // detail modal error
const statusCode = ref<number>();
const checkValidate = ref<boolean>(false); //validate data ผ่านหรือไม่
const editvisible = ref<boolean>(false); //ปุ่ม edit บน table
// const closeModalError = () => {
//   modalError.value = false;
//   if (statusCode.value != 404) {
//     // fetchData();
//   }
// };

const rows = ref<RequestItemsObject[]>([]);
const filter = ref<string>(""); //search data table

const visibleColumns = ref<String[]>([]);
organizationalData.mappingPosition.columns.length == 0
  ? (visibleColumns.value = [
      "positionType",
      "positionLine",
      "positionPath",
      "positionPathSide",
      "positionExecutive",
      "positionExecutiveSide",
      "positionLevel",
      "positionStatus",
      "qualification",
      "positionCondition",
      "isDirector",
      "isActive",
    ])
  : (visibleColumns.value = organizationalData.mappingPosition.columns);

const columns = ref<QTableProps["columns"]>([
  {
    name: "positionType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "positionType",
    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: "positionPath",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionPath",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionPathSide",
    align: "left",
    label: "ด้าน/สาขา",
    sortable: true,
    field: "positionPathSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "positionExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutiveSide",
    align: "left",
    label: "ด้านทางการบริหาร",
    sortable: true,
    field: "positionExecutiveSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  //   {
  //     name: "isDirector",
  //     align: "left",
  //     label: "",
  //     sortable: true,
  //     field: "isDirector",
  //     headerStyle: "font-size: 14px",
  //     style: "font-size: 14px",
  //  sort: (a: string, b: string) =>
  //       a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  //   },
  {
    name: "positionStatus",
    align: "left",
    label: "สถานภาพของตำแหน่ง",
    sortable: true,
    field: "positionStatus",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "qualification",
    align: "left",
    label: "คุณวุฒิ",
    sortable: true,
    field: "qualification",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionCondition",
    align: "left",
    label: "เงื่อนไขตำแหน่ง",
    sortable: true,
    field: "positionCondition",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "isActive",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "positionType",
    align: "left",
    label: "ตำแหน่งประเภท",
    sortable: true,
    field: "positionType",
    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: "positionPath",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "positionPath",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionPathSide",
    align: "left",
    label: "ด้าน/สาขา",
    sortable: true,
    field: "positionPathSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutive",
    align: "left",
    label: "ตำแหน่งทางการบริหาร",
    sortable: true,
    field: "positionExecutive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionExecutiveSide",
    align: "left",
    label: "ด้านทางการบริหาร",
    sortable: true,
    field: "positionExecutiveSide",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ระดับ",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  //   {
  //     name: "isDirector",
  //     align: "left",
  //     label: "หัวหน้า",
  //     sortable: true,
  //     field: "isDirector",
  //     headerStyle: "font-size: 14px",
  //     style: "font-size: 14px",
  //  sort: (a: string, b: string) =>
  //       a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  //   },
  {
    name: "positionStatus",
    align: "left",
    label: "สถานภาพของตำแหน่ง",
    sortable: true,
    field: "positionStatus",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "qualification",
    align: "left",
    label: "คุณวุฒิ",
    sortable: true,
    field: "qualification",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "positionCondition",
    align: "left",
    label: "เงื่อนไขตำแหน่ง",
    sortable: true,
    field: "positionCondition",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "isActive",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "isActive",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "center",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const visibleColumnsHistory = ref<String[]>([
  "positionType",
  "positionLine",
  "positionPath",
  "positionPathSide",
  "positionExecutive",
  "positionExecutiveSide",
  "positionLevel",
  "positionStatus",
  "qualification",
  "positionCondition",
  "isDirector",
  "isActive",
  "lastUpdatedAt",
  "lastUpdateFullName",
]);

watch(visibleColumns, async (count: String[], prevCount: String[]) => {
  await changeOrganizationalColumns("mappingPosition", count);
});

onMounted(async () => {
  hideLoader();
  await fetchPosition();
  await fetchData();
  await fetchHistory();
});

/**
 * ฟังก์ชัน get data ล่าสุด
 */
const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.getPostionMasterDraft(true))
    .then((res) => {
      let data = res.data.result;
      rows.value = [];
      version.value = "published";
      data.map((e: RequestItemsObject) => {
        rows.value.push({
          id: e.id,
          isActive: e.isActive,
          positionType: e.positionType,
          positionLine: e.positionLine,
          positionPath: e.positionPath,
          positionPathSide: e.positionPathSide,
          positionExecutive: e.positionExecutive,
          positionExecutiveSide: e.positionExecutiveSide,
          positionLevel: e.positionLevel.toString(),
          positionStatus: e.positionStatus,
          positionTypeId: e.positionTypeId,
          positionMasterId: e.positionMasterId,
          positionLineId: e.positionLineId,
          positionPathId: e.positionPathId,
          positionPathSideId: e.positionPathSideId,
          positionExecutiveId: e.positionExecutiveId,
          positionExecutiveSideId: e.positionExecutiveSideId,
          positionLevelId: e.positionLevelId,
          positionStatusId: e.positionStatusId,
          qualification: e.qualification,
          positionCondition: e.positionCondition,
          positionMasterUserNote: e.positionMasterUserNote,
          isDirector: e.isDirector,
        });
        if (e.isPublished == false) {
          version.value = "draft";
        }
      });
    })
    .catch((e) => {
      rows.value.splice(0);
      modalError($q, "ไม่สามารถดึงข้อมูลตำแหน่งได้", e.response.data.message);
    })
    .finally(() => {
      //   updateData.value = false;
      hideLoader();
    });
};

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลทั้งหมด
 */
const fetchHistory = async () => {
  //   showLoader();
  //   await http
  //     .get(config.API.listxxxxxxxxPublishedHistory)
  //     .then((res) => {
  //       const data = res.data.result;
  //       rawHistory.value = [];
  //       if (data.length > 0) {
  //         data.map((e: RequestItemsPublishHistoryObject) => {
  //           e.items.map((i: RequestItemsObject) => {
  //             rawHistory.value.push({
  //               createdAt: i.createdAt,
  //               createdFullName: i.createdFullName,
  //               createdUserId: i.createdUserId,
  //               id: i.id,
  //               isActive: i.isActive,
  //               lastUpdateFullName: i.lastUpdateFullName,
  //               lastUpdateUserId: i.lastUpdateUserId,
  //               lastUpdatedAt: i.lastUpdatedAt,
  //               name: i.name,
  //               shortName: i.shortName,
  //             });
  //           });
  //         });
  //       }
  //     })
  //     .catch((e) => {
  //       modalError.value = true;
  //       modalErrorTittle.value = "ไม่พบประวัติการเผยแพร่";
  //       modalErrorDetail.value = e.response.data.message;
  //       statusCode.value = e.response.data.status;
  //     })
  //     .finally(async () => {
  //       hideLoader();
  //     });
};

/**
 * get รายการ ตำแหน่ง
 */
const fetchPosition = async () => {
  showLoader();
  await http
    .get(config.API.position)
    .then((res) => {
      const data = res.data.result;
      console.log(data.positionPaths);

      let optionpositionpaths: DataOption[] = [];
      data.positionPaths.map((r: any) => {
        optionpositionpaths.push({
          id: r.id.toString(),
          name: r.name.toString(),
          note: r.note.toString(),
        });
      });
      positionPathOptions.value = optionpositionpaths;
      positionPathOptionsRaw.value = optionpositionpaths;

      let optionPositionPathSides: DataOption[] = [];
      data.positionPathSides.map((r: any) => {
        optionPositionPathSides.push({
          id: r.id.toString(),
          name: r.name.toString(),
          note: r.note.toString(),
        });
      });
      positionPathSideOptions.value = optionPositionPathSides;
      positionPathSideOptionsRaw.value = optionPositionPathSides;

      let optionPositionTypes: DataOption[] = [];
      data.positionTypes.map((r: any) => {
        optionPositionTypes.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      positionTypeOptions.value = optionPositionTypes;
      positionTypeOptionsRaw.value = optionPositionTypes;

      let optionPositionLines: DataOption[] = [];
      data.positionLines.map((r: any) => {
        optionPositionLines.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      positionLineOptions.value = optionPositionLines;
      positionLineOptionsRaw.value = optionPositionLines;

      let optionPositionExecutives: DataOption[] = [];
      data.positionExecutives.map((r: any) => {
        optionPositionExecutives.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      positionExecutiveOptions.value = optionPositionExecutives;
      positionExecutiveOptionsRaw.value = optionPositionExecutives;

      let optionPositionExecutiveSides: DataOption[] = [];
      data.positionExecutiveSides.map((r: any) => {
        optionPositionExecutiveSides.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      positionExecutiveSideOptions.value = optionPositionExecutiveSides;
      positionExecutiveSideOptionsRaw.value = optionPositionExecutiveSides;

      let optionPositionLevels: DataOption[] = [];
      data.positionLevels.map((r: any) => {
        optionPositionLevels.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      positionLevelOptions.value = optionPositionLevels;
      positionLevelOptionsRaw.value = optionPositionLevels;

      let optionPositionStatuss: DataOption[] = [];
      data.positionStatuss.map((r: any) => {
        optionPositionStatuss.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      positionStatusOptions.value = optionPositionStatuss;
      positionStatusOptionsRaw.value = optionPositionStatuss;
    })
    .catch((e: any) => {})
    .finally(() => {
      hideLoader();
    });
};

/**
 * filter select ตำแหน่งประเภท
 * @param val text filter
 * @param update
 * @param abort
 */
const positionTypeFilterFn = async (val: string, update: any, abort: any) => {
  update(() => {
    positionTypeOptions.value = positionTypeOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * filter select สายงาน
 * @param val text filter
 * @param update
 * @param abort
 */
const positionLineFilterFn = async (val: string, update: any, abort: any) => {
  update(() => {
    positionLineOptions.value = positionLineOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * filter select ตำแหน่ง
 * @param val text filter
 * @param update
 * @param abort
 */
const positionPathFilterFn = async (val: string, update: any, abort: any) => {
  update(() => {
    positionPathOptions.value = positionPathOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * filter select ด้าน/สาขา
 * @param val text filter
 * @param update
 * @param abort
 */
const positionPathSideFilterFn = async (
  val: string,
  update: any,
  abort: any
) => {
  update(() => {
    positionPathSideOptions.value = positionPathSideOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * filter select ตำแหน่งทางการบริหาร
 * @param val text filter
 * @param update
 * @param abort
 */
const positionExecutiveFilterFn = async (
  val: string,
  update: any,
  abort: any
) => {
  update(() => {
    positionExecutiveOptions.value = positionExecutiveOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * filter select ด้านทางการบริหาร
 * @param val text filter
 * @param update
 * @param abort
 */
const positionExecutiveSideFilterFn = async (
  val: string,
  update: any,
  abort: any
) => {
  update(() => {
    positionExecutiveSideOptions.value =
      positionExecutiveSideOptionsRaw.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
      );
  });
};

/**
 * filter select ระดับ
 * @param val text filter
 * @param update
 * @param abort
 */
const positionLevelFilterFn = async (val: string, update: any, abort: any) => {
  update(() => {
    positionLevelOptions.value = positionLevelOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * filter select สถานภาพของตำแหน่ง
 * @param val text filter
 * @param update
 * @param abort
 */
const positionStatusFilterFn = async (val: string, update: any, abort: any) => {
  update(() => {
    positionStatusOptions.value = positionStatusOptionsRaw.value.filter(
      (v: any) => v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
    );
  });
};

/**
 * กดบันทึกใน dialog
 */
const clickSave = async () => {
  myForm.value!.validate().then(async (result: boolean) => {
    if (result) {
      if (modalEdit.value) {
        await editData();
      } else {
        await saveData();
      }
    }
  });
};

/**
 * บันทึกเพิ่มข้อมูล
 */
const saveData = async () => {
  modal.value = false;
  showLoader();
  await http
    .post(config.API.getPositionMaster, {
      positionTypeId: positionTypeId.value,
      positionLineId: positionLineId.value,
      positionPathId: positionPathId.value,
      positionPathSideId: positionPathSideId.value,
      positionExecutiveId: positionExecutiveId.value,
      positionExecutiveSideId: positionExecutiveSideId.value,
      positionLevelId: positionLevelId.value,
      isDirector: isDirector.value,
      positionStatusId: positionStatusId.value,
      qualification: qualification.value,
      positionCondition: positionCondition.value,
      positionMasterUserNote: positionMasterUserNote.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลร่างสำเร็จ");
    })
    .catch((e) => {
      statusCode.value = e.response.data.status;
    })
    .finally(async () => {
      modal.value = false;
      await fetchData();
    });
};

/**
 * บันทึกแก้ไขข้อมูล
 */
const editData = async () => {
  modal.value = false;
  showLoader();
  await http
    .put(config.API.getPositionMasterId(positionMasterId.value), {
      positionMasterId: positionMasterId.value,
      positionTypeId: positionTypeId.value,
      positionLineId: positionLineId.value,
      positionPathId: positionPathId.value,
      positionPathSideId: positionPathSideId.value,
      positionExecutiveId: positionExecutiveId.value,
      positionExecutiveSideId: positionExecutiveSideId.value,
      positionLevelId: positionLevelId.value,
      isDirector: isDirector.value,
      positionStatusId: positionStatusId.value,
      qualification: qualification.value,
      positionCondition: positionCondition.value,
      positionMasterUserNote: positionMasterUserNote.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลร่างสำเร็จ");
    })
    .catch((e) => {
      statusCode.value = e.response.data.status;
    })
    .finally(async () => {
      edit.value = false;
      await fetchData();
    });
};

/**
 * ฟังก์ชัน clear data แบบร่าง
 * เมื่อเรียก api เสร็จแล้วจะ get data มาใหม่
 */
const clearPublishedData = async () => {
  showLoader();
  await http
    .put(config.API.getPositionMasterSync)
    .then((res) => {
      success($q, "ลบข้อมูลร่างสำเร็จ");
    })
    .catch((e) => {
      // modalError.value = true;
      // modalErrorTittle.value = "ไม่สามารถลบข้อมูลที่เผยแพร่ได้";
      // modalErrorDetail.value = e.response.data.message;
      statusCode.value = e.response.data.status;
    })
    .finally(async () => {
      hideLoader();
      await fetchHistory();
      await fetchData();
    });
};

/**
 * ฟังก์ชันเผยแพร่แบบร่าง
 * เมื่อเรียก api เสร็จแล้วจะ get data มาใหม่
 */
const publishedData = async () => {
  //   editvisible.value = false;
  showLoader();
  await http
    .put(config.API.getPositionMasterPublish)
    .then((res) => {
      success($q, "เผยแพร่ข้อมูลสำเร็จ");
    })
    .catch((e) => {
      statusCode.value = e.response.data.status;
    })
    .finally(async () => {
      hideLoader();
      await fetchData();
    });
};

/**
 * กดปิด dialog
 */
const clickClose = async () => {
  if (editRow.value == true) {
    $q.dialog({
      title: `ข้อมูลมีการแก้ไข`,
      message: `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`,
      cancel: "ยกเลิก",
      ok: "ยืนยัน",
      persistent: true,
    }).onOk(async () => {
      modal.value = false;
    });
  } else {
    modal.value = false;
  }
};

/**
 * กดเลือกข้อมูลที่จะแก้ไข
 * @param props ค่า props ใน row ที่เลือก
 */
const selectData = (props: RequestItemsObject) => {
  if (editvisible.value == true) {
    editRow.value = false;
    modalEdit.value = true;
    modal.value = true;
    edit.value = true;
    positionType.value = props.positionType;
    positionLine.value = props.positionLine;
    positionPath.value = props.positionPath;
    positionPathSide.value = props.positionPathSide;
    positionExecutive.value = props.positionExecutive;
    positionExecutiveSide.value = props.positionExecutiveSide;
    positionLevel.value = props.positionLevel;
    positionStatus.value = props.positionStatus;
    positionMasterId.value = props.id;
    positionTypeId.value = props.positionTypeId;
    positionLineId.value = props.positionLineId;
    positionPathId.value = props.positionPathId;
    positionPathSideId.value = props.positionPathSideId;
    positionExecutiveId.value = props.positionExecutiveId;
    positionExecutiveSideId.value = props.positionExecutiveSideId;
    positionLevelId.value = props.positionLevelId;
    positionStatusId.value = props.positionStatusId;
    qualification.value = props.qualification;
    positionCondition.value = props.positionCondition;
    positionMasterUserNote.value = props.positionMasterUserNote;
    isDirector.value = props.isDirector;
    isActive.value = props.isActive;
    id.value = props.id;
  }
};

/**
 * กดปุ่มเพิ่มบน table
 */
const clickAdd = () => {
  editRow.value = false;
  modalEdit.value = false;
  modal.value = true;
  edit.value = true;
  positionType.value = "";
  positionLine.value = "";
  positionPath.value = "";
  positionPathSide.value = "";
  positionExecutive.value = "";
  positionExecutiveSide.value = "";
  positionLevel.value = "";
  positionStatus.value = "";
  positionTypeId.value = "";
  positionLineId.value = "";
  positionPathId.value = "";
  positionPathSideId.value = [];
  positionExecutiveId.value = "";
  positionExecutiveSideId.value = [];
  positionLevelId.value = [];
  positionStatusId.value = positionStatusOptionsRaw.value[0].id;
  qualification.value = "";
  positionCondition.value = "";
  positionMasterUserNote.value = "";
  isDirector.value = false;
  isActive.value = false;
};

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 * @param row ข้อมูล row ที่ดูประวัติการแก้ไข
 */
const clickHistory = async (row: RequestItemsObject) => {
  showLoader();
  await http
    .get(config.API.getPositionMasterHistoryId(row.id))
    .then((res) => {
      let data = res.data.result;
      rowsHistory.value = [];
      data.map((e: RequestItemsObject, index: number) => {
        console.log(index);
        if (index != 0) {
          rowsHistory.value.push({
            id: e.id,
            isActive: e.isActive,
            positionType: e.positionType,
            positionLine: e.positionLine,
            positionPath: e.positionPath,
            positionPathSide: e.positionPathSide,
            positionExecutive: e.positionExecutive,
            positionExecutiveSide: e.positionExecutiveSide,
            positionLevel: e.positionLevel,
            positionStatus: e.positionStatus,
            positionTypeId: e.positionTypeId,
            positionMasterId: e.positionMasterId,
            positionLineId: e.positionLineId,
            positionPathId: e.positionPathId,
            positionPathSideId: e.positionPathSideId,
            positionExecutiveId: e.positionExecutiveId,
            positionExecutiveSideId: e.positionExecutiveSideId,
            positionLevelId: e.positionLevelId,
            positionStatusId: e.positionStatusId,
            qualification: e.qualification,
            positionCondition: e.positionCondition,
            positionMasterUserNote: e.positionMasterUserNote,
            isDirector: e.isDirector,
            lastUpdatedAt: e.lastUpdatedAt,
            lastUpdateFullName: e.lastUpdateFullName,
          });
        }
      });
    })
    .catch((e) => {
      statusCode.value = e.response.data.status;
    })
    .finally(async () => {
      modalHistory.value = true;
      hideLoader();
    });
};

/**
 * ฟังก์ชันปุ่มลบแบบร่าง
 */
const clickDelete = async () => {
  await clearPublishedData();
};

/**
 * ฟังก์ชันปุ่มยกเลิกการแก้ไขข้อมูล
 */
const clickCancel = async () => {
  editvisible.value = false;
  await fetchData();
};

/**
 * ฟังก์ชันปุ่มเผยแพร่ข้อมูล
 * เช็คข้อมูลก่อนว่าใน array กรอกข้อมูลครบไหมถ้าครบก็ให้เผยแพร่ได้
 * ถ้าค่าใน array ไม่มีข้อมูลใน row ก้จะให้บันทึกได้
 */
const clickPublish = async () => {
  await publishedData();
};

/**
 * กด Active data
 */
const clickIsActive = async (val: string, status: boolean) => {
  $q.dialog({
    title: `${status == true ? "เปิด" : "ปิด"}ใช้งานข้อมูล`,
    message: `ยืนยันการ${
      status == true ? "เปิด" : "ปิด"
    }ใช้งานข้อมูลนี้ใช่หรือไม่?`,
    cancel: "ยกเลิก",
    ok: "ยืนยัน",
    persistent: true,
  })
    .onOk(async () => {
      // edit.value = false;
      showLoader();
      await http
        .delete(config.API.getPositionMasterId(val) + `?Id=${val}`)
        .then((res) => {
          success($q, "เปลี่ยนสถานะสำเร็จ");
        })
        .catch((e) => {
          statusCode.value = e.response.data.status;
        })
        .finally(async () => {
          modal.value = false;
          await fetchData();
        });
    })
    .onCancel(async () => {
      await fetchData();
    });
};

/**
 * เช็คว่ามีการแก้ไขข้อมูล
 */
const clickEditRow = () => {
  editRow.value = true;
};

/**
 * เลือกตำแหน่ง
 */
const clickEditRowPositionPath = (id: string) => {
  let _note = positionPathOptionsRaw.value.filter(
    (v: DataOption) => v.id == id
  );
  if (_note.length > 0) {
    positionMasterUserNote.value = _note == null ? "" : _note[0].note;
  }
  clickEditRow();
};

/**
 * validate input ใน dialog
 */
const validateData = async () => {
  checkValidate.value = true;
  await myForm.value!.validate().then((result: boolean) => {
    if (result == false) {
      checkValidate.value = false;
    }
  });
};

/**
 * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
 * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
