<!-- card เครื่องราชอิสริยาภรณ์ -->
<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md">
    <q-form ref="myForm">
      <ProfileTable
        :rows="rows"
        :columns="columns"
        :filter="filter"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        :add="clickAdd"
        name="เครื่องราชอิสริยาภรณ์"
        icon="mdi-medal"
        :statusEdit="statusEdit"
      >
        <template #columns="props">
          <q-tr :props="props">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="selectData(props)"
              class="cursor-pointer"
            >
              <div
                v-if="
                  col.name == 'receiveDate' ||
                  col.name == 'dateAnnounce' ||
                  col.name == 'refCommandDate'
                "
                class="table_ellipsis"
              >
                {{ col.value == null ? null : date2Thai(col.value) }}
              </div>
              <div v-else-if="col.name == 'year'" class="table_ellipsis">
                {{ col.value + 543 }}
              </div>
              <div v-else class="table_ellipsis">
                {{ 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>
      </ProfileTable>
    </q-form>
  </q-card>
  <!-- popup Edit window-->
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 600px">
      <q-form ref="myForm">
        <DialogHeader tittle="เครื่องราชอิสริยาภรณ์" :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">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit"
                v-model="year"
                :locale="'th'"
                autoApply
                year-picker
                :enableTimePicker="false"
                @update:modelValue="clickEditRow"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    :class="getClass(edit)"
                    :outlined="edit"
                    dense
                    :borderless="!edit"
                    :model-value="year + 543"
                    :rules="[
                      (val:string) =>
                        !!val ||
                        `${'กรุณาเลือกปีที่ยื่นขอพระราชทานเครื่องราชฯ'}`,
                    ]"
                    hide-bottom-space
                    :label="`${'ปีที่ยื่นขอพระราชทานเครื่องราชฯ'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        :style="
                          edit
                            ? 'color: var(--q-primary)'
                            : 'color: var(--q-grey)'
                        "
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit"
                v-model="receiveDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                @update:modelValue="clickEditRow"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    :class="getClass(edit)"
                    :outlined="edit"
                    dense
                    :borderless="!edit"
                    :model-value="date2Thai(receiveDate)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่ได้รับ'}`]"
                    hide-bottom-space
                    :label="`${'วันที่ได้รับ'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        :style="
                          edit
                            ? 'color: var(--q-primary)'
                            : 'color: var(--q-grey)'
                        "
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="insigniaId"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกชื่อเครื่องราชฯ'}`]"
                hide-bottom-space
                :label="`${'ชื่อเครื่องราชฯ'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="Ops.insigniaOptions"
                option-value="id"
                use-input
                input-debounce="0"
                @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'insigniaOptions'
                      ) "
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(false)"
                :outlined="false"
                dense
                lazy-rules
                :readonly="true"
                :borderless="true"
                v-model="insigniaType"
                :label="`${'ลำดับชั้น'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="no"
                :rules="[(val:string) => !!val || `${'กรุณากรอกลำดับที่'}`]"
                :label="`${'ลำดับที่'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="issue"
                :rules="[(val:string) => !!val || `${'กรุณากรอกราชกิจจาฯ ฉบับที่'}`]"
                :label="`${'ราชกิจจาฯ ฉบับที่'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="volumeNo"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเล่มที่'}`]"
                :label="`${'เล่มที่'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="volume"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเล่ม'}`]"
                :label="`${'เล่ม'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="section"
                :rules="[(val:string) => !!val || `${'กรุณากรอกตอน'}`]"
                :label="`${'ตอน'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="page"
                :rules="[(val:string) => !!val || `${'กรุณากรอกหน้า'}`]"
                :label="`${'หน้า'}`"
                @update:modelValue="clickEditRow"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit"
                v-model="dateAnnounce"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                @update:modelValue="clickEditRow"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    :class="getClass(edit)"
                    :outlined="edit"
                    dense
                    :borderless="!edit"
                    :model-value="date2Thai(dateAnnounce)"
                    :rules="[
                      (val:string) =>
                        !!val || `${'กรุณาเลือกวันที่ประกาศในราชกิจจาฯ'}`,
                    ]"
                    hide-bottom-space
                    :label="`${'วันที่ประกาศในราชกิจจาฯ'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        :style="
                          edit
                            ? 'color: var(--q-primary)'
                            : 'color: var(--q-grey)'
                        "
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="refCommandNo"
                hide-bottom-space
                :label="`${'เลขที่คำสั่ง'}`"
                @update:modelValue="clickEditRow"
              >
                <template v-slot:append>
                  <q-icon
                    name="mdi-file"
                    class="cursor-pointer"
                    @click="resetFilter"
                  />
                </template>
              </q-input>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit"
                v-model="refCommandDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                @update:modelValue="clickEditRow"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    :class="getClass(edit)"
                    :outlined="edit"
                    dense
                    :borderless="!edit"
                    :model-value="
                      refCommandDate == null ? null : date2Thai(refCommandDate)
                    "
                    hide-bottom-space
                    :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        :style="
                          edit
                            ? 'color: var(--q-primary)'
                            : 'color: var(--q-grey)'
                        "
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <DialogFooter
          :cancel="clickCancel"
          :edit="clickEdit"
          :save="clickSave"
          :validate="validateData"
          :clickNext="clickNext"
          :clickPrevious="clickPrevious"
          :clickDelete="clickDelete"
          v-model:editvisible="edit"
          v-model:next="next"
          v-model:previous="previous"
          v-model:modalEdit="modalEdit"
        />
      </q-form>
    </q-card>
  </q-dialog>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    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 v-for="col in props.cols" :key="col.name" :props="props">
          <div
            v-if="
              col.name == 'receiveDate' ||
              col.name == 'dateAnnounce' ||
              col.name == 'createdAt' ||
              col.name == 'refCommandDate'
            "
            class="table_ellipsis"
          >
            {{ col.value == null ? null : date2Thai(col.value) }}
          </div>
          <div v-else-if="col.name == 'year'" class="table_ellipsis">
            {{ col.value + 543 }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useComponentProfileDataStore } from "@/components/information/store/store";
