<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 $q = useQuasar();
const mixin = useCounterMixin();
const route = useRoute();
const {
  showLoader,
  hideLoader,
  messageError,
  success,
  dialogConfirm,
  dialogMessageNotify,
} = mixin;

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  type: String,
  profileType: String,
  keycloakUserId: String,
  fetchDetailLeave: Function,
  idCheck: Array,
  commandersList: Array,
});

const pageId = ref<string>(route.params.id 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",
    format(val, row) {
      return val ?? row.posExecutiveName;
    },
    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() {
  showLoader();
  await http
    .put(config.API.workflowCommanderOperate, {
      pageSize: pagination.value.rowsPerPage,
      page: pagination.value.page,
      keyword: keyword.value,
      isAct: isAct.value,
      keycloakId: props.keycloakUserId,
      type:
        props.profileType?.toLocaleLowerCase() === "officer"
          ? "officer"
          : "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() {
  dialogConfirm($q, async () => {
    const body = selected.value.map((items: any, index: any) => ({
      seq: index,
      prefix: items.prefix ?? "",
      firstName: items.firstName ?? "",
      lastName: items.lastName ?? "",
      positionName: items.position ?? "",
      positionSign: items.positionSign,
      profileId: items.id,
      keycloakId: items.keycloakId,
      positionLeaveName:
        items.posType == "บริหาร" || items.posType == "อำนวยการ"
          ? (items.posType ?? "") + (items.posLevel ?? "")
          : items.posLevel ?? "",
      posExecutiveName: items.posExecutiveName ?? "",
      organizationName: [
        items.orgChild4 ?? "",
        items.orgChild3 ?? "",
        items.orgChild2 ?? "",
        items.orgChild1 ?? "",
        items.orgRoot ?? "",
      ]
        .filter(Boolean)
        .join(" "),
    }));

    const hasCommander = selected.value.some((e) =>
      props.commandersList?.some((i: any) => i === e.id)
    );

    if (hasCommander) {
      dialogMessageNotify($q, "ไม่สามารถเลือกได้ เนื่องจากเลือกรายชื่อซ้ำ");
      return;
    }

    showLoader();
    await http
      .post(
        config.API.addApproverByType(
          props.type?.toLocaleLowerCase() as string,
          "officer",
          pageId.value
        ),
        body.length > 0 ? body : []
      )
      .then(async () => {
        await props.fetchDetailLeave?.(pageId.value);
        closeDialog();
        success($q, "บันทึกสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function closeDialog() {
  modal.value = false;
  rows.value = [];
  selected.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"
                >
                  <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>
