<script setup lang="ts">
import { ref, onMounted, computed } 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 type {
  LeaveItem,
  MainList,
} from "@/modules/05_leave/interface/index/main";
import type { QTableProps } from "quasar";

import CalendarView from "@/modules/05_leave/components/Calendar.vue";
import ListView from "@/modules/05_leave/components/ListView.vue";

const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const leaveStore = useLeaveStore();
const { messageError } = mixin;

const row = ref<MainList[]>([]);
const filterLeaveType = ref(["ลาป่วย", "ลากิจส่วนตัว", "ลาพักผ่อน"]);
const itemPie = ref<LeaveItem[]>([]);
const pagination = ref({ rowsPerPage: 15 });
const modalStatsTable = ref<boolean>(false);

/**
 * find ข้อมูลจาก api
 */
const filteredItems = computed(() => {
  return itemPie.value.filter((item) => item.text === "ลาพักผ่อน");
});
const filteredSick = computed(() => {
  return itemPie.value.filter((item) => item.text === "ลาป่วย");
});
const filteredBusi = computed(() => {
  return itemPie.value.filter((item) => item.text === "ลากิจส่วนตัว");
});

const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:5%;",
  },
  {
    name: "leaveTypeName",
    align: "left",
    label: "ประเภทการลา",
    sortable: true,
    field: "leaveTypeName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "leaveLimit",
    align: "left",
    label: "โควตาวันลา",
    sortable: true,
    field: "leaveLimit",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "leaveExtend",
    align: "left",
    label: "วันลาสะสม",
    sortable: true,
    field: "leaveExtend",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },

  {
    name: "leaveCountSend",
    align: "left",
    label: "จำนวนยื่นขอลา (วัน)",
    sortable: true,
    field: "leaveCountSend",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "leaveCountApprove",
    align: "left",
    label: "จำนวนที่อนุมัติ (วัน)",
    sortable: true,
    field: "leaveCountApprove",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "leaveCountReject",
    align: "left",
    label: "จำนวนที่ไม่อนุมัติ (วัน)",
    sortable: true,
    field: "leaveCountReject",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "leaveCountDelete",
    align: "left",
    label: "จำนวนที่ยกเลิก (วัน)",
    sortable: true,
    field: "leaveCountDelete",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
]);

const isloadingSummary = ref<boolean>(false);

/** function เรียกข้อมูลตารางสถิติการลา*/
async function fetchStatsTable() {
  isloadingSummary.value = true;
  await http
    .get(config.API.leaveStats())
    .then((res) => {
      const data = res.data.result;
      const stat = filterLeaveType.value.map((e) => {
        return data
          .filter((el: any) => el.leaveTypeName === e)
          .map((el: any) => ({
            text: el.leaveTypeName,
            color:
              el.leaveTypeName === "ลาพักผ่อน"
                ? "text-pink-5"
                : el.leaveTypeName === "ลากิจส่วนตัว"
                ? "text-deep-purple"
                : "text-indigo",
            value:
              el.leaveLimit > 0
                ? Math.round(
                    (Number(el.leaveCountApprove) / Number(el.leaveLimit)) * 100
                  )
                : 0,
            all: Number(el.leaveLimit),
            use: el.leaveCountApprove,
            remain: Number(el.leaveLimit) - Number(el.leaveCountApprove),
          }));
      });
      stat.forEach((item) => itemPie.value.push(...item));

      row.value = data.map((e: MainList) => ({
        leaveTypeName: e.leaveTypeName,
        leaveLimit:
          e.leaveTypeName === "ลาพักผ่อน"
            ? e.leaveLimit
            : e.leaveTypeName === "ลากิจส่วนตัว"
            ? "-"
            : "-",
        leaveExtend:
          e.leaveTypeName === "ลาพักผ่อน"
            ? e.leaveExtend
            : e.leaveTypeName === "ลากิจส่วนตัว"
            ? "-"
            : "-",
        leavePercent: e.leavePercent,
        leaveCountSend: e.leaveCountSend,
        leaveCountApprove: e.leaveCountApprove,
        leaveCountReject: e.leaveCountReject,
        leaveCountDelete: e.leaveCountDelete,
      }));
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isloadingSummary.value = false;
    });
}

