<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";
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 http from "@/plugins/http";
import config from "@/app.config";

import DialogSendToCommand from "@/modules/11_discipline/components/7_ListSuspend/DialogSendToCommand.vue";

/** 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",
  "position",
  "positionLevel",
  "organization",
  "dateTotal",
  "descriptionSuspend",
  "status",
]);

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

//ค้นหา คอลัมน์ คอลัมน์ที่แสดง
const rows2 = ref<dataType[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    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: "position",
    align: "left",
    label: "ตำแหน่งในสายงาน",
    sortable: true,
    field: "position",
    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",
  },
  {
    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 closeModal = () => (modal.value = false);

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

const currentPage = ref<number>(1);
const maxPage = ref<number>(1);
const page = ref<number>(1);
const rowsPerPage = ref<number>(10);

/**
 *pagination ของตาราง
 */
const pagination = ref({
  descending: false,
  page: page.value,
  rowsPerPage: rowsPerPage.value,
});

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

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

/**
 * ยืนยัน ส่งไปออกคำสั่ง
 * @param data ข้อมูลรายบุคคล
 */
function onSubmit(data: dataType[], type: string) {
  const dataMapId = data.map((item: dataType) => item.id);
  showLoader();
  http
    .put(`${config.API.suspendReport()}/${type}`, {
      id: dataMapId,
    })
    .then((res) => {
      success($q, `ส่งข้อมูลไปออกคำสั่งสำเร็จ`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      getList();
    });
}

watch(
  () => currentPage.value,
  () => {
    rowsPerPage.value = pagination.value.rowsPerPage;
    getList();
  }
);

watch(
  () => pagination.value.rowsPerPage,
  () => {
    rowsPerPage.value = pagination.value.rowsPerPage;
    currentPage.value = 1;
    getList();
  }
);

function filterFn() {
  getList();
}

/** เรียกใช้งานเมื่อเริ่มหน้าเว็ป */
onMounted(() => {
  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
            @click="openModalOrder"
            size="14px"
            flat
            round
            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 v-if="filterKeyword == ''" name="search" />
              <q-icon
                v-if="filterKeyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="resetFilter"
              />
            </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"
            options-cover
            style="min-width: 150px"
            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"
            v-model:pagination="pagination"
            :rows-per-page-options="[10, 25, 50, 100]"
          >
            <template v-slot:pagination="scope">
              <q-pagination
                v-model="currentPage"
                active-color="primary"
                color="dark"
                :max="Number(maxPage)"
                size="sm"
                boundary-links
                direction-links
              ></q-pagination>
            </template>
            <template v-slot:header="props">
              <q-tr :props="props">
                <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" class="cursor-pointer">
                <q-td
                  v-for="col in props.cols"
                  :key="col.name"
                  :props="props"
                  @click="router.push(`/discipline-suspend/${props.row.id}`)"
                >
                  <div v-if="col.name === 'no'">
                    {{
                      (currentPage - 1) * Number(pagination.rowsPerPage) +
                      props.rowIndex +
                      1
                    }}
                  </div>
                  <div v-else-if="col.name === 'title'" class="table_ellipsis">
                    {{ props.row.title }}
                  </div>
                  <div
                    v-else-if="col.name === 'organization'"
                    class="table_ellipsis"
                  >
                    {{ 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"
    :closeModal="closeModal"
    :rows2="rows2"
    v-model:filterKeyword2="filterKeyword2"
    @returnPerson="onSubmit"
  />
</template>
<style scoped lang="scss"></style>
