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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";

import type { AppointMainRows } from "@/modules/05_placement/interface/request/Main";
import DialogOrder from "@/modules/05_placement/components/probation/DialogOrder/DialogSendToCommand.vue";

const $q = useQuasar(); //ใช้ noti quasar
const mixin = useCounterMixin();
const { dialogRemove, showLoader, hideLoader, messageError, success } = mixin;
const router = useRouter();

const rows = ref<AppointMainRows[]>([]);
const rowsOrder = ref<AppointMainRows[]>([]);

const filterKeyword = ref<string>("");
const filterKeywordOrder = ref<string>("");
const modalOrder = ref<boolean>(false);

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

const visibleColumns = ref<string[]>(["no", "topic", "commandNo", "status"]);
/** หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "topic",
    align: "left",
    label: "หัวข้อ",
    sortable: true,
    field: "topic",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "commandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "commandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

/** ดึงข้อมูลหลัก */
async function getData() {
  showLoader();
  await http
    .get(config.API.appointMain)
    .then(async (res) => {
      const data = await res.data.data;
      rows.value = data;
      hideLoader();
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

/** reset ฟิลเตอร์ */
function resetFilter() {
  filterKeyword.value = "";
}

/**
 * เปิด หน้าราลละเอียด
 * @param type แยก (false = รายละเอียด)/(true = แก้ไข)
 */
function onNextPage(id: string, type: boolean) {
  router.push(`/probation${type ? "" : "-detail"}/assign/${id}`);
}

/** ลบข้อมูล
 * @param id id row
 */
function onDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    http
      .delete(config.API.appointMain + `/${id}`)
      .then(async (res) => {
        await getData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
        hideLoader();
      })
      .finally(() => {});
  });
}

/** แปลง EN to THAI */
function convertText(val: string) {
  switch (val) {
    case "PENDING":
      return "รอดำเนินการ";
    case "REPORT":
      return "ส่งไปออกคำสั่ง";
    case "DONE":
      return "เสร็จสิ้น";
    default:
      "-";
  }
}

function onSendOrder() {
  modalOrder.value = true;
  rowsOrder.value = rows.value.filter(
    (item: AppointMainRows) => item.status == "PENDING"
  );
}

function closeModal() {
  modalOrder.value = false;
  rowsOrder.value = [];
}
watch(
  () => pagination.value.rowsPerPage,
  async () => {
    await getData();
  }
);

onMounted(async () => {
  await getData();
});
</script>
<template>
  <q-card flat class="q-pa-sm">
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <div class="row">
          <div class="q-px-sm">
            <q-btn
              v-if="checkPermission($route)?.attrIsUpdate"
              flat
              round
              dense
              color="add"
              icon="mdi-account-arrow-right"
              @click="onSendOrder"
              ><q-tooltip>ส่งไปออกคำสั่ง</q-tooltip></q-btn
            >
          </div>

          <q-space />
          <q-input
            class="col-xs-12 col-sm-3 col-md-2 q-mr-sm"
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            debounce="300"
            placeholder="ค้นหา"
          >
            <template v-slot:append>
              <q-icon v-if="filterKeyword == ''" name="search" />
              <q-icon
                v-if="filterKeyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter"
              />
            </template>
          </q-input>

          <q-select
            v-model="visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columns"
            option-value="name"
            options-cover
            style="min-width: 150px"
            class="col-xs-12 col-sm-3 col-md-2"
          />
        </div>
      </div>
      <div class="col-12">
        <d-table
          ref="table"
          :columns="columns"
          :rows="rows"
          :filter="filterKeyword"
          row-key="Order"
          flat
          :visible-columns="visibleColumns"
          bordered
          :paging="true"
          dense
          v-model:pagination="pagination"
          :rows-per-page-options="[10, 25, 50, 100]"
          @update:pagination="updatePagination"
        >
          <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">
                <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"
                  flat
                  dense
                  round
                  color="info"
                  icon="mdi-eye"
                  @click="onNextPage(props.row.id, false)"
                >
                  <q-tooltip>รายละเอียด</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    props.row.status == 'PENDING' &&
                    checkPermission($route)?.attrIsUpdate &&
                    checkPermission($route)?.attrIsGet
                  "
                  flat
                  dense
                  round
                  color="edit"
                  icon="edit"
                  @click="onNextPage(props.row.id, true)"
                >
                  <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    props.row.status == 'PENDING' &&
                    checkPermission($route)?.attrIsDelete
                  "
                  flat
                  dense
                  round
                  color="red"
                  icon="delete"
                  @click="onDelete(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 == 'no'">
                  {{
                    (pagination.page - 1) * pagination.rowsPerPage +
                    props.rowIndex +
                    1
                  }}
                </div>
                <div v-else-if="col.name == 'status'">
                  {{ props.row.status ? convertText(props.row.status) : "-" }}
                </div>

                <div v-else>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
          <template v-slot:pagination="scope">
            ทั้งหมด {{ total }} รายการ
            <q-pagination
              v-model="pagination.page"
              active-color="primary"
              color="dark"
              :max="Number(totalList)"
              size="sm"
              boundary-links
              direction-links
              :max-pages="5"
              @update:model-value="getData"
            ></q-pagination>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>

  <DialogOrder
    v-model:modal="modalOrder"
    :close-modal="closeModal"
    v-model:rows="rowsOrder"
    v-model:filter-keyword="filterKeywordOrder"
    :get-data="getData"
  />
</template>
