<!-- card ประวัติการเปลี่ยนชื่อ-นามสกุล -->
<template>
  <div class="col-12">
    <q-form ref="myForm">
      <div class="col-12 q-pt-md q-pb-sm"><q-separator /></div>
      <ProfileTable
        :rows="rows"
        :columns="columns"
        :filter="filter"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        :add="clickAdd"
        name="ประวัติการเปลี่ยนชื่อ-นามสกุล"
        icon="mdi-book"
        :statusEdit="!statusEdit"
      >
        <template #columns="props">
          <q-tr :props="props">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="statusEdit ? selectData(props) : ''"
              class="cursor-pointer"
            >
              <div v-if="col.name == 'status'" class="table_ellipsis">
                {{ typeChangeName(col.value) }}
              </div>
              <div v-else class="table_ellipsis">
                {{ col.value }}
              </div>
            </q-td>
            <q-td auto-width>
              <q-btn
                v-if="props.row.file != null"
                color="green"
                flat
                dense
                round
                size="14px"
                icon="mdi-file-document-outline"
                @click="openFile(props.row.file)"
              >
                <q-tooltip>ไฟล์เอกสารหลักฐาน</q-tooltip>
              </q-btn>
              <q-btn
                color="info"
                flat
                dense
                round
                size="14px"
                icon="mdi-history"
                @click="clickHistory(props.row)"
              >
                <q-tooltip>ประวัติการเปลี่ยนชื่อ-นามสกุล </q-tooltip>
              </q-btn>
            </q-td>
          </q-tr>
        </template>
      </ProfileTable>
    </q-form>
  </div>
  <!-- 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">
              <selector
                :hide-dropdown-icon="!edit"
                hide-bottom-space
                :class="getClass(edit)"
                :readonly="!edit"
                :borderless="!edit"
                :rules="[(val:string) => !!val || `${'กรุณาเลือก สถานะการเปลี่ยนชื่อ'}`]"
                :outlined="edit"
                dense
                lazy-rules
                v-model="status"
                emit-value
                map-options
                option-label="name"
                :options="Ops.statusOps"
                option-value="id"
                :label="`${'สถานะการเปลี่ยนชื่อ'}`"
                use-input
                input-debounce="0"
                @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'statusOps'
                      ) "
              />
            </div>
            <q-space class="col-6" />
            <div class="col-xs-4 col-sm-4 col-md-4">
              <selector
                :hide-dropdown-icon="!edit"
                hide-bottom-space
                :class="getClass(edit)"
                :readonly="!edit"
                :borderless="!edit"
                :rules="[(val:string) => !!val || `${'กรุณาเลือก คำนำหน้าชื่อ'}`]"
                :outlined="edit"
                dense
                lazy-rules
                v-model="prefixId"
                emit-value
                map-options
                option-label="name"
                :options="Ops.prefixOps"
                option-value="id"
                :label="`${'คำนำหน้าชื่อ'}`"
                use-input
                input-debounce="0"
                @filter="(inputValue:any,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'prefixOps'
                      ) "
              />
            </div>
            <div class="col-xs-4 col-sm-4 col-md-4">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit || status == 'lastName'"
                :borderless="!edit"
                v-model="firstName"
                :rules="[(val) => !!val || `${'กรุณากรอกชื่อ'}`]"
                hide-bottom-space
                :label="`${'ชื่อ'}`"
                @update:modelValue="clickEditRow"
              />
            </div>
            <div class="col-xs-4 col-sm-4 col-md-4">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit || status == 'firstName'"
                :borderless="!edit"
                v-model="lastName"
                :rules="[(val) => !!val || `${'กรุณากรอกนามสกุล'}`]"
                hide-bottom-space
                :label="`${'นามสกุล'}`"
                @update:modelValue="clickEditRow"
              />
            </div>
            <q-btn
              v-if="file != null && !edit"
              color="green"
              flat
              dense
              round
              size="14px"
              icon="mdi-file-document-outline"
              @click="openFile(file)"
            />
            <q-uploader
              v-if="edit"
              color="gray"
              type="file"
              flat
              ref="uploader"
              class="full-width"
              text-color="white"
              :max-size="10000000"
              accept=".jpg,.png,.pdf,.csv,.doc,.docx"
              bordered
              label="[ไฟล์ jpg,png,pdf,csv,doc,docx ขนาดไม่เกิน 10MB]"
              @added="fileAdd"
            >
              <template v-slot:header="scope">
                <div class="row no-wrap items-center q-pa-sm q-gutter-xs">
                  <q-btn
                    v-if="scope.queuedFiles.length > 0"
                    icon="clear_all"
                    @click="scope.removeQueuedFiles"
                    round
                    dense
                    flat
                  >
                    <q-tooltip>ลบทั้งหมด</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="scope.uploadedFiles.length > 0"
                    icon="done_all"
                    @click="scope.removeUploadedFiles"
                    round
                    dense
                    flat
                  >
                    <q-tooltip>ลบไฟล์ที่อัปโหลด</q-tooltip>
                  </q-btn>
                  <q-spinner
                    v-if="scope.isUploading"
                    class="q-uploader__spinner"
                  />
                  <div class="col">
                    <div class="q-uploader__title">
                      {{ "[ไฟล์ jpg,png,pdf,csv,doc,docx ขนาดไม่เกิน 10MB]" }}
                    </div>
                    <div class="q-uploader__subtitle">
                      {{ scope.uploadSizeLabel }} /
                      {{ scope.uploadProgressLabel }}
                    </div>
                  </div>
                  <q-btn
                    v-if="scope.canAddFiles"
                    type="a"
                    icon="add_box"
                    @click="scope.pickFiles"
                    round
                    dense
                    flat
                  >
                    <q-uploader-add-trigger />
                    <q-tooltip>เลือกไฟล์</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="scope.isUploading"
                    icon="clear"
                    @click="scope.abort"
                    round
                    dense
                    flat
                  >
                    <q-tooltip>ยกเลิกการอัปโหลด</q-tooltip>
                  </q-btn>
                </div>
              </template>
            </q-uploader>
          </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"
    :history="true"
  >
    <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 == 'createdAt'" class="table_ellipsis">
            {{ date2Thai(col.value) }}
          </div>
          <div v-else-if="col.name == 'status'" class="table_ellipsis">
            {{ typeChangeName(col.value) }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            v-if="props.row.file != null"
            color="green"
            flat
            dense
            round
            size="14px"
            icon="mdi-file-document-outline"
            @click="openFile(props.row.file)"
          />
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useProfileDataStore } from "@/modules/04_registry/store";
import { useCounterMixin } from "@/stores/mixin";

