<script setup lang="ts">
import { ref, reactive, watch, onMounted } from "vue";
import dialogHeader from "@/components/DialogHeader.vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { QForm, useQuasar } from "quasar";
import { useRoute } from "vue-router";
import type { RequestItemsObject } from "@/modules/04_registryNew/interface/request/ProfesLicense";
import type { ResponseObject } from "@/modules/04_registryNew/interface/response/ProfesLicense";
import http from "@/plugins/http";
import config from "@/app.config";
const mixin = useCounterMixin();
const $q = useQuasar();
const {
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  date2Thai,
} = mixin;

const historyDialog = ref<boolean>(false);
const mode = ref<string>("table");
const dialog = ref<boolean>(false);
const route = useRoute();
const id = ref<string>(route.params.id.toString());
const dialogStatus = ref<string>("create");
const editId = ref<string>("");
const keyword = ref<string>("");
const historyKeyword = 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 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),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const profesLicenseData = reactive<RequestItemsObject>({
  certificateType: "",
  issuer: "",
  certificateNo: "",
  issueDate: new Date(),
  expireDate: null,
  profileId: id.value,
});

const rows = ref<ResponseObject[]>([]);
const historyRows = ref<ResponseObject[]>([]);

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const visibleColumns = ref<string[]>([
  "certificateType",
  "issuer",
  "certificateNo",
  "issueDate",
  "expireDate",
]);