function onClickOpenStat() {
  modalStatsTable.value = true;
}

/** function redirectTo  ยื่นใบลา*/
async function addAbsence() {
  leaveStore.resetForm2();
  router.push(`/leave/add`);
}

onMounted(async () => {
  await fetchStatsTable();
});
</script>

<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="router.push(`/`)"
        />
        <div>รายการลา</div>
      </div>
    </div>

    <div class="col-xs-12 col-sm-12 col-md-11 row">
      <!-- สถิติการลา -->
      <div class="col-12 row q-pb-sm">
        <q-card bordered class="col-12 row" v-if="!isloadingSummary">
          <div class="row col-12 items-center q-px-md q-py-sm">
            <div class="text-weight-bold">สถิติการลา</div>
            <q-space />
            <q-btn
              dense
              flat
              class="text-blue"
              icon="mdi-chart-line-variant"
              @click="onClickOpenStat"
              label="ตารางสถิติการลา"
            />
          </div>
          <div
            bordered
            class="col-6 row justify-center q-px-md q-pb-md q-col-gutter-sm"
            v-for="item in filteredItems"
            :key="item.text"
          >
            <div class="col-xs-12 col-sm-12">
              <q-card bordered flat class="col-12 row shadow-0 no-wrap">
                <div class="col-xs-12 col-sm-8 row justify-center q-py-md">
                  <div class="col-12 row items-center justify-center q-pb-sm">
                    <q-knob
                      readonly
                      v-model="item.value"
                      show-value
                      size="60px"
                      :thickness="0.15"
                      track-color="grey-3"
                      class="text-indigo"
                    >
                      <span class="text-subtitle2 text-weight-bold">{{
                        item.remain
                      }}</span>
                    </q-knob>
                  </div>
                  <div class="col-12 text-center text-weight-medium">
                    ลาพักผ่อน
                  </div>
                </div>
                <div class="row gt-xs"><q-separator vertical /></div>
                <div class="col-xs-12 col-sm-4 gt-xs row">
                  <div class="col-12 row text-dark text-body2 items-center">
                    <div class="col-12 row q-pa-xs q-px-md row">
                      <span class="text-grey-7 col-6">ได้รับ</span>
                      <span class="text-weight-bold">{{ item.all }}</span>
                    </div>
                    <div class="col-12"><q-separator /></div>
                    <div class="col-12 row q-pa-xs q-px-md">
                      <span class="text-grey-7 col-6">ใช้ไป</span>
                      <span class="text-weight-bold">{{ item.use }}</span>
                    </div>
                    <div class="col-12"><q-separator /></div>
                    <div class="col-12 row q-pa-xs q-px-md">
                      <span class="text-grey-7 col-6">คงเหลือ</span>
                      <span class="text-weight-bold">{{ item.remain }}</span>
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </div>

          <div class="col-6 row">
            <div
              bordered
              class="col-12 row justify-center q-px-md q-pb-md q-col-gutter-sm"
              v-for="item in filteredSick"
              :key="item.text"
            >
              <div class="col-xs-12 col-sm-12 row q-col-gutter-sm">
                <div class="col-12 row" v-if="item.text === 'ลาป่วย'">
                  <q-card
                    bordered
                    flat
                    class="shadow-0 col-12 fit row items-center q-px-lg"
                  >
                    <div class="text-subtitle2 col-4">ลาป่วย</div>
                    <div class="text-subtitle2 col-8">
                      <span class="text-grey-7 q-pr-md">ใช้ไป</span>
                      <span class="text-weight-bold">{{ item.use }}</span>
                      <!-- <span class="text-grey-7 q-pl-md">ลา</span> -->
                    </div>
                  </q-card>
                </div>
              </div>
            </div>
            <div
              bordered
              class="col-12 row justify-center q-px-md q-pb-md q-col-gutter-sm"
              v-for="item in filteredBusi"
              :key="item.text"
            >
              <div class="col-xs-12 col-sm-12 row q-col-gutter-sm">
                <div class="col-12 row" v-if="item.text === 'ลากิจส่วนตัว'">
                  <q-card
                    bordered
                    flat
                    class="shadow-0 col-12 fit row items-center q-px-lg"
                  >
                    <div class="text-subtitle2 col-4">ลากิจส่วนตัว</div>
                    <div class="text-subtitle2 col-8">
                      <span class="text-grey-7 q-pr-md">ใช้ไป</span>
                      <span class="text-weight-bold">{{ item.use }}</span>
                      <!-- <span class="text-grey-7 q-pl-md">ลา</span> -->
                    </div>
                  </q-card>
                </div>
              </div>
            </div>
          </div>
        </q-card>

        <q-card bordered class="col-12 row q-px-md q-py-sm" v-else>
          <div class="row col-12 items-center q-px-md q-py-sm">
            <div class="text-weight-bold">สถิติการลา</div>
            <q-space />
            <q-skeleton type="QBtn" size="20px" style="width: 100px" />
          </div>
          <div
            bordered
            class="col-6 row justify-center q-px-md q-pb-md q-col-gutter-sm"
          >
            <div class="col-xs-12 col-sm-12">
              <q-card bordered flat class="col-12 row shadow-0 no-wrap">
                <div class="col-xs-12 col-sm-8 row justify-center q-py-md">
                  <div class="col-12 row items-center justify-center q-pb-sm">
                    <q-skeleton type="circle" size="60px" />

                    <div class="col-12 row items-center justify-center">
                      <q-skeleton type="text" size="20px" style="width: 50px" />
                    </div>
                  </div>
                </div>
                <div class="row gt-xs"><q-separator vertical /></div>
                <div class="col-xs-12 col-sm-4 gt-xs row">
                  <div class="col-12 row text-dark text-body2 items-center">
                    <div class="col-12 row q-pa-xs q-px-md row">
                      <span class="text-grey-7 col-6">ได้รับ</span>
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                    <div class="col-12"><q-separator /></div>
                    <div class="col-12 row q-pa-xs q-px-md">
                      <span class="text-grey-7 col-6">ใช้ไป</span>
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                    <div class="col-12"><q-separator /></div>
                    <div class="col-12 row q-pa-xs q-px-md">
                      <span class="text-grey-7 col-6">คงเหลือ</span>
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                  </div>
                </div>
              </q-card>
            </div>
          </div>
          <div class="col-6 row">
            <div bordered class="col-12 row justify-center q-px-md q-pb-md">
              <div class="col-xs-12 col-sm-12 row">
                <div class="col-12 row">
                  <q-card
                    bordered
                    flat
                    class="shadow-0 col-12 fit row items-center q-px-lg"
                  >
                    <div class="text-subtitle2 col-4">
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                    <div class="text-subtitle2 col-8 row">
                      <span class="text-grey-7 q-pr-md">ใช้ไป</span>
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                  </q-card>
                </div>
              </div>
            </div>
            <div bordered class="col-12 row justify-center q-px-md q-pb-md">
              <div class="col-xs-12 col-sm-12 row">
                <div class="col-12 row">
                  <q-card
                    bordered
                    flat
                    class="shadow-0 col-12 fit row items-center q-px-lg"
                  >
                    <div class="text-subtitle2 col-4">
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                    <div class="text-subtitle2 col-8 row">
                      <span class="text-grey-7 q-pr-md">ใช้ไป</span>
                      <q-skeleton type="text" style="width: 50px" />
                    </div>
                  </q-card>
                </div>
              </div>
            </div>
          </div>
        </q-card>
      </div>

      <div class="row col-12">
        <!-- แสดงปฏิทิน -->
        <div class="col-12 row">
          <q-card bordered class="q-pa-md col-12">
            <div class="row col-12">
              <div class="row items-center">
                <div class="q-ml-sm">
                  <q-btn round dense flat class="q-px-sm" @click="addAbsence">
                    <q-icon name="mdi-plus" color="primary" />
                    <q-tooltip>สร้างใบลา</q-tooltip>
                  </q-btn>
                </div>
              </div>
              <q-space />
              <div class="justify-center row items-center">
                <!-- tab รูปแบบแสดงวันหยุด ปฏิทินกับรายการ -->
                <q-tabs
                  v-model="leaveStore.tabValue"
                  indicator-color="transparent"
                  align="left"
                  active-color="activetab"
                  class="text-nativetab"
                  inline-label
                  dense
                >
                  <q-btn
                    name="calendar"
                    round
                    size="12px"
                    flat
                    icon="mdi-calendar-month"
                    @click="leaveStore.tabValue = 'calendar'"
                    :color="
                      leaveStore.tabValue == 'calendar' ? 'primary' : 'grey-6'
                    "
                    class="q-mr-sm"
                  >
                    <q-tooltip>ปฏิทิน</q-tooltip>
                  </q-btn>
                  <q-separator vertical inset />
                  <q-btn
                    name="list"
                    round
                    size="12px"
                    flat
                    icon="mdi-format-list-bulleted"
                    @click="leaveStore.tabValue = 'list'"
                    :color="
                      leaveStore.tabValue == 'list' ? 'primary' : 'grey-6'
                    "
                    class="q-ml-sm"
                  >
                    <q-tooltip>รายการ</q-tooltip>
                  </q-btn>
                </q-tabs>
              </div>
            </div>
            <div class="col-12">
              <CalendarView v-if="leaveStore.tabValue === 'calendar'" />
            </div>

            <div class="col-12">
              <ListView v-if="leaveStore.tabValue === 'list'" />
            </div>
          </q-card>
        </div>
      </div>
    </div>
  </div>

  <!-- modal ตารางสถิติการลา -->
  <q-dialog v-model="modalStatsTable" persistent>
    <q-card style="min-width: 85%">
      <q-card-section class="row items-center q-pa-sm">
        <div class="text-bold q-pl-sm">ตารางสถิติการลา</div>
        <q-space />
        <q-btn
          icon="close"
          unelevated
          round
          dense
          v-close-popup
          style="color: #ff8080; background-color: #ffdede"
        />
      </q-card-section>
      <q-separator />
      <q-card-section class="q-p-md row">
        <div class="col-12">
          <d-table
            flat
            bordered
            dense
            :rows="row"
            :columns="columns"
            row-key="leaveTypeName"
            hide-bottom
            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-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <q-td v-for="col in props.cols" :key="col.name" :props="props">
                  <div v-if="col.name == 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>
                  <div v-else>
                    {{ col.value }}
                  </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>
                  <q-list>
                    <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'">
                          {{ props.rowIndex + 1 }}
                        </q-item-label>

                        <q-item-label v-else>{{
                          col.value ?? "-"
                        }}</q-item-label>
                      </q-item-section>
                    </q-item>
                  </q-list>
                </q-card>
              </div>
            </template>
          </d-table>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped>
.borderTop {
  border-top: 1px solid #ededed;
  border-bottom: 1px solid #ededed;
}
.custom-table2 {
  .q-table tr:nth-child(odd) td {
    background: white;
  }

  .q-table tr:nth-child(even) td {
    background: #f8f8f8;
  }

  .q-table thead tr {
    background: #ecebeb;
  }

  .q-table thead tr th {
    position: sticky;
  }

  .q-table td:nth-of-type(2) {
    z-index: 3 !important;
  }

  .q-table th:nth-of-type(2),
  .q-table td:nth-of-type(2) {
    position: sticky;
    left: 0;
    z-index: 1;
  }

  /* this will be the loading indicator */
  .q-table thead tr:last-child th {
    /* height of all previous header rows */
    top: 48px;
  }

  .q-table thead tr:first-child th {
    top: 0;
  }
}
</style>