import ProfileTable from "@/modules/04_registry/components/Table.vue";
import DialogHeader from "@/modules/04_registry/components/DialogHeader.vue";
import DialogFooter from "@/modules/04_registry/components/DialogFooter.vue";
import { useQuasar } from "quasar";
import type {
  RequestItemsObject,
  DataProps,
} from "@/modules/04_registry/interface/request/OldName";
import type { ResponseObject } from "@/modules/04_registry/interface/response/OldName";
import type {
  OldNameOps,
  DataOption,
} from "@/modules/04_registry/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,
  },
  fetchDataInformation: {
    type: Function,
    default: () => console.log("not function"),
  },
  perfixId: {
    type: String,
    required: true,
  },
  firstname: {
    type: String,
    required: true,
  },
  lastname: {
    type: String,
    required: true,
  },
});

const $q = useQuasar();
const store = useProfileDataStore();
const { profileData, changeProfileColumns } = store;

const mixin = useCounterMixin();
const {
  date2Thai,
  success,
  dateToISO,
  messageError,
  typeChangeName,
  dialogMessage,
  showLoader,
  hideLoader,
} = mixin;
const route = useRoute();
const id = ref<string>("");
const prefixId = ref<string>();
const firstName = ref<string>();
const lastName = ref<string>();
const status = ref<string>();
const nameFile = ref<string>("");
const minDate = ref<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.toString());
const file = ref<string | null>(null);
const fileUpload = ref<any>([]);
const rows = ref<RequestItemsObject[]>([]);
const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([]);
const Ops = ref<OldNameOps>({
  prefixOps: [],
  statusOps: [
    {
      id: "firstName",
      name: "เปลี่ยนชื่อ",
    },
    {
      id: "lastName",
      name: "เปลี่ยนนามสกุล",
    },
    {
      id: "all",
      name: "เปลี่ยนชื่อ-นามสกุล",
    },
  ],
});
const OpsFilter = ref<OldNameOps>({
  prefixOps: [],
  statusOps: [
    {
      id: "firstName",
      name: "เปลี่ยนชื่อ",
    },
    {
      id: "lastName",
      name: "เปลี่ยนนามสกุล",
    },
    {
      id: "all",
      name: "เปลี่ยนชื่อ-นามสกุล",
    },
  ],
});
profileData.oldName.columns.length == 0
  ? (visibleColumns.value = ["prefix", "firstName", "lastName", "status"])
  : (visibleColumns.value = profileData.oldName.columns);
