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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useLeaveStore } from "@/modules/05_leave/store";
import { calculateFiscalYear } from "@/utils/functions";

import type { LeaveType } from "@/modules/05_leave/interface/response/leave";

import DialogDetail from "@/modules/05_leave/components/DialogDetail.vue";
import Table from "@/modules/05_leave/components/Table.vue";

/**ตัวแปรที่ใช้ */
const $q = useQuasar();
const mixin = useCounterMixin();
const router = useRouter();
const LeaveData = useLeaveStore();
const { showLoader, hideLoader, messageError, dialogRemove, success } = mixin;

const modal = ref<boolean>(false);
const leaveId = ref<string>("");
const leaveType = ref<LeaveType[]>();
const leaveStatus = ref<string>("");

/** filter */
const year = ref<number>(LeaveData.fiscalYearyear);
const type = ref<string>("00000000-0000-0000-0000-000000000000");
const status = ref<string>("ALL");
const filter = ref<string>("");
const isLoading = ref<boolean>(false);

/** pagination*/
const maxPage = ref<number>(1);
const page = ref<number>(1);
const pageSize = ref<number>(10);
const total = ref<number>(0);
const sortBy = ref<string>("dateSendLeave");
const descending = ref<boolean>(true);
/** function เรียกข้อมูลการลา*/
async function fetchDataTable() {
  isLoading.value = true;
  const body = {
    year: year.value, //*ปีในการยื่นขอใบลา(ใช้เป็น คศ.)
    type: LeaveData.type, //*Id ประเภทการลา
    status: LeaveData.status, //*สถานะการของลา
    page: page.value.toString(), //*หน้า
    pageSize: pageSize.value.toString(), //*จำนวนแถวต่อหน้า
    keyword: filter.value, //keyword ค้นหา
    ...(sortBy.value && {
      sortBy: sortBy.value,
      descending: descending.value,
    }),
  };
  await http
    .post(config.API.leaveTableList(), body)
    .then((res) => {
      const data = res.data.result.data;
      LeaveData.fetchListLeave(data);
      maxPage.value = Math.ceil(res.data.result.total / pageSize.value);
      total.value = res.data.result.total;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoading.value = false;
    });
}

/** function เรียกประเภทการลา */
async function fectOptionType() {
  const data = await LeaveData.fetchLeaveTypeData();
  if (!data) {
    return;
  }
  leaveType.value = data;
  LeaveData.fetchLeaveType(data);
}

/**
 * function openPopupDateail
 * @param id การลา
 * @param status การลา
 */
async function onClickView(id: string, status: string) {
  modal.value = true;
  leaveId.value = id;
  leaveStatus.value = status;
}

/**
 * function ไปหน้า edit
 * @param id
 */
async function onClickEdit(id: string) {
  router.push(`/leave/edit/${id}`);
}

/**
 * ฟังก์ชันลบข้อมูลการลา
 * @param id รายการลาที่ต้องการลบ
 */
function clickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.leaveUserId(id))
      .then(async () => {
        await fetchDataTable();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/** function closePopup*/
async function onClickClose() {
  modal.value = false;
}

/**
 * function updateFilter
 * @param y ปีงบประมาณ
 * @param t ประเภทการลา
 * @param s สภานะ
 * @param k คำค้นหา
 */
async function updateFilterTable(y: number, t: string, s: string, k: string) {
  if (t && s) {
    year.value = y;
    type.value = t;
    status.value = s;
    filter.value = k;
    LeaveData.fiscalYearyear = y;
    await fetchDataTable();
  }
}

/**
 * function updatePagination
 * @param p หน้า
 * @param ps แถวต่อหน้า
 * @param s เรียงลำดับตาม
 * @param d เรียงลำดับจากน้อยไปมาก
 */
async function updatePagination(p: number, ps: number, s: string, d: boolean) {
  page.value = p;
  pageSize.value = ps;
  sortBy.value = s;
  descending.value = d;
  await fetchDataTable();
}

function convert(val: any) {
  if (leaveType.value) {
    const filtertype = leaveType.value.find(
      (e: any) => e.id === val.leaveTypeId
    );
    const type = filtertype?.code;
    if (type == "LV-006" && val.hajjDayStatus == false) {
      return "ลาอุปสมบทหรือการลาประกอบพิธีฮัจญ์ฯ";
      // return "ลาอุปสมบท"; รอ API
    } else if (type == "LV-006" && val.hajjDayStatus == true) {
      return "ลาอุปสมบทหรือการลาประกอบพิธีฮัจญ์ฯ";
      // return "ลาประกอบพิธีฮัจญ์"; รอ API
    } else {
      return val.leaveTypeName;
    }
  }
}

/**
 * เรียกฟังก์ชันทั้งหมดตอนเรียกใช้ไฟล์นี้
 */
onMounted(async () => {
  year.value = LeaveData.fiscalYearyear;
  await fectOptionType();
  await fetchDataTable();
});
</script>
<template>
  <Table
    :rows="LeaveData.rows"
    :columns="LeaveData.columns"
    :visible-columns="LeaveData.visibleColumns"
    v-model:inputfilter="filter"
    v-model:inputvisible="LeaveData.visibleColumns"
    :inputShow="true"
    :grid="$q.screen.gt.xs ? false : true"
    @update:filter="updateFilterTable"
    @update:Pagination="updatePagination"
    :maxPage="maxPage"
    :pageSize="pageSize"
    :leaveType="leaveType"
    :total="total"
    :sortBy="sortBy"
    :descending="descending"
    :isloadingData="isLoading"
  >
    <template #columns="props">
      <q-tr :props="props" class="cursor-pointer">
        <q-td
          key="no"
          :props="props"
          @click="onClickView(props.row.id, props.row.status)"
        >
          {{ props.rowIndex + 1 }}
        </q-td>
        <q-td
          key="leaveTypeName"
          :props="props"
          @click="onClickView(props.row.id, props.row.status)"
        >
          {{
            props.row.leaveTypeName
              ? `${props.row.leaveTypeName} ${
                  props.row.leaveSubTypeName
                    ? `(${props.row.leaveSubTypeName})`
                    : ""
                }`
              : "-"
          }}
        </q-td>
        <q-td
          key="leaveStartDate"
          :props="props"
          @click="onClickView(props.row.id, props.row.status)"
        >
          {{ props.row.dateLeave }}
        </q-td>
        <q-td
          key="dateSendLeave"
          :props="props"
          @click="onClickView(props.row.id, props.row.status)"
        >
          {{ props.row.dateSendLeave }}
        </q-td>

        <q-td key="status" :props="props">
          <div class="col-12 row items-center">
            <div @click="onClickView(props.row.id, props.row.status)">
              <q-icon
                v-if="props.row.status == 'DRAFT'"
                size="10px"
                color="light-grey"
                name="mdi-circle"
                class="q-mr-sm"
              />
              <q-icon
                v-if="props.row.status == 'APPROVE'"
                size="10px"
                color="light-green"
                name="mdi-circle"
                class="q-mr-sm"
              />
              <q-icon
                v-else-if="props.row.status == 'REJECT'"
                size="10px"
                color="red-6"
                name="mdi-circle"
                class="q-mr-sm"
              />
              <q-icon
                v-else-if="props.row.status == 'PENDING'"
                size="10px"
                color="light-blue-14"
                name="mdi-circle"
                class="q-mr-sm"
              />
              <q-icon
                v-else-if="props.row.status == 'NEW'"
                size="10px"
                color="orange"
                name="mdi-circle"
                class="q-mr-sm"
              />
              <q-icon
                v-if="
                  props.row.status == 'DELETING' || props.row.status == 'DELETE'
                "
                size="10px"
                color="grey-10"
                name="mdi-circle"
                class="q-mr-sm"
              />

              <span class="q-pr-md">{{ props.row.statusConvert }}</span>
            </div>
            <q-space />

            <q-btn
              v-if="
                props.row.status != 'DELETE' &&
                props.row.status != 'REJECT' &&
                props.row.status != 'CANCEL' &&
                props.row.status != 'DELETING'
              "
              flat
              icon="mdi-dots-vertical"
              color="grey-8"
              for="#cancel"
              dense
              round
              unelevated
            >
              <q-menu>
                <q-list>
                  <q-item
                    v-if="props.row.status != 'DRAFT'"
                    clickable
                    v-close-popup
                    @click="onClickView(props.row.id, 'CANCEL')"
                  >
                    <q-item-section>
                      <q-item-label>ขอยกเลิก</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-if="props.row.status == 'DRAFT'"
                    clickable
                    v-close-popup
                    @click="onClickEdit(props.row.id)"
                  >
                    <q-item-section>
                      <q-item-label>แก้ไข</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-if="props.row.status == 'DRAFT'"
                    clickable
                    v-close-popup
                    @click="clickDelete(props.row.id)"
                  >
                    <q-item-section>
                      <q-item-label>ลบรายการการลา</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>
          </div>
        </q-td>
      </q-tr>
    </template>

    <template #item="props">
      <div class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
        <q-card bordered flat>
          <div class="row justify-end">
            <q-btn
              v-if="
                props.row.status != 'DELETE' &&
                props.row.status != 'REJECT' &&
                props.row.status != 'CANCEL'
              "
              flat
              icon="mdi-dots-vertical"
              color="grey-8"
              for="#cancel"
              dense
              round
              unelevated
              @click.pervent
            >
              <q-menu>
                <q-list>
                  <q-item
                    clickable
                    v-close-popup
                    @click="onClickView(props.row.id, 'CANCEL')"
                  >
                    <q-item-section>
                      <q-item-label>ขอยกเลิก</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-if="props.row.status == 'DRAFT'"
                    clickable
                    v-close-popup
                    @click="onClickEdit(props.row.id)"
                  >
                    <q-item-section>
                      <q-item-label>แก้ไข</q-item-label>
                    </q-item-section>
                  </q-item>
                  <q-item
                    v-if="props.row.status == 'DRAFT'"
                    clickable
                    v-close-popup
                    @click="clickDelete(props.row.id)"
                  >
                    <q-item-section>
                      <q-item-label>ลบรายการการลา</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-menu>
            </q-btn>
          </div>

          <q-separator />
          <q-list @click.prevent="onClickView(props.row.id, props.row.status)">
            <q-item
              v-for="col in props.cols.filter((col:any) => col.name !== 'desc')"
              :key="col.name"
            >
              <q-item-section>
                <q-item-label caption>{{ col.label }}</q-item-label>

                <q-item-label v-if="col.name === 'no'">
                  {{ (page - 1) * pageSize + props.rowIndex + 1 }}
                </q-item-label>
                <q-item-label v-if="col.name === 'status'">
                  <q-icon
                    v-if="props.row.status == 'DRAFT'"
                    size="10px"
                    color="light-grey"
                    name="mdi-circle"
                    class="q-mr-sm"
                  />
                  <q-icon
                    v-if="props.row.status == 'APPROVE'"
                    size="10px"
                    color="light-green"
                    name="mdi-circle"
                    class="q-mr-sm"
                  />
                  <q-icon
                    v-else-if="props.row.status == 'REJECT'"
                    size="10px"
                    color="red-6"
                    name="mdi-circle"
                    class="q-mr-sm"
                  />
                  <q-icon
                    v-else-if="props.row.status == 'PENDING'"
                    size="10px"
                    color="light-blue-14"
                    name="mdi-circle"
                    class="q-mr-sm"
                  />
                  <q-icon
                    v-else-if="props.row.status == 'NEW'"
                    size="10px"
                    color="orange"
                    name="mdi-circle"
                    class="q-mr-sm"
                  />
                  <q-icon
                    v-if="
                      props.row.status == 'DELETING' ||
                      props.row.status == 'DELETE'
                    "
                    size="10px"
                    color="grey-10"
                    name="mdi-circle"
                    class="q-mr-sm"
                  />

                  <span class="q-pr-md">{{ props.row.statusConvert }}</span>
                </q-item-label>
                <q-item-label v-else>{{ col.value }}</q-item-label>
              </q-item-section>
            </q-item>
          </q-list>
        </q-card>
      </div>
    </template>
  </Table>

  <DialogDetail
    :modal="modal"
    :leaveId="leaveId"
    :leaveStatus="leaveStatus"
    :onClickClose="onClickClose"
    :leaveType="leaveType"
    :fetchDataTable="fetchDataTable"
  />
</template>
