<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useQuasar } from "quasar";

import { useRouter, useRoute } from "vue-router";
import {
  checkPermission,
  checkPermissionList,
  checkPermissionCreate,
} from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useTransferDataStore } from "@/modules/05_placement/store";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type { ResponseData } from "@/modules/05_placement/interface/response/Transfer";

import DialogOrders from "@/modules/05_placement/components/Transfer/DialogOrders.vue"; //ส่งไปออกคำสั่งขอโอน

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const mixin = useCounterMixin();
const store = useTransferDataStore();
const { statusText, filterOption } = useTransferDataStore();
const {
  date2Thai,
  messageError,
  showLoader,
  hideLoader,
  onSearchDataTable,
  dialogRemove,
  success,
} = mixin;

const modal = ref<boolean>(false); //ส่งไปออกคำสั่ง
const dataTransfer = ref<ResponseData[]>([]); //ช่อมูลรายการขอโอน
const status = ref<string>("");

//Table
const rows = ref<ResponseData[]>([]); //รายการขอโอน
const filter = ref(""); //คำค้นหารายการขอโอน
const rowsOrder = ref<ResponseData[]>([]); //รายการส่งไปออกคำสั่ง
const rowsOrderData = ref<ResponseData[]>([]); //รายการส่งไปออกคำสั่ง
const filterOrder = ref<string>(""); //คำค้นหารายการส่งไปออกคำสั่ง
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: "positionNumberOld",
    align: "left",
    label: "เลขที่ตำแหน่งเดิม",
    sortable: true,
    field: "positionNumberOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posType",
    align: "left",
    label: "ตำแหน่งประเภทเดิม",
    sortable: true,
    field: "posType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.positionTypeOld
        ? `${row.positionTypeOld}${
            row.positionLevelOld ? `(${row.positionLevelOld})` : ""
          }`
        : "";
    },
  },

  {
    name: "organizationPositionOld",
    align: "left",
    label: "ตำแหน่ง/สังกัดเดิม",
    sortable: true,
    field: "organizationPositionOld",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return row.organizationPositionOld
        ? `${row.organizationPositionOld.replace(/\n/g, " ")}`
        : "-";
    },
  },
  {
    name: "organization",
    align: "left",
    label: "หน่วยงานที่ขอโอนไป",
    sortable: true,
    field: "organization",
    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) {
      return date2Thai(val);
    },
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (val) => statusText(val),
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "posType",
  "positionNumberOld",
  "organizationPositionOld",
  "organization",
  "status",
  "createdAt",
]);

const isPermissionDelete = computed(() => {
  return (status: string) => {
    return (
      checkPermission(route)?.attrOwnership === "OWNER" &&
      !store.statusDelete.includes(status)
    );
  };
});

