<script setup lang="ts">
import { ref, watch } from "vue";
import { useQuasar, type QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { getColumnLabel } from "@/utils/function";
import { useCounterMixin } from "@/stores/mixin";

import DialogHeader from "@/components/DialogHeader.vue";
import { useRoute } from "vue-router";

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  type: String,
  profileType: String,
  keycloakUserId: String,
  getData: Function,
  idCheck: Array,
});
const $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();
const {
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogConfirm,
  dialogMessageNotify,
} = mixin;

const pageId = ref<string>(route.params.id as string);
const routeName = ref<string>(route?.name as string);

const keyword = ref<string>("");
const isAct = ref<boolean>(false);

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

const rows = ref<any[]>([]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "fullName",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullName",
    format(val, row) {
      return `${row.prefix}${row.firstName} ${row.lastName}`;
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "posNo",
    align: "left",
    label: "เลขที่ตำแหน่ง",
    sortable: true,
    field: "posNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "positionSign",
    align: "left",
    label: "ตำแหน่งใต้ลายเซ็น",
    sortable: true,
    field: "positionSign",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

function onSearchData() {
  getSearch();
}

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

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

async function getData() {
  const url =
    props.type == "COMMANDER"
      ? config.API.workflowCommanderOperate
      : config.API.workflowCommanderSign;
  showLoader();
  await http
    .put(url, {
      pageSize: pagination.value.rowsPerPage,
      page: pagination.value.page,
      keyword: keyword.value,
      isAct: isAct.value,
      keycloakId: props.keycloakUserId,
      type: props.profileType === "officer" ? props.profileType : "employee",
    })
    .then(async (res) => {
      const data = res.data.result;
      totalList.value = Math.ceil(data.total / pagination.value.rowsPerPage);
      total.value = data.total;
      rows.value = data.data;
      selected.value = data.data.filter((items: any) => {
        return props.idCheck?.some((i: any) => i === items.id);
      });
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onSubmit() {
  // if (selected.value.length !== 0) {
  dialogConfirm($q, async () => {
    if (props.keycloakUserId) {
      const body = selected.value.map((items: any, index: any) => ({
        seq: index,
        prefix: items.prefix,
        firstName: items.firstName,
        lastName: items.lastName,
        positionName: items.position,
        profileId: items.id,
        keycloakId: items.keycloakId,
        PositionExecutiveName: items.positionSign,
        // ...(items.positionSign
        //   ? { PositionExecutiveName: items.positionSign }
        //   : {}),
      }));
      showLoader();
      const profileSuffix =
        (props.profileType?.toLocaleLowerCase() as string) === "officer"
          ? ""
          : "-employee";

      const apiEndpoint =
        routeName.value === "resignReject" ||
        routeName.value === "resignRejectEMP"
          ? config.API.addResignCancel(
              profileSuffix,
              props.type?.toLocaleLowerCase() as string,
              pageId.value
            )
          : config.API.addResign(
              profileSuffix,
              props.type?.toLocaleLowerCase() as string,
              pageId.value
            );
      await http
        .post(apiEndpoint, body)
        .then(async () => {
          await props.getData?.(pageId.value);
          closeDialog();
          success($q, "บันทึกสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    } else {
      closeDialog();
    }
  });
  // } else {
  //   dialogMessageNotify($q, "กรุณาเลือกอย่างน้อย 1 คน");
  // }
}

function closeDialog() {
  modal.value = false;
  rows.value = [];
  selected.value = [];
  keyword.value = "";
}

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

watch(
  () => modal.value,
  () => {
    if (modal.value) {
      getSearch();
    }
  }
);
</script>
<template>
  <q-dialog v-model="modal" persistent>
    <q-card class="col-12" style="width: 80%">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            props.type == 'APPROVER' ? 'เลือกผู้มีอำนาจ' : 'เลือกผู้บังคับบัญชา'
          "
          :close="closeDialog"
        />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-12">
              <div class="row q-gutter-x-xs">
                <q-input
                  dense
                  outlined
                  label="ค้นหา"
                  v-model="keyword"
                  style="width: 300px"
                >
                  <template v-slot:append>
                    <q-icon name="search"></q-icon>
                  </template>
                </q-input>
                <q-checkbox
                  keep-color
                  v-model="isAct"
                  label="แสดงเฉพาะรักษาการแทน"
                  color="primary"
                  @update:model-value="onSearchData"
                >
                  <q-tooltip>แสดงเฉพาะรักษาการแทน </q-tooltip>
                </q-checkbox>
                <q-space />
                <q-btn
                  color="primary"
                  icon="search"
                  label="ค้นหา"
                  class="q-pa-sm"
                  @click.prevent="onSearchData"
                  style="width: 200px"
                >
                </q-btn>
              </div>
            </div>
            <div class="col-12 text-red">
              {{
                props.type == "APPROVER"
                  ? ""
                  : "*ลำดับการอนุมัติขึ้นอยู่กับลำดับการคลิกเลือก"
              }}
            </div>
            <div class="col-12">
              <d-table
                ref="table"
                :columns="columns"
                :rows="rows"
                row-key="key"
                flat
                bordered
                :paging="true"
                dense
                :rows-per-page-options="[10, 25, 50, 100]"
                :selection="props.type == 'COMMANDER' ? `multiple` : `single`"
                v-model:selected="selected"
                @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="getData"
                  ></q-pagination>
                </template>

                <template v-slot:header-selection="scope">
                  <q-checkbox
                    keep-color
                    color="primary"
                    dense
                    v-model="scope.checkBox"
                  />
                </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">{{
                        getColumnLabel(col, isAct)
                      }}</span>
                    </q-th>
                  </q-tr>
                </template>
                <template v-slot:body="props">
                  <q-tr :props="props" class="cursor-pointer">
                    <q-td>
                      <q-checkbox
                        keep-color
                        color="primary"
                        dense
                        v-model="props.selected"
                      />
                    </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>
                        {{ col.value ? col.value : "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>
              </d-table>
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
