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

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

import type { QTableColumn } from "quasar";
import type { ResAbsentLateData} from "@/modules/04_registryPerson/interface/response/Government";

import DialogAbsentLate from "@/modules/04_registryPerson/components/detail/GovernmentInformation/08_DialogAbsentLate.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";

const route = useRoute();
const absentLateStore = useAbsentLateStore();
const $q = useQuasar();
const {
  date2Thai,
  dialogConfirm,
  showLoader,
  hideLoader,
  messageError,
  success,
  pathRegistryEmp,
  onSearchDataTable,
  convertDateToAPI,
  dialogRemove,
} = useCounterMixin();

const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

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

const baseColumns = ref<QTableColumn[]>([
  {
    name: "status",
    align: "left",
    label: "มาสาย/ ขาดราชการ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      const status = absentLateStore.statusOps.find(
        (option) => option.id === val
      );
      return status ? status.name : val;
    },
  },
  {
    name: "stampDate",
    align: "left",
    label: "วันที่ลงเวลา",
    sortable: true,
    field: "stampDate",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "stampType",
    align: "left",
    label: "ประเภทการลงเวลา",
    sortable: true,
    field: "stampType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val) {
      const type = absentLateStore.stampTypeOps.find(
        (option) => option.id === val
      );
      return type ? type.name : val;
    },
  },
  {
    name: "stampAmount",
    align: "left",
    label: "จำนวน",
    sortable: true,
    field: "stampAmount",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const baseVisibleColumns = ref<string[]>([
  "status",
  "stampDate",
  "stampType",
  "stampAmount",
  "remark",
]);

/** Table*/
const rows = ref<ResAbsentLateData[]>([]);
const rowsMain = ref<ResAbsentLateData[]>([]);
const mode = ref<string>("table"); //การแสดงผล Table card
const filterKeyword = ref<string>(""); //คำค้นหา
const columns = ref<QTableColumn[]>(
  baseColumns.value.filter((e: QTableColumn) => e.name !== "lastUpdateFullName")
);
const visibleColumns = ref<string[]>(
  baseVisibleColumns.value.filter((e: string) => e !== "lastUpdateFullName")
);
const pagination = ref({
  sortBy: "lastUpdatedAt",
});

const columnsHistory = ref<QTableColumn[]>(baseColumns.value);
const visibleColumnsHistory = ref<string[]>(baseVisibleColumns.value);

/** Dialog*/
const isStatusEdit = ref<boolean>(false);
const modal = ref<boolean>(false);
const modalHistory = ref<boolean>(false);
const rowId = ref<string>("");
const dataAbsentLate = ref<ResAbsentLateData | null>(null);

async function fetchData() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileAbsentLate(empType.value) + `/${profileId.value}`
    );
    const data = res.data.result;
    rowsMain.value = data;
    serchDataTable();
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

/** function fetch ข้อมูลประวัติการแก้ไขข้อมูล*/
async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileAbsentLateHistory(rowId.value, empType.value)
    );
    return res.data.result;
  } catch (err) {
    messageError($q, err);
  } finally {
    hideLoader();
  }
}

function openEditDialog(data: any) {
  modal.value = true;
  isStatusEdit.value = true;
  rowId.value = data.id;
  dataAbsentLate.value = data;
}

function showHistoryDialog(id: string) {
  modalHistory.value = true;
  rowId.value = id;
}

/** ฟังก์ค้นหาข้อมูลขาดราชการ/มาสาย*/
function serchDataTable() {
  rows.value = onSearchDataTable(
    filterKeyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

function onDelete(rowId: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.patch(
        config.API.profileAbsentLateUpdateDelete(empType.value) + `/${rowId}`
      );
      await fetchData();
      await success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

onMounted(() => {
  fetchData();
});
</script>

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

    <q-space />
    <q-input
      standout
      dense
      v-model="filterKeyword"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      @keydown.enter.prevent="serchDataTable"
    >
      <template v-slot:append>
        <q-icon name="search" />
      </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"
      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"
    row-key="id"
    flat
    bordered
    dense
    :columns="columns"
    :rows="rows"
    :visible-columns="visibleColumns"
    v-model:pagination="pagination"
  >
    >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width></q-th>
        <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.stop.prevent="showHistoryDialog(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขขาดราชการ/มาสาย</q-tooltip>
          </q-btn>
          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            @click.stop.prevent="openEditDialog(props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>

          <q-btn
            v-if="!isLeave && checkPermission($route)?.attrIsDelete"
            flat
            dense
            round
            color="red"
            icon="delete"
            @click.stop.prevent="onDelete(props.row.id)"
          >
            <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-4 col-md-3">
        <q-card flat bordered>
          <q-card-actions align="right" class="bg-grey-3">
            <q-btn
              color="deep-purple"
              icon="mdi-history"
              flat
              round
              @click.stop.prevent="showHistoryDialog(props.row.id)"
            >
              <q-tooltip>ประวัติแก้ไขขาดราชการ/มาสาย</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave === false && checkPermission($route)?.attrIsUpdate"
              :color="props.row.commandId ? 'grey-5' : 'edit'"
              :disable="props.row.commandId !== null"
              icon="edit"
              flat
              round
              @click.stop.prevent="openEditDialog(props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave === false && checkPermission($route)?.attrIsDelete"
              color="red"
              icon="delete"
              flat
              round
              @click.stop.prevent="onDelete(props.row.id)"
            >
              <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 class="col text-grey-6">
                <div>{{ col.label }}</div>
              </div>
              <div class="col">
                <div>{{ col.value ? col.value : "-" }}</div>
              </div>
            </div>
          </q-list>
        </q-card>
      </div>
    </template>
  </d-table>

  <DialogAbsentLate
    v-model:modal="modal"
    v-model:isStatusEdit="isStatusEdit"
    :fetchData="fetchData"
    :rowId="rowId"
    :dataAbsentLate="dataAbsentLate"
  />

  <DialogHistory
    v-model:modal="modalHistory"
    :title="`ประวัติแก้ไขขาดราชการ/มาสาย`"
    :columns="columnsHistory"
    :visible-columns="visibleColumnsHistory"
    :fetch-data="fetchDataHistory"
  />
</template>

<style scoped></style>
