<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { QForm, useQuasar } from "quasar";

import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/request/ProfesLicense";
import type { ResponseObject } from "@/modules/04_registryPerson/interface/response/ProfesLicense";

import dialogHeader from "@/components/DialogHeader.vue";

const route = useRoute();
const mixin = useCounterMixin();
const $q = useQuasar();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  date2Thai,
  pathRegistryEmp,
} = mixin;

const id = ref<string>(route.params.id.toString());
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));
/**
 * props
 */
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});

const mode = ref<string>("table"); //การแสดงผล Table,Card
const dialog = ref<boolean>(false); //แสดง popup ข้อมูลใบอนุญาตประกอบวิชาชีพ
const historyDialog = ref<boolean>(false); //แสดง popup ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ
const dialogStatus = ref<string>("create"); //สถานะการแก้ไขข้อมูล
const editId = ref<string>(""); //id ที่ต้องการแก้ไข

//Table Main
const rows = ref<ResponseObject[]>([]); //รายการใบอนุญาตประกอบวิชาชีพ
const keyword = ref<string>(""); //คำค้นหา
const columns = ref<QTableProps["columns"]>([
  {
    name: "certificateType",
    align: "left",
    label: "ชื่อใบอนุญาต",
    sortable: true,
    field: "certificateType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issuer",
    align: "left",
    label: "หน่วยงานผู้ออกใบอนุญาต",
    sortable: true,
    field: "issuer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "certificateNo",
    align: "left",
    label: "เลขที่ใบอนุญาต",
    sortable: true,
    field: "certificateNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issueDate",
    align: "left",
    label: "วันที่ออกใบอนุญาต",
    sortable: true,
    field: "issueDate",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "expireDate",
    align: "left",
    label: "วันที่หมดอายุ",
    sortable: true,
    format: (v) => date2Thai(v),
    field: "expireDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<string[]>([
  "certificateType",
  "issuer",
  "certificateNo",
  "issueDate",
  "expireDate",
]);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

//Table ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ
const historyRows = ref<ResponseObject[]>([]); //รายการประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ
const historyKeyword = ref<string>(""); //คำค้นหาประวัติแก้ไข
const historyColumns = ref<QTableProps["columns"]>([
  {
    name: "certificateType",
    align: "left",
    label: "ชื่อใบอนุญาต",
    sortable: true,
    field: "certificateType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issuer",
    align: "left",
    label: "หน่วยงานผู้ออกใบอนุญาต",
    sortable: true,
    field: "issuer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "certificateNo",
    align: "left",
    label: "เลขที่ใบอนุญาต",
    sortable: true,
    field: "certificateNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issueDate",
    align: "left",
    label: "วันที่ออกใบอนุญาต",
    sortable: true,
    field: "issueDate",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "expireDate",
    align: "left",
    label: "วันที่หมดอายุ",
    sortable: true,
    format: (v) => date2Thai(v),
    field: "expireDate",
    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" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const historyVisibleColumns = ref<string[]>([
  "certificateType",
  "issuer",
  "certificateNo",
  "issueDate",
  "expireDate",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const profesLicenseData = reactive<RequestItemsObject>({
  certificateType: "", //ชื่อใบอนุญาต
  issuer: "", //หน่วยงานผู้ออกใบอนุญาต
  certificateNo: "", //เลขที่ใบอนุญาต
  issueDate: new Date(), //วันที่ออกใบอนุญาต
  expireDate: null, //วันที่หมดอายุ
  profileId: id.value,
});

/**
 * ยืนยันการบันทึกข้อมูล
 */
function onSubmit() {
  dialogConfirm(
    $q,
    () => {
      dialogStatus.value === "create" ? addData() : editData(editId.value);
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/**
 * ปิด form  ข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function closeDialog() {
  dialog.value = false;
}

/**
 * ปิด popup ประวัติการแก้ไขข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function closeHistoryDialog() {
  historyDialog.value = false;
  historyRows.value = [];
  historyKeyword.value = "";
}

/**
 * fetch ข้อมูลรายการใบอนุญาตประกอบวิชาชีพ
 */
async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewCertificateByProfileId(id, empType.value))
    .then(async (res) => {
      rows.value = await res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * เคลียร์ form ข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function clearForm() {
  profesLicenseData.expireDate = null;
  profesLicenseData.issueDate = new Date();
  profesLicenseData.certificateNo = "";
  profesLicenseData.certificateType = "";
  profesLicenseData.issuer = "";
}

/**
 * เปิด form แก้ไขข้อมูลใบอนุญาตประกอบวิชาชีพ
 * @param row  ข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function editForm(row: any) {
  dialogStatus.value = "edit";
  editId.value = row.id;
  profesLicenseData.certificateType = row.certificateType;
  profesLicenseData.certificateNo = row.certificateNo;
  profesLicenseData.issuer = row.issuer;
  profesLicenseData.issueDate = row.issueDate;
  profesLicenseData.expireDate = row.expireDate;
  dialog.value = true;
}

/**
 * เพิ่มรายการข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function addData() {
  showLoader();
  http
    .post(config.API.profileNewCertificate(empType.value), {
      ...profesLicenseData,
      profileId: empType.value === "" ? id.value : undefined,
      profileEmployeeId: empType.value !== "" ? id.value : undefined,
    })
    .then(async () => {
      await fetchData(id.value);
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * แก้ไขข้อมูลใบอนุญาตประกอบวิชาชีพ
 * @param idData  รายการข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function editData(idData: string) {
  showLoader();
  http
    .patch(
      config.API.profileNewCertificateByCertificateId(idData, empType.value),
      {
        ...profesLicenseData,
        profileId: undefined,
      }
    )
    .then(async () => {
      await fetchData(id.value);
      await success($q, "บันทึกข้อมูลสำเร็จ");
      closeDialog();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * fetch ข้อมูลประวัติการแก้ไขข้อมูลใบอนุญาตประกอบวิชาชีพ
 */
function fetchHistoryData(id: string) {
  showLoader();
  http
    .get(config.API.profileNewCertificateHisByCertificateId(id, empType.value))
    .then(async (res) => {
      historyRows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(() => {
  fetchData(id.value);
});
</script>

<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
      round
      flat
      color="primary"
      icon="add"
      dense
      @click="
        dialogStatus = 'create';
        clearForm();
        dialog = true;
      "
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input dense outlined v-model="keyword" label="ค้นหา">
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      v-if="mode === 'table'"
      v-model="visibleColumns"
      multiple
      outlined
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      style="min-width: 140px"
    />

    <q-btn-toggle
      v-model="mode"
      dense
      class="no-shadow toggle-borderd"
      toggle-color="grey-4"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="24px"
          :style="{
            color: mode === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="24px"
          :style="{
            color: mode === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </div>

  <d-table
    :grid="mode === 'card'"
    ref="table"
    :columns="columns"
    :rows="rows"
    row-key="name"
    flat
    bordered
    :paging="true"
    dense
    :filter="keyword.trim()"
    v-model:pagination="pagination"
    :rows-per-page-options="[20, 50, 100]"
    class="custom-header-table"
    :visible-columns="visibleColumns"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium">{{ col.label }}</span>
        </q-th>
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="mode === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click="
              () => (fetchHistoryData(props.row.id), (historyDialog = true))
            "
          >
            <q-tooltip>ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ</q-tooltip>
          </q-btn>
          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            clickable
            @click="
              () => {
                editForm(props.row);
              }
            "
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.id">
          <div>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>
    <template v-slot:item="props" v-else>
      <div
        class="q-pa-xs col-xs-12 col-sm-6 col-md-6 col-lg-6 grid-style-transition"
      >
        <q-card bordered>
          <q-card-actions align="right" class="bg-grey-3">
            <q-btn
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="
                () => (fetchHistoryData(props.row.id), (historyDialog = true))
              "
            >
              <q-tooltip>ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ</q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              flat
              round
              color="edit"
              icon="edit"
              @click="editForm(props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <q-list>
            <div
              :class="`row q-pa-sm`"
              :style="`background-color: ${index % 2 !== 0 ? '#FAFAFA' : ''}`"
              v-for="(col, index) in props.cols"
              :key="col.name"
            >
              <div></div>
              <div class="col label-color">
                <div>{{ col.label }}</div>
              </div>
              <div class="col">
                <div>{{ col.value }}</div>
              </div>
            </div>
          </q-list>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="dialog" class="dialog" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <dialog-header
          :tittle="
            dialogStatus == 'edit'
              ? 'แก้ไขข้อมูลใบอนุญาตประกอบวิชาชีพ'
              : 'เพิ่มข้อมูลใบอนุญาตประกอบวิชาชีพ'
          "
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm q-pb-sm">
            <div class="col-xs-12 col-md-6">
              <q-input
                outlined
                v-model="profesLicenseData.certificateType"
                label="ชื่อใบอนุญาต"
                bg-color="white"
                dense
                class="inputgreen"
                :rules="[(val:string) => !!val || `${'กรุณากรอกชื่อใบอนุญาต'}`]"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-12 col-md-6">
              <q-input
                outlined
                v-model="profesLicenseData.issuer"
                label="หน่วยงานผู้ออกใบอนุญาต"
                bg-color="white"
                dense
                class="inputgreen"
                :rules="[
                  (val:string) => !!val || `${'กรุณากรอกหน่วยงานผู้ออกใบอนุญาต'}`,
                ]"
                hide-bottom-space
              />
            </div>
          </div>
          <div class="row q-col-gutter-sm q-pb-sm">
            <div class="col-xs-12 col-md-6">
              <q-input
                outlined
                v-model="profesLicenseData.certificateNo"
                label="เลขที่ใบอนุญาต"
                bg-color="white"
                class="inputgreen"
                dense
                :rules="[(val:string) => !!val || `${'กรุณากรอกเลขที่ใบอนุญาต'}`]"
                hide-bottom-space
              />
            </div>
            <div class="col-xs-12 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="profesLicenseData.issueDate"
                :locale="'th'"
                autoApply
                class="col"
                :enableTimePicker="false"
                @update:modelValue="profesLicenseData.issueDate"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    class="inputgreen"
                    outlined
                    bg-color="white"
                    hide-bottom-space
                    :model-value="
                      profesLicenseData.issueDate
                        ? date2Thai(profesLicenseData.issueDate)
                        : ''
                    "
                    :rules="[
                      (val:string) => !!val || `${'กรุณาเลือกวันที่ออกใบอนุญาต'}`,
                    ]"
                    :label="`${'วันที่ออกใบอนุญาต'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
          </div>
          <div class="row q-gutter-sm q-pb-sm">
            <div class="col">
              <datepicker
                menu-class-name="modalfix"
                v-model="profesLicenseData.expireDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                @update:modelValue="profesLicenseData.expireDate"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    bg-color="white"
                    class="inputgreen"
                    clearable
                    @clear="() => (profesLicenseData.expireDate = null)"
                    hide-bottom-space
                    :model-value="
                      profesLicenseData.expireDate
                        ? date2Thai(profesLicenseData.expireDate)
                        : ''
                    "
                    :label="`${'วันที่หมดอายุ'}`"
                    @update:modelValue="profesLicenseData.expireDate = null"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        style="color: var(--q-primary)"
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="historyDialog" class="dialog" persistent>
    <q-card style="min-width: 80%">
      <dialog-header
        tittle="ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ"
        :close="closeHistoryDialog"
      />
      <q-separator />

      <q-card-section style="max-height: 60vh" class="scroll">
        <div class="row q-gutter-sm q-mb-sm">
          <q-space />
          <q-input
            dense
            outlined
            bg-color="white"
            v-model="historyKeyword"
            label="ค้นหา"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>

          <q-select
            v-model="historyVisibleColumns"
            multiple
            outlined
            dense
            bg-color="white"
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="historyColumns"
            option-value="name"
            style="min-width: 140px"
          />
        </div>
        <d-table
          ref="table"
          :columns="historyColumns"
          :rows="historyRows"
          row-key="name"
          flat
          :filter="historyKeyword.trim()"
          v-model:pagination="historyPagination"
          bordered
          :paging="true"
          dense
          :rows-per-page-options="[20, 50, 100]"
          class="custom-header-table"
          :visible-columns="historyVisibleColumns"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
              <q-th auto-width />
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td v-for="col in props.cols" :key="col.id">
                <div>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style scoped>
.bg-color {
  background-color: #fafafa;
}

.label-color {
  color: #747474cc;
}
</style>
