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

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

import type { QTableProps } from "quasar";
import type { DataQuery } from "@/components/Workflow/interface/request/Main";
import type { DataCommander } from "@/components/Workflow/interface/response/Main";
import type { PropsTable } from "@/interface/PropsTable";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const { dialogConfirm, showLoader, hideLoader, messageError } =
  useCounterMixin();

const modal = defineModel<boolean>("modal", { required: true });
const props = defineProps({
  stateId: { type: String, require: true },
  keycloakId: { type: String, require: true },
  sysName: { type: String, require: true },
  fetchData: { type: Function, require: true },
  type: { type: String, require: true },
});

const rejectName = computed(() =>
  props.sysName && ["SYS_RESIGN", "SYS_RESIGN_EMP"].includes(props.sysName)
    ? "ยับยั้ง"
    : "ไม่อนุมัติ",
);

/** table*/
const selected = ref<DataCommander[]>([]);
const rows = ref<DataCommander[]>([]);
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",
  },
]);
const pagination = ref<PropsTable.Pagination>({
  sortBy: "",
  descending: true,
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
});

const isAcceptSetting = ref<boolean>(false);
const isApproveSetting = ref<boolean>(false);
const isReasonSetting = ref<boolean>(false);

const formDataQuery = reactive<DataQuery>({
  isAct: false,
  keyword: "",
});

async function fetchLists() {
  showLoader();
  await http
    .put(config.API.workflow + `commander/${props.type}`, {
      ...formDataQuery,
      keycloakId: props.keycloakId,
      page: pagination.value.page,
      pageSize: pagination.value.rowsPerPage,
    })
    .then(async (res) => {
      pagination.value.rowsNumber = res.data.result.total;
      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ฟังก์ชันยืนยัน*/
function onSubmit() {
  dialogConfirm($q, async () => {
    showLoader();
    await http
      .post(config.API.workflow + `add-step`, {
        stateId: props.stateId,
        profileId: selected.value[0].id,
        isAcceptSetting: isAcceptSetting.value,
        isApproveSetting: isApproveSetting.value,
        isReasonSetting: isReasonSetting.value,
      })
      .then(async () => {
        await props.fetchData?.();
        onCloseModal();
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function onSearchData() {
  pagination.value.page = 1;
  fetchLists();
}

function onCloseModal() {
  modal.value = false;
  selected.value = [];
  rows.value = [];
  isAcceptSetting.value = false;
  isApproveSetting.value = false;
  isReasonSetting.value = false;
  formDataQuery.isAct = false;
  formDataQuery.keyword = "";
}

/**
 * ฟังก์ชันรับ request จากตาราง เมื่อมีการเปลี่ยน pagination
 * @param requestProps ข้อมูลการร้องขอจากตาราง
 */
function onTableRequest(requestProps: PropsTable.RequestProps) {
  const newPagination = requestProps?.pagination || requestProps;
  if (!newPagination?.page || !newPagination?.rowsPerPage) return;
  pagination.value = { ...newPagination };
}

watch(modal, (val) => {
  if (val) {
    fetchLists();
  }
});
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 700px">
      <q-form q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader :tittle="`เลือกรายชื่อ`" :close="onCloseModal" />
        <q-separator />

        <q-card-section>
          <div class="row q-col-gutter-sm items-start q-mb-sm">
            <div class="col-12 col-sm-4 col-md-4">
              <q-input
                v-model="formDataQuery.keyword"
                outlined
                clearable
                hide-bottom-space
                dense
                label="คำค้น"
                @clear="formDataQuery.keyword = ''"
              />
            </div>
            <q-checkbox
              keep-color
              v-model="formDataQuery.isAct"
              label="แสดงเฉพาะรักษาการแทน"
              color="primary"
              @update:model-value="onSearchData"
            >
              <q-tooltip>แสดงเฉพาะรักษาการแทน </q-tooltip>
            </q-checkbox>
            <q-space />

            <div class="col-12 col-sm-6 col-md-3">
              <q-btn
                color="primary"
                icon="search"
                label="ค้นหา"
                class="full-width q-pa-sm"
                @click.prevent="onSearchData"
              >
              </q-btn>
            </div>
          </div>
          <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="single"
            v-model:selected="selected"
            v-model:pagination="pagination"
            @request="onTableRequest"
          >
            <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, formDataQuery.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>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
          <div class="q-gutter-xs q-pt-sm">
            <div>
              <q-checkbox
                keep-color
                color="primary"
                dense
                v-model="isAcceptSetting"
                label="ให้เลือกรับทราบ"
                @update:model-value="
                  (isApproveSetting = false), (isReasonSetting = false)
                "
              />
            </div>
            <div v-if="!isAcceptSetting">
              <q-checkbox
                dense
                keep-color
                color="primary"
                v-model="isApproveSetting"
                :label="`ให้เลือกพิจารณา (อนุมัติ/${rejectName})`"
              />
            </div>
            <div>
              <q-checkbox
                dense
                keep-color
                color="primary"
                v-model="isReasonSetting"
                label="ให้แสดงความเห็นในเอกสาร"
              />
            </div>
          </div>
        </q-card-section>

        <q-separator />

        <q-card-actions align="right">
          <q-btn
            :label="
              props.type === 'operate'
                ? 'ส่งไปยังผู้บังคับบัญชา'
                : 'ส่งไปยังผู้มีอำนาจ'
            "
            color="public"
            type="submit"
            :disable="
              selected.length === 0 ||
              (!isAcceptSetting && !isApproveSetting && !isReasonSetting)
            "
          >
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style scoped></style>
