<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useQuasar } from "quasar";
import { useRouter, useRoute } 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 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>(new Date().getFullYear());
const type = ref<string>("00000000-0000-0000-0000-000000000000");
const status = ref<string>("ALL");
const filter = ref<string>("");

/** pagination*/
const maxPage = ref<number>(1);
const page = ref<number>(1);
const pageSize = ref<number>(10);

/** function เรียกข้อมูลการลา*/
async function fetchDataTable() {
  showLoader();
  const body = {
    year: year.value, //*ปีในการยื่นขอใบลา(ใช้เป็น คศ.)
    type: type.value, //*Id ประเภทการลา
    status: status.value, //*สถานะการของลา
    page: page.value.toString(), //*หน้า
    pageSize: pageSize.value.toString(), //*จำนวนแถวต่อหน้า
    keyword: filter.value, //keyword ค้นหา
  };
  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);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เรียกประเภทการลา */
async function fectOptionType() {
  await http
    .get(config.API.leaveType())
    .then(async (res) => {
      leaveType.value = res.data.result;
      LeaveData.fetchLeaveType(res.data.result);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * 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}`);
}

//เเจ้งเตือนลบข้อมูล
function clickDelete(id: string) {
  dialogRemove($q, () => onClickDelete(id));
}

/**
 * function ลบรายการ
 * @param id
 */
async function onClickDelete(id: string) {
  await http
    .delete(config.API.leaveUserId(id))
    .then(async (res) => {
      success($q, "ลบข้อมูลสำเร็จ");
      fetchDataTable();
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/** 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 = await y;
    type.value = await t;
    status.value = await s;
    filter.value = await k;
    await fetchDataTable();
  }
}

/**
 * function updatePagination
 * @param p หน้า
 * @param ps แถวต่อหน้า
 */
async function updatePagination(p: number, ps: number) {
  (page.value = await p), (pageSize.value = await ps);
  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 "ลาอุปสมบท";
    } else if (type == "LV-006" && val.hajjDayStatus == true) {
      return "ลาประกอบพิธีฮัจญ์";
    } else {
      return val.leaveTypeName;
    }
  }
}

/**
 * เรียกฟังก์ชันทั้งหมดตอนเรียกใช้ไฟล์นี้
 */
onMounted(async () => {
  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"
  >
    <template #columns="props">
      <q-tr :props="props" class="cursor-pointer">
        <q-td
          key="no"
          :props="props"
          @click="onClickView(props.row.id, props.row.status)"
        >
          {{ (page - 1) * pageSize + props.rowIndex + 1 }}
        </q-td>
        <q-td
          key="leaveTypeName"
          :props="props"
          @click="onClickView(props.row.id, props.row.status)"
        >
          {{ convert(props.row) }}
        </q-td>
        <q-td
          key="dateLeave"
          :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 == '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'
              "
              flat
              icon="mdi-dots-vertical"
              color="grey-8"
              for="#cancel"
              dense
              round
              unelevated
            >
              <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-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 == '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>
