<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { QTableProps } from "quasar";
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 { checkPermission } from "@/utils/permissions";
import { useTransferDataStore } from "@/modules/05_placement/store";

import type { ResponseData } from "@/modules/06_retirement/interface/response/out";

import DialogSendToCommand from "@/modules/06_retirement/components/06_dismissOrder/DialogSendToCommand.vue";

/** use */
const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const transferStore = useTransferDataStore();
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  success,

  dialogRemove,
} = mixin;
const { statusText } = transferStore;
const modal = ref<boolean>(false);

/** คอลัมน์ที่แสดง */
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "positionLevel",
  "organizationPositionOld",
  "createdAt",
  "status",
]);

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

//ค้นหา คอลัมน์ คอลัมน์ที่แสดง
const rows = ref<ResponseData[]>([]);
const rows2 = ref<ResponseData[]>([]);
const filters = ref<ResponseData[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
  },
  {
    name: "positionLevel",
    align: "left",
    label: "ประเภทตำแหน่ง",
    sortable: true,
    field: "positionLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      let name = "";
      if (row.positionTypeOld && row.positionLevelOld) {
        name = `${row.positionTypeOld} (${row.positionLevelOld})`;
      } else if (row.positionTypeOld) {
        name = `${row.positionTypeOld}`;
      } else if (row.positionLevelOld) {
        name = `(${row.positionLevelOld})`;
      } else name = "-";
      return name;
    },
  },
  {
    name: "organizationPositionOld",
    align: "left",
    label: "ตำแหน่ง/สังกัดเดิม",
    sortable: true,
    field: "organizationPositionOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ดำเนินการ",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => date2Thai(val),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => statusText(val),
  },
]);

const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

function openModalOrder() {
  openModal();
  const row = filters.value.filter(
    (r: ResponseData) =>
      (r.status == "WAITTING" ||
        r.status == "PENDING" ||
        r.status == "APPROVE") &&
      r.organizationPositionOld &&
      r.positionTypeOld &&
      r.positionLevelOld &&
      r.positionNumberOld &&
      r.organization &&
      r.date
  );
  rows2.value = row;
}

//นำข้อมูลมาแสดง
async function getData() {
  showLoader();
  await http
    .get(config.API.retirementOut)
    .then((res: any) => {
      const data = res.data.result;
      rows.value = data;
      filters.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function clickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.outByid(id))
      .then(async () => {
        await getData();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  });
}

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

function closeModal() {
  modal.value = false;
}

onMounted(async () => {
  await getData();
});
</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"
            size="14px"
            flat
            round
            color="add"
            icon="mdi-account-arrow-right"
          >
            <q-tooltip>ส่งไปออกคำสั่งให้ออก</q-tooltip>
          </q-btn>

          <q-space />
          <div class="row q-col-gutter-sm">
            <q-input
              standout
              dense
              v-model="filterKeyword"
              ref="filterRef"
              outlined
              debounce="300"
              placeholder="ค้นหา"
            >
              <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 q-pt-sm">
          <d-table
            :columns="columns"
            :rows="rows"
            :filter="filterKeyword.trim()"
            row-key="id"
            :visible-columns="visibleColumns"
            v-model:pagination="pagination"
          >
            <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"
                    flat
                    dense
                    round
                    color="info"
                    icon="mdi-eye"
                    @click="
                      router.push(
                        `/retirement/dismiss-order-detail/${props.row.id}`
                      )
                    "
                  >
                    <q-tooltip>รายละเอียด</q-tooltip>
                  </q-btn>
                  <q-btn
                    v-if="
                      checkPermission($route)?.attrIsGet &&
                      checkPermission($route)?.attrIsUpdate
                    "
                    flat
                    dense
                    round
                    color="edit"
                    icon="edit"
                    @click="
                      router.push(`/retirement/dismiss-order/${props.row.id}`)
                    "
                  >
                    <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                  </q-btn>

                  <q-btn
                    v-if="checkPermission($route)?.attrIsDelete"
                    dense
                    flat
                    round
                    :color="
                      props.row.status == 'REPORT' || props.row.status == 'DONE'
                        ? 'grey'
                        : 'red-7'
                    "
                    @click="clickDelete(props.row.id)"
                    icon="mdi-delete"
                    :disable="
                      props.row.status == 'REPORT' || props.row.status == 'DONE'
                    "
                  >
                    <q-tooltip>ลบข้อมูล</q-tooltip>
                  </q-btn>
                </q-td>
                <q-td v-for="col in props.cols" :key="col.id">
                  <div v-if="col.name === 'no'">
                    {{ props.rowIndex + 1 }}
                  </div>

                  <div
                    v-else
                    :class="
                      col.name === 'organizationPositionOld'
                        ? 'table_ellipsis2'
                        : ''
                    "
                  >
                    {{ col.value ? 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"
    :fecthlistRecevice="getData"
  />
</template>
<style scoped lang="scss"></style>
