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

import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useCommandListStore } from "@/modules/18_command/store/ListStore";
import http from "@/plugins/http";
import config from "@/app.config";

import type {
  ItemTabs,
  DataOption,
} from "@/modules/18_command/interface/index/Main";
import type { FormQuery } from "@/modules/18_command/interface/request/Main";

import DialogFormCommand from "@/modules/18_command/components/Main/DialogFormCommand.vue";
import TableList from "@/modules/18_command/components/Main/TableMain.vue";

const $q = useQuasar();
const store = useCommandListStore();
const { showLoader, hideLoader, messageError } = useCounterMixin();

//รายการ Tab รายการคำสั่ง
const tabsManu = ref<ItemTabs[]>([
  { label: "แบบร่าง", name: "DRAFT" },
  { label: "รอผู้มีอำนาจลงนามอนุมัติ", name: "PENDING" },
  { label: "รอออกคำสั่ง", name: "WAITING" },
  { label: "ออกคำสั่งเสร็จสิ้น", name: "REPORTED" },
  { label: "ลบ", name: "CANCEL" },
]);
//ฟอร์มช้อมูลการค้นหา
const queryParams = reactive<FormQuery>({
  page: 1, //หน้า
  pageSize: 10, //จำนวนต่อหน้า
  year: new Date().getFullYear(), //ปีงบประมาณ
  keyword: "", //คำค้นหา
  commandTypeId: "",
});
const commandOpMain = ref<DataOption[]>([
  {
    id: "",
    name: "ทั้งหมด",
  },
]);
const commandOp = ref<DataOption[]>([]);

const modalAdd = ref<boolean>(false); // เพิ่มคำสั่ง

/**
 * ฟังก์ชันดึงข้อมูลรายการคำสั่ง
 */
async function fetchListCommand() {
  store.rows = [];
  showLoader();
  await http
    .get(config.API.commandList, {
      params: {
        ...queryParams,
        status: store.tabsMain,
        keyword: queryParams.keyword.trim(),
      },
    })
    .then(async (res) => {
      const data = await res.data.result;
      store.rows = data.data;
      store.total = data.total;
      store.maxPage = Math.ceil(data.total / queryParams.pageSize);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันค้นหาข้อมูลรายการประเภทคำสั่ง
 * @param val คำที่ค้องการค้นหา
 * @param update function จาก quasar
 */
function filterSelector(val: string, update: Function) {
  update(() => {
    commandOp.value = commandOpMain.value.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

onMounted(async () => {
  const data = await store.fetchCommandType();
  if (data) {
    commandOpMain.value.push(...data);
    commandOp.value = commandOpMain.value;
  }
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">รายการคำสั่ง</div>

  <!-- toolbar -->
  <q-card class="q-pa-md">
    <div class="row q-col-gutter-sm">
      <div class="col-12 row">
        <datepicker
          menu-class-name="modalfix"
          v-model="queryParams.year"
          :locale="'th'"
          autoApply
          year-picker
          :enableTimePicker="false"
          @update:model-value="(queryParams.page = 1), fetchListCommand()"
        >
          <template #year="{ year }">{{ year + 543 }}</template>
          <template #year-overlay-value="{ value }">{{
            parseInt(value + 543)
          }}</template>
          <template #trigger>
            <q-input
              dense
              outlined
              hide-bottom-space
              :model-value="
                queryParams.year == null ? null : queryParams.year + 543
              "
              :label="`${'ปีงบประมาณ'}`"
            >
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>

        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          flat
          round
          dense
          icon="add"
          color="primary"
          @click.prevent="modalAdd = true"
        />
      </div>

      <div class="col-12 row">
        <q-card bordered class="col-12 filter-card q-pa-sm">
          <div class="row col-12 q-col-gutter-sm">
            <q-select
              :clearable="queryParams.commandTypeId !== ''"
              @clear="
                (queryParams.page = 1),
                  (queryParams.commandTypeId = ''),
                  (commandOp = commandOpMain)
              "
              :class="queryParams.commandTypeId ? 'select_ellipsis3' : ''"
              v-model="queryParams.commandTypeId"
              :label="`${'ประเภทคำสั่ง'}`"
              dense
              emit-value
              map-options
              option-label="name"
              :options="commandOp"
              option-value="id"
              lazy-rules
              use-input
              @update:model-value="(queryParams.page = 1), fetchListCommand()"
              outlined
              hide-selected
              fill-input
              style="width: 620px"
              @filter="(inputValue:string,
              doneFn:Function) => filterSelector(inputValue, doneFn) "
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
            <q-space />
            <q-input
              dense
              outlined
              v-model="queryParams.keyword"
              label="ค้นหา"
              @keydown.enter="(queryParams.page = 1), fetchListCommand()"
            >
              <template v-slot:append> <q-icon name="search" /> </template
            ></q-input>

            <q-select
              dense
              multiple
              outlined
              emit-value
              map-options
              options-dense
              option-value="name"
              style="min-width: 140px"
              v-model="store.visibleColumns"
              :options="store.columns"
              :display-value="$q.lang.table.columns"
            />
          </div>
        </q-card>
      </div>
    </div>
  </q-card>

  <!-- Tabs -->
  <q-card class="q-mt-sm">
    <q-card-section style="padding: 0px">
      <q-separator />
      <q-tabs
        v-model="store.tabsMain"
        inline-label
        align="justify"
        indicator-color="primary"
        active-color="primary bg-teal-1"
      >
        <q-tab
          v-for="(tab, index) in tabsManu"
          :key="index"
          :name="tab.name"
          :label="tab.label"
        />
      </q-tabs>
      <q-separator />

      <q-tab-panels v-model="store.tabsMain" animated>
        <q-tab-panel
          v-for="(panel, index) in tabsManu"
          :key="index"
          :name="panel.name"
        >
          <TableList
            :fetch-list="fetchListCommand"
            v-model:page="queryParams.page"
            v-model:pageSize="queryParams.pageSize"
          />
        </q-tab-panel>
      </q-tab-panels>
    </q-card-section>
  </q-card>

  <DialogFormCommand v-model:modal="modalAdd" :is-copy="false" />
</template>

<style scoped></style>
