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

import TableHistory from '@/components/TableHistory.vue'
import ToolBar from '@/components/ToolBar.vue'

import http from '@/plugins/http'
import config from '@/app.config'
import { useCounterMixin } from '@/stores/mixin'
// importStores
import { useChekIn } from '@/stores/chekin'

const mixin = useCounterMixin()
const router = useRouter()
const stores = useChekIn()
const { showLoader, hideLoader, messageError } = mixin
const { fetchHistoryList } = stores
const $q = useQuasar() //ใช้ noti quasar

const tab = ref<string>('history')

// paging
const page = ref<number>(1)
const year = ref<number>(new Date().getFullYear())
const month = ref<number>(new Date().getMonth())
const pageSize = ref<number>(10)
const total = ref<number>(0)
const maxPage = ref<number>(1)
const filter = ref<string>('') //search data table

/**
 * ฟังก์ชั่น api เปลี่ยนหน้า
 * @param pageVal page
 * @param pageSizeVal pagesize
 *
 */
async function changePage(pageVal: number, pageSizeVal: number, key: string) {
  page.value = await pageVal
  pageSize.value = await pageSizeVal
  filter.value = await key
  functionFetch()
}

function functionFetch() {
  stores.tab === 'history' ? fetchlistHistory() : fetchlistTime()
}

/**
 * ฟังก์ชั่นดึงข้อมูลรายการประวัติการลงเวลาจาก api มาแสดง
 * @param loading แสดง loading ไหม true คือแสดง, false คือไม่แสดง
 */
async function fetchlistHistory() {
  showLoader()
  await http
    .get(
      config.API.history() +
        `?year=${year.value}&page=${page.value}&pageSize=${
          pageSize.value
        }&keyword=${filter.value ? filter.value : ''}`
    )
    .then(async (res) => {
      const data = res.data.result.data
      total.value = res.data.result.total
      maxPage.value = await Math.ceil(total.value / pageSize.value)
      fetchHistoryList(data) // ปิดกรณีมี total
    })
    .catch((err) => {
      messageError($q, err)
    })
    .finally(() => {
      hideLoader()
    })
}

async function fetchlistTime() {
  showLoader()
  await http
    .get(
      config.API.historyTime() +
        `?year=${year.value}&month=${month.value + 1}&page=${
          page.value
        }&pageSize=${pageSize.value}&keyword=${
          filter.value ? filter.value : ''
        }`
    )
    .then(async (res) => {
      const data = res.data.result.data
      total.value = res.data.result.total
      maxPage.value = await Math.ceil(total.value / pageSize.value)
      fetchHistoryList(data) // ปิดกรณีมี total
    })
    .catch((err) => {
      messageError($q, err)
    })
    .finally(() => {
      hideLoader()
    })
}

/**
 * function updateYear
 * @param y ปีที่อัปเดท
 */
async function updateYear(y: number, m: number) {
  year.value = y
  month.value = m
  stores.year = y
  functionFetch()
}

/** Hook*/
onMounted(async () => {
  await functionFetch()
})

watch(
  () => stores.tab,
  () => {
    page.value = 1
    filter.value = ''
    functionFetch()
  }
)
</script>
<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-12">
      <q-card flat class="row col-12 cardNone">
        <div
          class="bg-secondary text-white col-12 row items-center q-px-md q-py-sm"
        >
            <q-btn
              icon="arrow_back"
              round
              dense
              flat
              color="white"
              @click="router.go(-1)"
            />
          <span class="text-body1 text-weight-bold q-pl-md"
            >ประวัติการลงเวลา
          </span>
        </div>
        <div class="col-12 text-grey-9">
            <q-tabs
              v-model="stores.tab"
              dense
              align="left"
              inline-label
              class="rounded-borders"
              indicator-color="primary"
              active-bg-color="teal-1"
              active-class="text-primary"
            >
              <q-tab name="history" label="ประวัติการลงเวลา" />
              <q-tab name="time" label="รายการลงเวลากรณีพิเศษ" />
            </q-tabs>

            <q-separator />

            <q-tab-panels v-model="stores.tab" animated>
              <q-tab-panel name="history">
                <ToolBar
                  :fetchData="functionFetch"
                  @update:year="updateYear"
                  :tab="stores.tab"
                />
                <TableHistory
                  :fetchData="functionFetch"
                  :page-size="pageSize"
                  :total="total"
                  :page="page"
                  :paging="true"
                  @update:change-page="changePage"
                  :max-page="maxPage"
                  :tab="stores.tab"
                />
              </q-tab-panel>

              <q-tab-panel name="time">
                <ToolBar
                  :fetchData="functionFetch"
                  @update:year="updateYear"
                  :tab="stores.tab"
                />
                <TableHistory
                  :fetchData="functionFetch"
                  :page-size="pageSize"
                  :total="total"
                  :page="page"
                  :paging="true"
                  @update:change-page="changePage"
                  :max-page="maxPage"
                  :tab="stores.tab"
                />
              </q-tab-panel>
            </q-tab-panels>
            <!-- </q-card> -->
          <!-- <Table
            :fetchData="fetchlistHistory"
            :page-size="pageSize"
            :total="total"
            :page="page"
            :paging="true"
            @update:change-page="changePage"
            :max-page="maxPage"
          /> -->
        </div>
      </q-card>
    </div>
  </div>
</template>
