<script setup lang="ts">
import { ref, useAttrs, onMounted } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** ImportStores*/
import { useRoundDataStore } from "@/modules/09_leave/stores/RoundStores";
import { useCounterMixin } from "@/stores/mixin";

/** ImportComponents*/
import DialogForm from "@/modules/09_leave/components/01_RoundTime/DialogForm.vue";
import { checkPermission } from "@/utils/permissions";

const $q = useQuasar(); //ใช้ noti quasar
const attrs = ref<any>(useAttrs());
const mixin = useCounterMixin();
const dataStore = useRoundDataStore();
const { fetchData } = dataStore;
const { showLoader, hideLoader, messageError, dialogRemove, success,onSearchDataTable } = mixin;

const modal = ref<boolean>(false);
const isRead = ref<boolean>(false);
const detailData = ref<any>();
const editCheck = ref<string>("");

/** ค้นหาข้อมูลใน Table */
const filterKeyword = ref<string>("");
const filterRef = ref<HTMLInputElement | null>(null);
const resetFilter = () => {
  filterKeyword.value = "";
  if (filterRef.value) {
    filterRef.value.focus();
  }
};

/** Function get ข้อมูลรายการรอบการปฏิบัติงาน */
async function fetchListRound() {
  showLoader();
  await http
    .get(config.API.roundDutytime())
    .then(async (res) => {
      const data = await res.data.result;
      await fetchData(data);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * Function delete รายการรอบการปฏิบัติงาน
 * @param id ค่า ID ของ rows
 */
function onClickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.roundDutytimeByid(id))
      .then(async () => {
        await fetchListRound();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 *
 * @param data ข้อมูลรอบการปฏิบัติงาน
 * @param check action แก้ไข,เพิ่ม
 */
function openModal(data: any, check: string) {
  modal.value = true;
  editCheck.value = check;
  if (check === "edit") {
    detailData.value = data;
  }
}

/**
 *
 * @param data ข้อมูลรอบการปฏิบัติงาน
 * @param check action แก้ไข,เพิ่ม
 */
function openModalDetail(data: any, check: string) {
  modal.value = true;
  editCheck.value = check;
  if (check === "edit") {
    isRead.value = true;
    detailData.value = data;
  }
}

/** Function ปิด popup รายละเอียดและการเพิ่ม*/
function closeDialog() {
  modal.value = false;
  editCheck.value = "add";
}

/**  pagination */
const pagination = ref({
  descending: false,
  page: 1,
  rowsPerPage: 10,
});

function onSearch() {
  dataStore.rows = onSearchDataTable(
    filterKeyword.value,
    dataStore.rowsData,
    dataStore.columns ? dataStore.columns : []
  );
}

/** Hook*/
onMounted(async () => {
  await fetchListRound();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการรอบการปฏิบัติงาน
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pa-md">
    <div class="row col-12 q-col-gutter-sm q-mb-sm">
      <div>
        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          for="#addInvestigatefacts"
          @click="openModal(null, 'add')"
          dense
          flat
          round
          color="primary"
          icon="mdi-plus"
        >
          <q-tooltip>เพิ่มรอบการปฏิบัติงาน</q-tooltip>
        </q-btn>
      </div>
      <q-space />

      <q-input
        for="#search"
        class="col-xs-12 col-sm-3 col-md-2"
        standout
        dense
        v-model="filterKeyword"
        ref="filterRef"
        outlined
        placeholder="ค้นหา"
        @keydown.enter.prevent="onSearch"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>

      <q-select
        for="#select"
        v-model="dataStore.visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="dataStore.columns"
        option-value="name"
        style="min-width: 140px"
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </div>
    <div class="col-12">
      <d-table
        ref="table"
        :columns="dataStore.columns"
        :rows="dataStore.rows"
        row-key="interrogated"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        v-bind="attrs"
        :visible-columns="dataStore.visibleColumns"
        v-model:pagination="pagination"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width></q-th>
            <q-th
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              style="color: #000000; font-weight: 500"
            >
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                dense
                flat
                round
                color="info"
                icon="mdi-eye"
                @click.prevent="openModalDetail(props.row, 'edit')"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
              <q-btn
                v-if="
                  checkPermission($route)?.attrIsGet &&
                  checkPermission($route)?.attrIsUpdate
                "
                dense
                flat
                round
                color="edit"
                icon="edit"
                @click.prevent="openModal(props.row, 'edit')"
                ><q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
              <q-btn
                v-if="checkPermission($route)?.attrIsDelete"
                dense
                flat
                round
                color="red"
                icon="delete"
                @click="onClickDelete(props.row.id)"
                ><q-tooltip>ลบข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name === 'isActive'" class="text-center">
                <q-icon
                  v-if="props.row.isActive === true"
                  name="mdi-check"
                  size="sm"
                  color="positive"
                />
                <q-icon
                  v-if="props.row.isActive === false"
                  name="mdi-close"
                  size="sm"
                  color="grey"
                />
              </div>
              <div v-else-if="col.name === 'round'">
                <q-icon
                  v-if="props.row.isDefault === true"
                  name="mdi-bookmark"
                  size="xs"
                  color="primary"
                >
                  <q-tooltip>เวลา Default</q-tooltip>
                </q-icon>
                <q-icon v-else />
                {{ col.value }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>
  <DialogForm
    :modal="modal"
    :closeDialog="closeDialog"
    :editCheck="editCheck"
    :detailData="detailData"
    :fetchData="fetchListRound"
    v-model:isRead="isRead"
  />
</template>
<style scoped lang="scss">
.q-table tbody td:before.no-background {
  background: none;
}
</style>
