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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useDisciplineSuspendStore } from "@/modules/11_discipline/store/SuspendStore";

import type { dataType } from "@/modules/11_discipline/interface/response/Suspend";
import type { QTableProps } from "quasar";

import DialogSendToCommand from "@/modules/11_discipline/components/7_ListSuspend/DialogSendToCommand.vue";
import { checkPermission } from "@/utils/permissions";

/** use */
const dataStore = useDisciplineSuspendStore();
const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader, success } = mixin;

const modal = ref<boolean>(false);

/** คอลัมน์ที่แสดง */
const visibleColumns = ref<string[]>([
  "no",
  "title",
  "name",
  "positionType",
  "positionLevel",
  "organization",
  "dateTotal",
  "descriptionSuspend",
  "status",
]);

//ค้นหา คอลัมน์ คอลัมน์ที่แสดง
const filterKeyword = ref<string>("");
const filterRef = ref<any>(null);

//ค้นหา คอลัมน์ คอลัมน์ที่แสดง
const rows2 = ref<dataType[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "title",
    align: "left",
    label: "เรื่องร้องเรียน",
    sortable: true,
    field: "title",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "name",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val, row) => {
      return row.positionLevel
        ? `${row.positionType} (${row.positionLevel})`
        : "-";
    },
  },
  {
    name: "organization",
    align: "left",
    label: "สังกัด",
    sortable: true,
    field: "organization",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateTotal",
    align: "left",
    label: "วันที่เริ่มต้น-สิ้นสุดคำสั่ง",
    sortable: true,
    field: "dateTotal",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "descriptionSuspend",
    align: "left",
    label: "เหตุที่ถูกสั่งพักราชการ",
    sortable: true,
    field: "descriptionSuspend",
    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",
  },
]);

const openModal = () => (modal.value = true);

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

function resetFilter() {
  filterKeyword.value = "";
  filterRef.value.focus();
  getSearch();
}

/** เปิด popup ส่งไปออกคำสั่ง โดย PENDING*/
function openModalOrder() {
  openModal();
  const dataMap = dataStore.rows.filter(
    (r: dataType) =>
      r.statusEn == "PENDING" &&
      r.startDateSuspend !== null &&
      r.endDateSuspend !== null &&
      r.name &&
      r.organization &&
      r.positionType &&
      r.positionLevel &&
      r.posNo &&
      r.organization
  );
  rows2.value = dataMap;
}

/** ดึงข้อมูลหน้าหลัก */
async function getList() {
  showLoader();
  await http
    .get(
      config.API.suspendMain(
        pagination.value.page,
        pagination.value.rowsPerPage,
        filterKeyword.value.trim()
      )
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      await dataStore.getData(data);
      hideLoader();
    })
    .catch((e) => {
      messageError($q, e);
      hideLoader();
    })
    .finally(() => {});
}

function filterFn() {
  getSearch();
}

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

function getSearch() {
  pagination.value.page = 1;
  getList();
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    getSearch();
  }
);

/** เรียกใช้งานเมื่อเริ่มหน้าเว็ป */
onMounted(async () => {
  await getList();
  dataStore.columns = columns.value;
  dataStore.visibleColumns = visibleColumns.value;
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายชื่อผู้ถูกพักราชการ
  </div>
  <q-card flat bordered class="col-12 q-mt-sm">
    <q-separator />
    <div class="row q-pa-md">
      <div class="col-12">
        <div class="row col-12">
          <q-btn
            v-if="checkPermission($route)?.attrIsUpdate"
            @click="openModalOrder"
            flat
            round
            dense
            color="add"
            icon="mdi-account-arrow-right"
          >
            <q-tooltip>ส่งไปออกคำสั่ง</q-tooltip>
          </q-btn>
          <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="filterFn"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>

          <q-select
            v-model="dataStore.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"
            class="col-xs-12 col-sm-3 col-md-2 q-ml-sm"
          />
        </div>

        <div class="col-12 q-pt-sm">
          <d-table
            :columns="dataStore.columns"
            :rows="dataStore.rows"
            row-key="id"
            :visible-columns="dataStore.visibleColumns"
            :rows-per-page-options="[10, 25, 50, 100]"
            @update:pagination="updatePagination"
          >
            <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="getList"
              ></q-pagination>
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th auto-width />
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
                <!-- <q-th auto-width /> -->
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props">
                <q-td auto-width>
                  <q-btn
                    v-if="checkPermission($route)?.attrIsGet"
                    @click="
                      router.push(`/discipline-suspend-detail/${props.row.id}`)
                    "
                    flat
                    dense
                    round
                    color="info"
                    icon="mdi-eye"
                  >
                    <q-tooltip>รายละเอียด</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="
                      checkPermission($route)?.attrIsUpdate &&
                      checkPermission($route)?.attrIsGet
                    "
                    @click="router.push(`/discipline-suspend/${props.row.id}`)"
                    flat
                    dense
                    round
                    color="edit"
                    icon="edit"
                  >
                    <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 === 'name'" class="table_ellipsis">
                    {{ props.row.prefix ? props.row.prefix : ""
                    }}{{ props.row.firstName ? props.row.firstName : "" }}
                    {{ props.row.lastName ? props.row.lastName : "" }}
                  </div>
                  <div v-else-if="col.name === 'title'" class="table_ellipsis">
                    {{ props.row.title ? props.row.title : "-" }}
                  </div>
                  <div
                    v-else-if="col.name === 'organization'"
                    class="table_ellipsis"
                  >
                    {{ props.row.organization ? props.row.organization : "-" }}
                  </div>
                  <div v-else>
                    {{ col.value ?? "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </div>
      </div>
    </div>
  </q-card>

  <DialogSendToCommand v-model:modal="modal" :rows="rows2" />
</template>
<style scoped lang="scss"></style>
