<script setup lang="ts">
import { ref, onMounted } 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 { usePagination } from "@/composables/usePagination";
import {
  checkPermission,
  checkPermissionList,
  checkPermissionCreate,
} from "@/utils/permissions";

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

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

/** use */
const dataStore = useDisciplineSuspendStore();
const $q = useQuasar();
const router = useRouter();
const { messageError, showLoader, hideLoader, date2Thai, convertDateToAPI } =
  useCounterMixin();
const { pagination, params, onRequest } = usePagination("", getList);

const date = ref<any>(null);
const employeeClass = ref<string>("OFFICER");
const employeeClassOption = ref<DataOption[]>([
  // { id: "", name: "ทั้งหมด" },
  { id: "OFFICER", name: "ข้าราชการ กทม. สามัญ" },
  { id: "EMPLOYEE", name: "ลูกจ้างประจำ กทม." },
]);
const modal = ref<boolean>(false);

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

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

//ค้นหา คอลัมน์ คอลัมน์ที่แสดง
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: "profileType",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: false,
    field: "profileType",
    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: "firstName",
    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",
    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: "startDateSuspend",
    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: false,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function openModal() {
  modal.value = true;
}

/** เปิด 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();
  const paramsNew = {
    ...params.value,
    keyword: filterKeyword.value.trim(),
    profileType: employeeClass.value,
    ...(date.value?.length === 2 && {
      startDate: convertDateToAPI(date.value[0]),
      endDate: convertDateToAPI(date.value[1]),
    }),
  };

  await http
    .get(config.API.suspendMain, { params: paramsNew })
    .then(async (res) => {
      const result = await res.data.result;
      pagination.value.rowsNumber = result.total;
      await dataStore.getData(result.data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

function convertType(val: string) {
  const data = val?.toLocaleUpperCase();
  switch (data) {
    case "OFFICER":
      return "ข้าราชการ กทม. สามัญ";
    case "EMPLOYEE":
      return "ลูกจ้างประจำ กทม.";
  }
}

/** เรียกใช้งานเมื่อเริ่มหน้าเว็ป */
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>
    <div class="row q-pa-md q-col-gutter-sm">
      <div class="col-12">
        <div class="row q-col-gutter-sm">
          <div class="col-xs-12 col-sm-7 col-md-6 col-lg-5">
            <div class="row col-12 q-col-gutter-sm items-center">
              <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
                <q-select
                  v-model="employeeClass"
                  outlined
                  dense
                  options-dense
                  emit-value
                  map-options
                  :options="employeeClassOption"
                  option-value="id"
                  option-label="name"
                  label="ประเภทตำแหน่ง"
                  @update:model-value="getList"
                />
              </div>
              <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
                <datepicker
                  v-model="date"
                  :locale="'th'"
                  autoApply
                  range
                  :enableTimePicker="false"
                  @update:model-value="getList()"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      class="bg-white"
                      dense
                      outlined
                      :label="`${'วันที่เริ่มต้น-สิ้นสุดคำสั่ง'}`"
                      :model-value="
                        date
                          ? `${date2Thai(date[0])} - ${date2Thai(date[1])}`
                          : ''
                      "
                    >
                      <template v-slot:prepend>
                        <q-icon
                          size="18px"
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        ></q-icon>
                      </template>
                      <template v-slot:append>
                        <q-icon
                          v-if="date !== null"
                          name="clear"
                          class="cursor-pointer"
                          @click.prevent.stop="(date = null), getList()"
                        />
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col-1 row justify-center">
                <q-btn
                  v-if="
                    checkPermission($route)?.attrIsUpdate &&
                    checkPermissionList(['COMMAND']) &&
                    checkPermissionCreate('COMMAND')
                  "
                  @click="openModalOrder"
                  flat
                  round
                  dense
                  color="primary"
                  icon="mdi-account-arrow-right"
                >
                  <q-tooltip>ส่งไปออกคำสั่ง</q-tooltip>
                </q-btn>
              </div>
            </div>
          </div>

          <q-space />
          <div class="col-xs-12 col-sm-4 col-md-5 col-lg-4">
            <div class="row q-col-gutter-sm items-center">
              <div class="col-7">
                <q-input
                  for="#search"
                  standout
                  dense
                  v-model="filterKeyword"
                  ref="filterRef"
                  outlined
                  placeholder="ค้นหา"
                  @keydown.enter.prevent="getSearch"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>
              </div>
              <div class="col-5">
                <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"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12">
        <p-table
          :columns="dataStore.columns"
          :rows="dataStore.rows"
          row-key="id"
          :visible-columns="dataStore.visibleColumns"
          :rows-per-page-options="[10, 25, 50, 100]"
          v-model:pagination="pagination"
          @request="onRequest"
        >
          <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-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'">
                  {{ props.rowIndex + 1 }}
                </div>
                <div
                  v-else-if="col.name === 'firstName'"
                  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 === 'profileType'">
                  {{
                    props.row.profileType
                      ? convertType(props.row.profileType.toUpperCase())
                      : "-"
                  }}
                </div>
                <div
                  v-else-if="col.name === 'organization'"
                  class="text-html"
                  style="width: 250px"
                >
                  {{ props.row.organization ? props.row.organization : "-" }}
                </div>
                <div v-else>
                  {{ col.value ?? "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </p-table>
      </div>
    </div>
  </q-card>

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