import { useCounterMixin } from "@/stores/mixin";

import ProfileTable from "@/components/information/Table.vue";
import DialogHeader from "@/components/information/DialogHeader.vue";
import DialogFooter from "@/components/information/DialogFooter.vue";
import { useQuasar } from "quasar";
import type {
  RequestItemsObject,
  Columns,
  DataProps,
} from "@/components/information/interface/request/Insignia";
import type { ResponseObject } from "@/components/information/interface/response/Insignia";
import type {
  DataOption,
  DataOptionInsignia,
  InsigniaOps,
} from "@/components/information/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 props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
});

const $q = useQuasar();
const store = useComponentProfileDataStore();
const { profileData, changeProfileColumns } = store;
const mixin = useCounterMixin();
const { date2Thai, success, dateToISO, messageError, showLoader, hideLoader } =
  mixin;
const route = useRoute();
const id = ref<string>("");
const insigniaId = ref<string>("");
const Ops = ref<InsigniaOps>({
  insigniaOptions: [],
});
const OpsFilter = ref<InsigniaOps>({
  insigniaOptions: [],
});
const insigniaType = ref<string>();
const year = ref<number>(0);
const no = ref<string>();
const issue = ref<string>();
const volumeNo = ref<string>();
const volume = ref<string>();
const section = ref<string>();
const page = ref<string>();
const receiveDate = ref<Date>(new Date());
const dateAnnounce = ref<Date>(new Date());
const refCommandNo = ref<string>();
const refCommandDate = ref<Date | null>(new Date());
const myForm = ref<any>(); //form data input
const edit = ref<boolean>(false); //เช็คการกดปุ่มแก้ไขใน dialog
const modal = ref<boolean>(false); //modal add detail
const modalEdit = ref<boolean>(false); //modal ที่แสดงใช้สำหรับแก้ไขหรือไม่
const rawItem = ref<RequestItemsObject>(); //ข้อมูลเดิมที่เลือกใน row นั้น
const rowIndex = ref<number>(0); //indexข้อมูลเดิมที่เลือกใน row นั้น
const previous = ref<boolean>(); //แสดงปุ่มดูข้อมูลก่อนหน้า
const next = ref<boolean>(); //แสดงปุ่มดูข้อมูลต่อไป
const editRow = ref<boolean>(false); //เช็คมีการแก้ไขข้อมูล
const rowsHistory = ref<RequestItemsObject[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติแก้ไขเครื่องราชอิสริยาภรณ์"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const checkValidate = ref<boolean>(false); //validate data ผ่านหรือไม่
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const rows = ref<RequestItemsObject[]>([]);
const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([]);
profileData.insignia.columns.length == 0
  ? (visibleColumns.value = [
      "insignia",
      "insigniaType",
      "year",
      "no",
      "issue",
      "volumeNo",
      "volume",
      "section",
      "page",
      "receiveDate",
      "dateAnnounce",
      "refCommandNo",
      "refCommandDate",
    ])
  : (visibleColumns.value = profileData.insignia.columns);
const columns = ref<QTableProps["columns"]>([
  {
    name: "year",
    align: "left",
    label: "ปีที่ยื่นขอ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "receiveDate",
    align: "left",
    label: "ลงวันที่",
    sortable: true,
    field: "receiveDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "insignia",
    align: "left",
    label: "ชื่อเครื่องราชฯ",
    sortable: true,
    field: "insignia",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ลำดับชั้น",
    sortable: true,
    field: "insigniaType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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: "issue",
    align: "left",
    label: "ราชกิจจาฯ ฉบับที่",
    sortable: true,
    field: "issue",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volumeNo",
    align: "left",
    label: "เล่มที่",
    sortable: true,
    field: "volumeNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volume",
    align: "left",
    label: "เล่ม",
    sortable: true,
    field: "volume",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "section",
    align: "left",
    label: "ตอน",
    sortable: true,
    field: "section",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "page",
    align: "left",
    label: "หน้า",
    sortable: true,
    field: "page",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateAnnounce",
    align: "left",
    label: "วันที่ประกาศในราชกิจจาฯ",
    sortable: true,
    field: "dateAnnounce",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    field: "refCommandDate",
    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: "year",
    align: "left",
    label: "ปีที่ยื่นขอ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "receiveDate",
    align: "left",
    label: "ลงวันที่",
    sortable: true,
    field: "receiveDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "insignia",
    align: "left",
    label: "ชื่อเครื่องราชฯ",
    sortable: true,
    field: "insignia",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ลำดับชั้น",
    sortable: true,
    field: "insigniaType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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: "issue",
    align: "left",
    label: "ราชกิจจาฯ ฉบับที่",
    sortable: true,
    field: "issue",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volumeNo",
    align: "left",
    label: "เล่มที่",
    sortable: true,
    field: "volumeNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volume",
    align: "left",
    label: "เล่ม",
    sortable: true,
    field: "volume",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "section",
    align: "left",
    label: "ตอน",
    sortable: true,
    field: "section",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "page",
    align: "left",
    label: "หน้า",
    sortable: true,
    field: "page",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateAnnounce",
    align: "left",
    label: "วันที่ประกาศในราชกิจจาฯ",
    sortable: true,
    field: "dateAnnounce",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    field: "refCommandDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "createdFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "insignia",
  "insigniaType",
  "year",
  "no",
  "issue",
  "volumeNo",
  "volume",
  "section",
  "page",
  "receiveDate",
  "dateAnnounce",
  "refCommandNo",
  "refCommandDate",
  "createdFullName",
  "createdAt",
]);

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

watch(insigniaId, (count: string, prevCount: string) => {
  const insigniaTypeFilter = Ops.value.insigniaOptions.filter(
    (r: DataOptionInsignia) => r.id == insigniaId.value
  );
  if (insigniaTypeFilter[0] != null) {
    insigniaType.value = insigniaTypeFilter[0].typeName;
  }
});

onMounted(async () => {
  await fetchInsignia();
  await fetchData();
});

const filterSelector = (val: any, update: Function, refData: string) => {
  switch (refData) {
    case "insigniaOptions":
      update(() => {
        Ops.value.insigniaOptions = OpsFilter.value.insigniaOptions.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
};

const fetchInsignia = async () => {
  showLoader();
  await http
    .get(config.API.insignia)
    .then((res) => {
      const data = res.data.result;
      let option: DataOptionInsignia[] = [];
      data.map((r: any) => {
        option.push({
          id: r.id.toString(),
          name: r.name.toString(),
          typeName:
            r.insigniaType == null ? null : r.insigniaType.name.toString(),
        });
      });
      Ops.value.insigniaOptions = option;
      OpsFilter.value.insigniaOptions = option;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const fetchData = async () => {
  if (profileId.value) {
    showLoader();
    await http
      .get(config.API.profileInsignId(profileId.value))
      .then((res) => {
        let data = res.data.result;
        rows.value = [];
        data.map((e: ResponseObject) => {
          rows.value.push({
            id: e.id,
            insignia: e.insignia,
            insigniaId: e.insigniaId,
            insigniaType: e.insigniaType,
            year: e.year,
            no: e.no,
            issue: e.issue,
            volumeNo: e.volumeNo,
            volume: e.volume,
            section: e.section,
            page: e.page,
            receiveDate: new Date(e.receiveDate),
            dateAnnounce: new Date(e.dateAnnounce),
            refCommandNo: e.refCommandNo,
            refCommandDate:
              e.refCommandDate == null ? null : new Date(e.refCommandDate),
            createdFullName: e.createdFullName,
            createdAt: new Date(e.createdAt),
          });
        });
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

/**
 * กดดูข้อมูลก่อนหน้า
 */
const clickPrevious = async () => {
  edit.value = false;
  rowIndex.value -= 1;
  await getData();
  await checkRowPage();
};

/**
 * กดดูข้อมูลต่อไป
 */
const clickNext = async () => {
  edit.value = false;
  rowIndex.value += 1;
  await getData();
  await checkRowPage();
};

/**
 * กดดูข้อมูลต่อไป
 */
const getData = () => {
  const row = rows.value[rowIndex.value];
  insigniaId.value = row.insigniaId;
  insigniaType.value = row.insigniaType;
  year.value = row.year;
  no.value = row.no;
  issue.value = row.issue;
  volumeNo.value = row.volumeNo;
  volume.value = row.volume;
  section.value = row.section;
  page.value = row.page;
  receiveDate.value = row.receiveDate;
  dateAnnounce.value = row.dateAnnounce;
  refCommandNo.value = row.refCommandNo;
  refCommandDate.value = row.refCommandDate;
  id.value = row.id;
};

/**
 * เช็คปุ่มดูข้อมูล ย้อน กับ ต่อไป ว่าต้องแสดงไหม
 */
const checkRowPage = () => {
  editRow.value = false;
  next.value = true;
  previous.value = true;
  if (rowIndex.value + 1 >= rows.value.length) {
    next.value = false;
  }
  if (rowIndex.value - 1 < 0) {
    previous.value = false;
  }
};

/**
 * กดปุ่มแก้ไขใน dialog
 */
const clickEdit = () => {
  editRow.value = false;
  next.value = false;
  previous.value = false;
};

/**
 * กดปุ่มเพิ่มด้านบน table
 */
const clickAdd = async () => {
  editRow.value = false;
  await addData();
};

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

/**
 * บันทึกเพิ่มข้อมูล
 */
const saveData = async () => {
  if (profileId.value) {
    showLoader();
    await http
      .post(config.API.profileInsignId(profileId.value), {
        id: id.value,
        insigniaId: insigniaId.value,
        insigniaType: insigniaType.value,
        year: year.value,
        no: no.value,
        issue: issue.value,
        volumeNo: volumeNo.value,
        volume: volume.value,
        section: section.value,
        page: page.value,
        receiveDate: dateToISO(receiveDate.value),
        dateAnnounce: dateToISO(dateAnnounce.value),
        refCommandNo: refCommandNo.value,
        refCommandDate:
          refCommandDate.value == null ? null : dateToISO(refCommandDate.value),
      })
      .then((res) => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        modal.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await fetchData();
      });
  }
};

/**
 * บันทึกแก้ไขข้อมูล
 */
const editData = async () => {
  showLoader();
  await http
    .put(config.API.profileInsignId(id.value), {
      id: id.value,
      insigniaId: insigniaId.value,
      insigniaType: insigniaType.value,
      year: year.value,
      no: no.value,
      issue: issue.value,
      volumeNo: volumeNo.value,
      volume: volume.value,
      section: section.value,
      page: page.value,
      receiveDate: dateToISO(receiveDate.value),
      dateAnnounce: dateToISO(dateAnnounce.value),
      refCommandNo: refCommandNo.value,
      refCommandDate:
        refCommandDate.value == null ? null : dateToISO(refCommandDate.value),
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      modal.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
};

/**
 * ลบลบข้อมูล
 */
const clickDelete = async () => {
  $q.dialog({
    title: `ลบข้อมูล`,
    message: `ต้องการทำการลบข้อมูลนี้ใช่หรือไม่?`,
    cancel: "ยกเลิก",
    ok: "ยืนยัน",
    persistent: true,
  })
    .onOk(async () => {
      showLoader();
      await http
        .delete(config.API.profileInsignId(id.value))
        .then((res) => {
          success($q, "ลบข้อมูลสำเร็จ");
          modal.value = false;
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(async () => {
          await fetchData();
        });
    })
    .onCancel(async () => {
      await fetchData();
    });
};

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

/**
 * กดเลือกข้อมูลที่จะแก้ไข
 * @param props ค่า props ใน row ที่เลือก
 */
const selectData = async (props: DataProps) => {
  modalEdit.value = true;
  modal.value = true;
  edit.value = false;
  rawItem.value = props.row;
  rowIndex.value = props.rowIndex;
  insigniaId.value = props.row.insigniaId;
  insigniaType.value = props.row.insigniaType;
  year.value = props.row.year;
  no.value = props.row.no;
  issue.value = props.row.issue;
  volumeNo.value = props.row.volumeNo;
  volume.value = props.row.volume;
  section.value = props.row.section;
  page.value = props.row.page;
  receiveDate.value = props.row.receiveDate;
  dateAnnounce.value = props.row.dateAnnounce;
  refCommandNo.value = props.row.refCommandNo;
  refCommandDate.value = props.row.refCommandDate;
  id.value = props.row.id;
  await checkRowPage();
};

/**
 * กดปุ่มเพิ่มบน table
 */
const addData = () => {
  modalEdit.value = false;
  modal.value = true;
  edit.value = true;
  insigniaId.value = "";
  insigniaType.value = "";
  year.value = new Date().getFullYear();
  no.value = "";
  issue.value = "";
  volumeNo.value = "";
  volume.value = "";
  section.value = "";
  page.value = "";
  receiveDate.value = new Date();
  dateAnnounce.value = new Date();
  refCommandNo.value = "";
  refCommandDate.value = null;
};

/**
 * ฟังก์ชันปุ่มยกเลิกการแก้ไขข้อมูล
 */
const clickCancel = async () => {
  if (editRow.value == true) {
    $q.dialog({
      title: `ข้อมูลมีการแก้ไข`,
      message: `ยืนยันยกเลิกการแก้ไขใช่หรือไม่?`,
      cancel: "ยกเลิก",
      ok: "ยืนยัน",
      persistent: true,
    }).onOk(async () => {
      edit.value = false;
      await checkRowPage();
      await getData();
    });
  } else {
    edit.value = false;
    await checkRowPage();
  }
};

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

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 * @param row ข้อมูล row ที่ดูประวัติการแก้ไข
 */
const clickHistory = async (row: RequestItemsObject) => {
  modalHistory.value = true;
  showLoader();
  await http
    .get(config.API.profileInsignHisId(row.id))
    .then((res) => {
      let data = res.data.result;
      rowsHistory.value = [];
      data.map((e: ResponseObject) => {
        rowsHistory.value.push({
          id: e.id,
          insignia: e.insignia,
          insigniaId: e.insigniaId,
          insigniaType: e.insigniaType,
          year: e.year,
          no: e.no,
          issue: e.issue,
          volumeNo: e.volumeNo,
          volume: e.volume,
          section: e.section,
          page: e.page,
          receiveDate: new Date(e.receiveDate),
          dateAnnounce: new Date(e.dateAnnounce),
          refCommandNo: e.refCommandNo,
          refCommandDate:
            e.refCommandDate == null ? null : new Date(e.refCommandDate),
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * 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,
  };
};
const resetFilter = () => {};
</script>
<style lang="scss">
.modalfix {
  position: fixed !important;
}
</style>
