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

import http from "@/plugins/http";
import config from "@/app.config";
import { useDataStore } from "@/stores/data";

import type { LeaveFormType } from "@/modules/10_registry/interface/index/Main";
import DialogHistory from "@/modules/10_registry/Dialog/DialogHistory.vue";

const link = ref<string>("");
const $q = useQuasar();
const mixin = useCounterMixin();
const dataStore = useDataStore();
const { showLoader, hideLoader, messageError, date2Thai, onSearchDataTable } =
  mixin;

const idByRow = ref<string>("");
const rows = ref<LeaveFormType[]>([]);
const rowsData = ref<LeaveFormType[]>([]);
const filter = ref<string>("");
const rowsHistory = ref<any[]>([]);
const rowsHistoryData = ref<any[]>([]);

const mode = ref<boolean>($q.screen.gt.xs);

const modalHistory = ref<boolean>(false);
/** ตัวแปรข้อมูล */

const visibleColumns = ref<string[]>([
  "no",
  "typeLeave",
  "dateLeave",
  "numLeave",
  "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
        .toString()
        .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, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const pagination = ref({
  sortBy: "lastUpdatedAt",
});

const visibleColumnsHistory = ref<string[]>([
  "no",
  "typeLeave",
  "dateLeave",
  "numLeave",
  "sumLeave",
  "totalLeave",
  "status",
  "reason",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const columnsHistory = 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
        .toString()
        .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 onHistory(id: string) {
  modalHistory.value = true;
  idByRow.value = id;
}

/** get data */
function getData() {
  showLoader();
  http
    .get(config.API.dataUserLeaveByType(link.value))
    .then((res) => {
      const data = res.data.result;
      const listData = data.map((item: any) => ({
        id: item.id,
        typeLeave: item.leaveType.name,
        code: item.leaveType.refCommandDate,
        dateStartLeave: item.dateLeaveStart,
        dateEndLeave: item.dateLeaveEnd,
        numLeave: item.leaveDays,
        status: item.status,
        reason: item.reason,
        typeLeaveId: item.leaveTypeId,
        lastUpdatedAt: item.lastUpdatedAt,
        lastUpdateFullName: item.lastUpdateFullName,
      }));
      rows.value = listData;
      rowsData.value = listData;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** get history */
function getHistory() {
  showLoader();
  http
    .get(config.API.dataUserLeaveHistoryByType(link.value, idByRow.value))
    .then((res) => {
      const data = res.data.result;
      const listData = data.map((item: any) => ({
        id: item.id,
        typeLeave: item.leaveType.name,
        code: item.leaveType.refCommandDate,
        dateStartLeave: item.dateLeaveStart,
        dateEndLeave: item.dateLeaveEnd,
        numLeave: item.leaveDays,
        status: item.status,
        reason: item.reason,
        typeLeaveId: item.leaveTypeId,
        lastUpdateFullName: item.lastUpdateFullName,
        lastUpdatedAt: item.lastUpdatedAt,
      }));
      rowsHistory.value = listData;
      rowsHistoryData.value = listData;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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 onSearch() {
  rows.value = onSearchDataTable(
    filter.value,
    rowsData.value,
    columns.value ? columns.value : []
  );
}

onMounted(async () => {
  link.value = await dataStore.getProFileType();
  getData();
});
</script>
<template>
  <!-- v-if="mode" -->
  <div class="col-12">
    <q-toolbar class="q-px-none q-mt-md">
      <span class="text-blue-6 text-weight-bold text-body1">การลา</span>
      <q-space />
      <q-input
        v-if="mode"
        class="inputgreen"
        outlined
        dense
        v-model="filter"
        label="ค้นหา"
        style="max-width: 200px"
        @keydown.enter.prevent="onSearch"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>
      <q-select
        v-if="mode"
        class="q-ml-sm"
        dense
        multiple
        outlined
        emit-value
        map-options
        options-dense
        option-value="name"
        style="min-width: 140px"
        v-model="visibleColumns"
        :options="columns"
        :display-value="$q.lang.table.columns"
      />
    </q-toolbar>
    <d-table
      flat
      dense
      bordered
      virtual-scroll
      :rows="rows.length !== 0 ? rows : []"
      :columns="columns"
      :grid="!mode"
      :rows-per-page-options="[10, 25, 50, 100]"
      :visible-columns="visibleColumns"
      :virtual-scroll-sticky-size-start="48"
      v-model:pagination="pagination"
    >
      <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-if="mode" v-slot:body="props">
        <q-tr :props="props" class="cursor-pointer">
          <q-td v-for="(col, index) in props.cols" :key="col.name">
            <div v-if="col.name == 'no'">
              {{ 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'">
              {{ props.row.status ? statusLeave(props.row.status) : "-" }}
            </div>
            <div v-else>
              {{ col.value ? col.value : "-" }}
            </div>
          </q-td>
          <q-td auto-width>
            <q-btn
              color="info"
              flat
              dense
              round
              size="14px"
              icon="mdi-history"
              @click="onHistory(props.row.id)"
            >
              <q-tooltip>ประวัติแก้ไขการลา</q-tooltip>
            </q-btn>
          </q-td>
        </q-tr>
      </template>
      <template v-else v-slot:item="props">
        <div class="q-mb-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
          <q-card bordered flat>
            <q-list dense class="q-mt-lg relative-position">
              <q-btn
                icon="mdi-history"
                color="info"
                flat
                dense
                round
                size="14px"
                class="absolute_button"
                @click="onHistory(props.row.id)"
              >
                <q-tooltip>ประวัติแก้ไขการลา</q-tooltip>
              </q-btn>
              <q-item v-for="col in props.cols" :key="col.name">
                <q-item-section class="fix_top">
                  <q-item-label class="text-grey-6 text-weight-medium">{{
                    col.label
                  }}</q-item-label>
                </q-item-section>
                <q-item-section class="fix_top">
                  <q-item-label
                    v-if="col.name == 'dateLeave'"
                    class="text-dark text-weight-medium"
                  >
                    {{
                      dateThaiRange([
                        props.row.dateStartLeave,
                        props.row.dateEndLeave,
                      ])
                    }}</q-item-label
                  >
                  <q-item-label
                    v-else-if="col.name == 'status'"
                    class="text-dark text-weight-medium"
                  >
                    {{
                      props.row.status ? statusLeave(props.row.status) : "-"
                    }}</q-item-label
                  >
                  <q-item-label v-else class="text-dark text-weight-medium">{{
                    col.value ? col.value : "-"
                  }}</q-item-label>
                </q-item-section>
              </q-item>
            </q-list>
          </q-card>
        </div>
      </template>
    </d-table>
  </div>
  <DialogHistory
    v-model:modal="modalHistory"
    :title="'ประวัติแก้ไขการลา'"
    :getData="getHistory"
    :rows="rowsHistory"
    :rows-data="rowsHistoryData"
    :visibleColumns="visibleColumnsHistory"
    :columns="columnsHistory"
    :type="'Leave'"
  />
</template>
<style scoped>
.absolute_button {
  position: absolute;
  right: 5px;
  top: -20px;
}

.fix_top {
  justify-content: start !important;
}
</style>