const columns = ref<QTableProps["columns"]>([
  {
    name: "prefix",
    align: "left",
    label: "คำนำหน้าชื่อ",
    sortable: true,
    field: "prefix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "firstName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastName",
    align: "left",
    label: "นามสกุล",
    sortable: true,
    field: "lastName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะการเปลี่ยนชื่อ",
    sortable: true,
    field: "status",
    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: "prefix",
    align: "left",
    label: "คำนำหน้าชื่อ",
    sortable: true,
    field: "prefix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "firstName",
    align: "left",
    label: "ชื่อ",
    sortable: true,
    field: "firstName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastName",
    align: "left",
    label: "นามสกุล",
    sortable: true,
    field: "lastName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะการเปลี่ยนชื่อ",
    sortable: true,
    field: "status",
    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[]>([
  "prefix",
  "firstName",
  "lastName",
  "status",
  "createdFullName",
  "createdAt",
]);

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

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

const fetchData = async () => {
  showLoader();
  await http
    .get(config.API.profileChangeNameId(profileId.value))
    .then((res) => {
      let data = res.data.result;
      rows.value = [];
      data.map((e: ResponseObject) => {
        rows.value.push({
          id: e.id,
          prefix: e.prefix,
          prefixId: e.prefixId,
          firstName: e.firstName,
          lastName: e.lastName,
          status: e.status,
          file: e.file,
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

/**
 * get รายการ ข้อมูลเกี่ยวกับบุคคล
 */
const fetchPerson = async () => {
  showLoader();
  await http
    .get(config.API.person)
    .then((res) => {
      const data = res.data.result;
      let optionprefixs: DataOption[] = [];
      data.prefixs.map((r: any) => {
        optionprefixs.push({
          id: r.id.toString(),
          name: r.name.toString(),
        });
      });
      Ops.value.prefixOps = optionprefixs;
      OpsFilter.value.prefixOps = optionprefixs;
    })
    .catch((e: any) => {})
    .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];
  prefixId.value = row.prefixId;
  firstName.value = row.firstName;
  lastName.value = row.lastName;
  status.value = row.status;
  file.value = row.file;
  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 (fileUpload.value.length > 0) {
    const blob = fileUpload.value.slice(0, fileUpload.value[0].size);
    const newFile = new File(blob, nameFile.value, {
      type: fileUpload.value[0].type,
    });
    const formData = new FormData();
    formData.append("", newFile);
    if (prefixId.value != undefined)
      formData.append("prefixId", prefixId.value);
    if (firstName.value != undefined)
      formData.append("firstName", firstName.value);
    if (lastName.value != undefined)
      formData.append("lastName", lastName.value);
    if (status.value != undefined) formData.append("status", status.value);
    showLoader();
    await http
      .post(config.API.profileChangeNameId(profileId.value), formData)
      .then((res) => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        modal.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await fetchData();
        await props.fetchDataInformation();
      });
  } else {
    dialogMessage(
      $q,
      "ไม่สามารถบันทึกข้อมูลได้",
      "กรุณาอัปโหลดเอกสารหลักฐาน",
      "warning",
      undefined,
      "orange",
      undefined,
      undefined,
      true
    );
  }
};

/**
 * บันทึกแก้ไขข้อมูล
 */
const editData = async () => {
  const formData = new FormData();
  if (fileUpload.value.length > 0) {
    const blob = fileUpload.value.slice(0, fileUpload.value[0].size);
    const newFile = new File(blob, nameFile.value, {
      type: fileUpload.value[0].type,
    });
    formData.append("", newFile);
  }
  if (prefixId.value != undefined) formData.append("prefixId", prefixId.value);
  if (firstName.value != undefined)
    formData.append("firstName", firstName.value);
  if (lastName.value != undefined) formData.append("lastName", lastName.value);
  if (status.value != undefined) formData.append("status", status.value);
  showLoader();
  await http
    .put(config.API.profileChangeNameId(id.value), formData)
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      modal.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
      await props.fetchDataInformation();
    });
};

/**
 * ลบลบข้อมูล
 */
const clickDelete = async () => {
  $q.dialog({
    title: `ลบข้อมูล`,
    message: `ต้องการทำการลบข้อมูลนี้ใช่หรือไม่?`,
    cancel: "ยกเลิก",
    ok: "ยืนยัน",
    persistent: true,
  })
    .onOk(async () => {
      showLoader();
      await http
        .delete(config.API.profileChangeNameId(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; //modal ที่เด้งขึ้นมา
  edit.value = false; //ปุ่ม edit ใน modal
  rawItem.value = props.row;
  rowIndex.value = props.rowIndex;
  prefixId.value = props.row.prefixId;
  firstName.value = props.row.firstName;
  lastName.value = props.row.lastName;
  status.value = props.row.status;
  file.value = props.row.file;
  id.value = props.row.id;
  await checkRowPage();
};

/**
 * กดปุ่มเพิ่มบน table
 */
const addData = () => {
  modalEdit.value = false;
  modal.value = true;
  edit.value = true;
  prefixId.value = props.perfixId;
  firstName.value = props.firstname;
  lastName.value = props.lastname;
  status.value = "";
  file.value = "";
};

/**
 * ฟังก์ชันปุ่มยกเลิกการแก้ไขข้อมูล
 */
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.profileChangeNameHisId(row.id))
    .then((res) => {
      let data = res.data.result;
      rowsHistory.value = [];
      data.map((e: ResponseObject) => {
        rowsHistory.value.push({
          id: e.id,
          prefix: e.prefix,
          prefixId: e.prefixId,
          firstName: e.firstName,
          lastName: e.lastName,
          status: e.status,
          file: e.file,
          createdFullName: e.createdFullName,
          createdAt: new Date(e.createdAt),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

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

const fileAdd = async (val: any) => {
  nameFile.value = val[0].name;
  fileUpload.value = val;
};

const openFile = async (val: string | null) => {
  if (val != null) window.open(val);
};

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