const historyVisibleColumns = ref<string[]>([
  "certificateType",
  "issuer",
  "certificateNo",
  "issueDate",
  "expireDate",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

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

function closeDialog() {
  dialog.value = false;
}
function closeHistoryDialog() {
  historyDialog.value = false;
}

async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewCertificateByProfileId(id))
    .then(async (res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function clearForm() {
  profesLicenseData.expireDate = null;
  profesLicenseData.issueDate = new Date();
  profesLicenseData.certificateNo = "";
  profesLicenseData.certificateType = "";
  profesLicenseData.issuer = "";
}

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;
}

async function addData() {
  await http
    .post(config.API.profileNewCertificate, {
      ...profesLicenseData,
    })
    .then(() => {
      fetchData(id.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function editData(idData: string) {
  await http
    .patch(config.API.profileNewCertificateByCertificateId(idData), {
      ...profesLicenseData,
      profileId: undefined,
    })
    .then(() => {
      fetchData(id.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

// function deleteData(idData: string) {
//   dialogRemove($q, () =>
//     http
//       .delete(config.API.profileNewCertificateByCertificateId(idData))
//       .then(() => {
//         fetchData(id.value);
//       })
//       .catch((err) => {
//         messageError($q, err);
//       })
//       .finally(() => {
//         hideLoader();
//       })
//   );
// }

async function fetchHistoryData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewCertificateHisByCertificateId(id))
    .then(async (res) => {
      historyRows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

onMounted(async () => {
  await fetchData(id.value);
});
</script>

<template>
  <q-toolbar style="padding: 0px" class="q-mb-xs">
    <q-btn
      round
      flat
      color="primary"
      icon="add"
      @click="
        dialogStatus = 'create';
        clearForm();
        dialog = true;
      "
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input dense outlined v-model="keyword" label="ค้นหา" class="q-mr-sm">
      <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"
      options-cover
      style="min-width: 150px"
      class="q-mr-sm"
    />

    <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>
  </q-toolbar>
  <d-table
    :grid="mode === 'card'"
    ref="table"
    :columns="columns"
    :rows="rows"
    row-key="name"
    flat
    bordered
    :paging="true"
    dense
    :filter="keyword"
    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 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" v-if="mode === 'table'">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.id">
          <div>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="primary"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="mdi-pencil-outline"
            clickable
            @click="
              () => {
                editForm(props.row);
              }
            "
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="
              () => (fetchHistoryData(props.row.id), (historyDialog = true))
            "
          >
            <q-tooltip>ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ</q-tooltip>
          </q-btn>
          <!-- <q-btn
            color="red"
            flat
            dense
            round
            size="14px"
            icon="mdi-delete"
            clickable
            @click.stop="deleteData(props.row.id)"
            v-close-popup
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn> -->
        </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="primary"
              icon="edit"
              @click="editForm(props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              color="info"
              icon="mdi-history"
              size="14px"
              @click="
                () => (fetchHistoryData(props.row.id), (historyDialog = true))
              "
            >
              <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-layout
      view="lHh lpr lFf"
      container
      style="height: 300px"
      class="bg-white"
    >
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <q-header>
          <q-toolbar>
            <dialog-header
              :tittle="
                dialogStatus == 'edit'
                  ? 'แก้ไขข้อมูลใบอนุญาตประกอบวิชาชีพ'
                  : 'เพิ่มข้อมูลใบอนุญาตประกอบวิชาชีพ'
              "
              :close="closeDialog"
            />
          </q-toolbar>
          <q-separator color="grey-4" />
        </q-header>

        <q-page-container>
          <q-page>
            <div class="row q-gutter-sm q-px-md q-pb-sm q-mt-sm">
              <div class="col">
                <q-input
                  outlined
                  v-model="profesLicenseData.certificateType"
                  label="ชื่อใบอนุญาต"
                  bg-color="white"
                  dense
                  class="inputgreen"
                  :rules="[(val) => !!val || `${'กรุณากรอกชื่อใบอนุญาต'}`]"
                  hide-bottom-space
                />
              </div>
              <div class="col">
                <q-input
                  outlined
                  v-model="profesLicenseData.issuer"
                  label="หน่วยงานผู้ออกใบอนุญาต"
                  bg-color="white"
                  dense
                  class="inputgreen"
                  :rules="[
                    (val) => !!val || `${'กรุณากรอกหน่วยงานผู้ออกใบอนุญาต'}`,
                  ]"
                  hide-bottom-space
                />
              </div>
            </div>
            <div class="row q-gutter-sm q-px-md q-pb-sm">
              <div class="col">
                <q-input
                  outlined
                  v-model="profesLicenseData.certificateNo"
                  label="เลขที่ใบอนุญาต"
                  bg-color="white"
                  class="inputgreen"
                  dense
                  :rules="[(val) => !!val || `${'กรุณากรอกเลขที่ใบอนุญาต'}`]"
                  hide-bottom-space
                />
              </div>
              <div class="col">
                <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
                      lazy-rules
                      class="inputgreen"
                      outlined
                      bg-color="white"
                      hide-bottom-space
                      :model-value="
                        profesLicenseData.issueDate
                          ? date2Thai(profesLicenseData.issueDate)
                          : ''
                      "
                      :rules="[
                        (val) => !!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-px-md 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-page>
        </q-page-container>
        <q-footer>
          <q-separator color="grey-4" />
          <q-toolbar class="fit row wrap justify-end items-start content-start">
            <q-btn
              dense
              unelevated
              label="บันทึก"
              id="onSubmit"
              type="submit"
              color="public"
              class="q-px-md"
            >
              <q-tooltip>บันทึกข้อมูล</q-tooltip>
            </q-btn>
          </q-toolbar>
        </q-footer>
      </q-form>
    </q-layout>
  </q-dialog>

  <q-dialog v-model="historyDialog" class="dialog" persistent>
    <q-layout
      view="lHh lpr lFf"
      container
      style="height: 500px; min-width: 80%"
      class="bg-white"
    >
      <q-header>
        <q-toolbar>
          <dialog-header
            tittle="ประวัติแก้ไขใบอนุญาตประกอบวิชาชีพ"
            :close="closeHistoryDialog"
          />
        </q-toolbar>
        <q-separator color="grey-4" />
      </q-header>

      <q-page-container>
        <q-page class="q-pa-md">
          <q-toolbar style="padding: 0px" class="text-primary q-mb-sm">
            <q-space />
            <q-input
              dense
              outlined
              bg-color="white"
              v-model="historyKeyword"
              label="ค้นหา"
              class="q-mr-sm"
            >
              <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"
              options-cover
              style="min-width: 150px"
            />
          </q-toolbar>
          <d-table
            ref="table"
            :columns="historyColumns"
            :rows="historyRows"
            row-key="name"
            flat
            :filter="historyKeyword"
            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" class="cursor-pointer">
                <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-page>
      </q-page-container>
    </q-layout>
  </q-dialog>
</template>

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

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