/** ฟังก์ชันดึงข้อมูรายการขอโอน*/
async function fetchData() {
  showLoader();
  await http
    .get(config.API.transfer + `?status=${status.value}`)
    .then(async (res) => {
      const data = await res.data.result;
      rows.value = data;
      dataTransfer.value = data;
      onSearch();
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันส่งไปออกคำสั่ง
 * ค้นหารายชื่อออกคำสั่งตามสถานะ อนุมัติ (APPROVE)
 */
function openModalOrder() {
  const row = dataTransfer.value.filter(
    (r: ResponseData) =>
      r.status == "APPROVE" &&
      r.organizationPositionOld &&
      r.positionTypeOld &&
      r.positionLevelOld &&
      r.positionNumberOld &&
      r.organization &&
      r.date
  );
  rowsOrder.value = row;
  rowsOrderData.value = row;
  modal.value = true;
}

/** ฟังก์ชันปิด popup ส่งไปออกคำสั่ง*/
function closeModal() {
  modal.value = false;
  filterOrder.value = "";
}

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

function handleDelete(id: string) {
  dialogRemove($q, async () => {
    try {
      showLoader();
      await http.delete(config.API.transfer + `/admin/${id}`);
      await fetchData();
      success($q, "ลบข้อมูลสำเร็จ");
    } catch (error) {
      messageError($q, error);
    } finally {
      hideLoader();
    }
  });
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 * จะเรียกใช้ fetchData เพื่อดึงข้อมูลรายการขอโอน
 */
onMounted(async () => {
  await fetchData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">รายการขอโอน</div>
  <q-card flat bordered class="col-12">
    <div class="row q-pa-md q-col-gutter-sm">
      <div class="col-12">
        <div class="row q-col-gutter-xs items-end">
          <div class="col-xs-12 col-sm-6 col-md-6 col-lg-3">
            <div class="row q-col-gutter-sm">
              <div class="col-xs-11 col-sm-7 col-md-7 col-lg-7">
                <q-select
                  :model-value="status ? status : 'ทั้งหมด'"
                  outlined
                  dense
                  label="สถานะ"
                  :options="store.statusOp.filter((item:any)=> item.id !== 'PENDING')"
                  emit-value
                  map-options
                  option-label="name"
                  option-value="id"
                  fill-input
                  use-input
                  hide-selected
                  bg-color="white"
                  @filter="(inputValue:any,doneFn:Function) => filterOption(inputValue, doneFn) "
                  @update:model-value="(value:string)=>{(status = value),fetchData()}"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        ไม่มีข้อมูล
                      </q-item-section>
                    </q-item>
                  </template>
                  <template v-if="status" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop.prevent="(status = ''), fetchData()"
                      class="cursor-pointer"
                      style="opacity: 0.6"
                    />
                  </template>
                </q-select>
              </div>

              <div class="col-xs-1 col-sm-5 col-md-5 col-lg-5">
                <q-btn
                  v-if="
                    checkPermission($route)?.attrIsUpdate &&
                    checkPermissionList(['COMMAND']) &&
                    checkPermissionCreate('COMMAND')
                  "
                  @click="openModalOrder"
                  flat
                  round
                  color="primary"
                  icon="mdi-account-arrow-right"
                >
                  <q-tooltip>ส่งไปออกคำสั่ง</q-tooltip>
                </q-btn>
              </div>
            </div>
          </div>

          <div class="col-xs-0 col-sm-1 col-md-3 col-lg-5"></div>

          <div class="col-xs-12 col-sm-5 col-md-3 col-lg-4">
            <div class="row q-col-gutter-sm">
              <!-- Search Input -->
              <div class="col-xs-12 col-sm-7 col-md-7 col-lg-7">
                <q-input
                  standout
                  dense
                  v-model="filter"
                  ref="filterRef"
                  outlined
                  placeholder="ค้นหา"
                  @keyup.enter="onSearch"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>
              </div>

              <div class="col-xs-12 col-sm-5 col-md-5 col-lg-5">
                <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"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12">
        <d-table
          :columns="columns"
          :rows="rows"
          row-key="id"
          :visible-columns="visibleColumns"
        >
          <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.stop.prevent="
                    router.push(`/placement/transfer/${props.row.id}`)
                  "
                >
                  <q-tooltip>รายละเอียด</q-tooltip>
                </q-btn>

                <q-btn
                  v-if="isPermissionDelete(props.row.status)"
                  flat
                  round
                  dense
                  icon="mdi-delete"
                  color="red"
                  @click.prevent="handleDelete(props.row.id)"
                >
                  <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-if="col.name === 'organizationPositionOld'"
                  class="text-html"
                >
                  {{ props.row.organizationPositionOld ?? "-" }}
                </div>

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

  <DialogOrders
    v-model:modal="modal"
    :fetch-data="fetchData"
    :close-modal="closeModal"
    v-model:rows="rowsOrder"
    v-model:rowsData="rowsOrderData"
  />
</template>
<style scoped lang="scss"></style>
