<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import DialogHeader from "@/components/DialogHeader.vue";
import { useCounterMixin } from "@/stores/mixin";
import { useQuasar, type QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";

import type {
  DetailData,
  FormFilter,
} from "@/modules/04_registryNew/interface/index/leave";

const modal = defineModel<boolean>("modal", { required: true });
const id = defineModel<string>("id", { required: true });

const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, date2Thai } = mixin;

const filterKeyword = ref<string>("");
const rows = ref<DetailData[]>([]); //select data history
const formFilter = reactive<FormFilter>({
  page: 1,
  pageSize: 12,
  keyword: "",
  type: "",
  posType: "",
  posLevel: "",
  retireYear: "",
  rangeYear: { min: 0, max: 60 },
  isShowRetire: false,
  isProbation: false,
});

const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});
const visibleColumns = ref<String[]>([
  "no",
  "typeLeave",
  "dateLeave",
  "numLeave",
  "sumLeave",
  "totalLeave",
  "status",
  "reason",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "typeLeave",
    align: "left",
    label: "ประเภทการลา",
    sortable: true,
    field: "typeLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateLeave",
    align: "left",
    label: "วัน เดือน ปี ที่ลา",
    sortable: true,
    field: "dateLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "numLeave",
    align: "left",
    label: "จำนวนวันลา",
    sortable: true,
    field: "numLeave",
    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: "reason",
    align: "left",
    label: "เหตุผล",
    sortable: true,
    field: "reason",
    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" }),
  },
]);
function getHistory() {
  showLoader();
  http
    .get(config.API.profileNewLeaveHistory(id.value))
    .then((res) => {
      let data = res.data.result;
      rows.value = [];
      data.map((e: any) => {
        rows.value.push({
          ...e,
          id: e.id,
          typeLeave: e.leaveType.name,
          code: e.leaveType.refCommandDate,
          dateStartLeave: e.dateLeaveStart,
          dateEndLeave: e.dateLeaveEnd,
          numLeave: e.leaveDays,
          status: e.status,
          reason: e.reason,
          typeLeaveId:
            e.typeLeaveId !== "00000000-0000-0000-0000-000000000000"
              ? e.typeLeaveId
              : "",
        });
      });
    })
    .catch((e) => {
      //   messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * แปลงช่วงวันที่ถ้า2ค่าเป็นวันเดียวกันจะโชววันเดียวแต่ถ้าไม่เท่ากันจะแสดงเป็นช่วง
 * @param val ช่วงวันที่
 */
function dateThaiRange(val: [Date, Date]) {
  if (val === null) {
  } else if (date2Thai(val[0]) === date2Thai(val[1])) {
    return `${date2Thai(val[0])}`;
  } else {
    return `${date2Thai(val[0])} - ${date2Thai(val[1])} `;
  }
}

function statusLeave(val: string) {
  switch (val) {
    case "waitting":
      return "รออนุมัติ";
    case "reject":
      return "ไม่ผ่านการอนุมัติ";
    case "approve":
      return "ผ่านการอนุมัติ";
    case "cancel":
      return "ยกเลิก";
    default:
      return "-";
  }
}

watch(modal, (status) => {
  if (status == true) {
    getHistory();
    filterKeyword.value = "";
  } else {
    filterKeyword.value = "";
  }
});
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader
        tittle="ประวัติแก้ไขการลา"
        :close="() => (modal = false)"
      />
      <q-separator color="grey-4" />
      <q-card-section style="max-height: 60vh" class="scroll">
        <div class="row q-gutter-sm q-mb-sm">
          <q-space />
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            debounce="300"
          >
            <template v-slot:append>
              <q-icon
                v-if="filterKeyword == ''"
                name="search"
                @click.stop.prevent="filterKeyword = ''"
                class="cursor-pointer"
              />
              <q-icon
                v-if="filterKeyword"
                name="cancel"
                @click.stop.prevent="filterKeyword = ''"
                class="cursor-pointer"
              />
            </template>
          </q-input>
          <q-select
            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"
          />
        </div>
        <d-table
          ref="table"
          flat
          bordered
          dense
          :columns="columns"
          :rows="rows"
          :paging="true"
          v-model:pagination="historyPagination"
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="visibleColumns"
          :filter="filterKeyword"
        >
          >
          <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-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 v-if="col.name === 'no'">
                  {{
                    (formFilter.page - 1) * formFilter.pageSize +
                    props.rowIndex +
                    1
                  }}
                </div>
                <div v-else-if="col.name == 'dateLeave'">
                  {{
                    dateThaiRange([
                      props.row.dateStartLeave,
                      props.row.dateEndLeave,
                    ])
                  }}
                </div>
                <div v-else-if="col.name == 'status'">
                  {{ statusLeave(col.value) }}
                </div>
                <div v-else>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
