<script setup lang="ts">
import { onMounted, ref } 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,
  checkPermissionList,
  checkPermissionCreate,
} 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,
  onSearchDataTable,
} = mixin;
const router = useRouter();

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

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

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",
    format(val, row) {
      return convertText(row.status);
    },
  },
]);

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

/**
 * เปิด หน้าราลละเอียด
 * @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 () => {
        await getData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

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

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

function closeModal() {
  modalOrder.value = false;
  rowsOrder.value = [];
  rowsOrderData.value = [];
}

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

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

<template>
  <q-card flat>
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <div class="row q-col-gutter-sm">
          <div class="q-px-sm">
            <q-btn
              v-if="
                checkPermission($route)?.attrIsUpdate &&
                checkPermissionList(['COMMAND']) &&
                checkPermissionCreate('COMMAND')
              "
              flat
              round
              dense
              color="primary"
              icon="mdi-account-arrow-right"
              @click="onSendOrder"
              ><q-tooltip>ส่งไปออกคำสั่ง</q-tooltip></q-btn
            >
          </div>

          <q-space />
          <q-input
            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
            v-model="visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columns"
            option-value="name"
            style="min-width: 140px"
          />
        </div>
      </div>
      <div class="col-12">
        <d-table
          ref="table"
          :columns="columns"
          :rows="rows"
          row-key="Order"
          flat
          :visible-columns="visibleColumns"
          bordered
          :paging="true"
          dense
          v-model:pagination="pagination"
          :rows-per-page-options="[10, 25, 50, 100]"
        >
          <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="
                    checkPermission($route)?.attrIsUpdate &&
                    checkPermission($route)?.attrIsGet
                  "
                  flat
                  :disable="props.row.status !== 'PENDING'"
                  :color="props.row.status !== 'PENDING' ? 'grey-5' : 'edit'"
                  dense
                  round
                  icon="edit"
                  @click="onNextPage(props.row.id, true)"
                >
                  <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="checkPermission($route)?.attrIsDelete"
                  :disable="props.row.status !== 'PENDING'"
                  :color="props.row.status !== 'PENDING' ? 'grey-5' : 'red'"
                  flat
                  dense
                  round
                  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'">
                  {{ props.rowIndex + 1 }}
                </div>

                <div v-else>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>

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